file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/3/0x42D133BFb13625fF67F0D78394E025461799b734/sources/EthlingUtils.sol
|
randomly assigns wearables to customizable slots with values [1,20]. [1,10] are rarer than [11,20] assumes that wearables with ID [1,20] have already been created slots the slot customizability for the avatar hash random values, uses indices [7,18] return bit mask of all assigned wearables in each slot, excluding 13th slot/ slots = 0b1011001001101 for each slot EXCEPT auxiliary1 and auxiliary 2
|
function assignWearables(uint16 slots, bytes32 hash) internal pure returns (uint256) {
uint256 worn = 0;
uint8 rand;
for (uint256 i = 0; i < MAX_SLOTS() - 2; i++) {
rand = uint8(hash[31 - i - MAX_SLOTS()]);
worn |= uint256(rand - 245) << (i * 16);
worn |= uint256((rand - 46) / 20 + 11) << (i * 16);
}
}
| 8,134,570 |
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.7.5;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iL1NFTBridge } from "./interfaces/iL1NFTBridge.sol";
import { iL2NFTBridge } from "./interfaces/iL2NFTBridge.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/* Library Imports */
import { CrossDomainEnabled } from "@eth-optimism/contracts/contracts/libraries/bridge/CrossDomainEnabled.sol";
import { Lib_PredeployAddresses } from "@eth-optimism/contracts/contracts/libraries/constants/Lib_PredeployAddresses.sol";
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { ERC721Holder } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
/* Contract Imports */
import { IL1StandardERC721 } from "../standards/IL1StandardERC721.sol";
/* External Imports */
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
/**
* @title L1NFTBridge
* @dev The L1 NFT Bridge is a contract which stores deposited L1 ERC721
* tokens that are in use on L2. It synchronizes a corresponding L2 Bridge, informing it of deposits
* and listening to it for newly finalized withdrawals.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract L1NFTBridge is iL1NFTBridge, CrossDomainEnabled, ERC721Holder, ReentrancyGuardUpgradeable, PausableUpgradeable {
using SafeMath for uint;
/********************************
* External Contract References *
********************************/
address public owner;
address public l2NFTBridge;
// Default gas value which can be overridden if more complex logic runs on L2.
uint32 public depositL2Gas;
enum Network { L1, L2 }
// Info of each NFT
struct PairNFTInfo {
address l1Contract;
address l2Contract;
Network baseNetwork; // L1 or L2
}
// Maps L1 token to tokenId to L2 token contract deposited for the native L1 NFT
mapping(address => mapping (uint256 => address)) public deposits;
// Maps L1 NFT address to NFTInfo
mapping(address => PairNFTInfo) public pairNFTInfo;
/***************
* Constructor *
***************/
// This contract lives behind a proxy, so the constructor parameters will go unused.
constructor()
CrossDomainEnabled(address(0))
{}
/**********************
* Function Modifiers *
**********************/
modifier onlyOwner() {
require(msg.sender == owner || owner == address(0), 'Caller is not the owner');
_;
}
modifier onlyInitialized() {
require(address(messenger) != address(0), "Contract has not yet been initialized");
_;
}
/******************
* Initialization *
******************/
/**
* @dev transfer ownership
*
* @param _newOwner new owner of this contract
*/
function transferOwnership(
address _newOwner
)
public
onlyOwner()
{
owner = _newOwner;
}
/**
* @dev Configure gas.
*
* @param _depositL2Gas default finalized deposit L2 Gas
*/
function configureGas(
uint32 _depositL2Gas
)
public
onlyOwner()
onlyInitialized()
{
depositL2Gas = _depositL2Gas;
}
/**
* @param _l1messenger L1 Messenger address being used for cross-chain communications.
* @param _l2NFTBridge L2 NFT bridge address.
*/
function initialize(
address _l1messenger,
address _l2NFTBridge
)
public
onlyOwner()
initializer()
{
require(messenger == address(0), "Contract has already been initialized.");
messenger = _l1messenger;
l2NFTBridge = _l2NFTBridge;
owner = msg.sender;
configureGas(1400000);
__Context_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
}
/***
* @dev Add the new NFT pair to the pool
* DO NOT add the same NFT token more than once.
*
* @param _l1Contract L1 NFT contract address
* @param _l2Contract L2 NFT contract address
* @param _baseNetwork Network where the NFT contract was created
*
*/
function registerNFTPair(
address _l1Contract,
address _l2Contract,
string memory _baseNetwork
)
public
onlyOwner()
{
// use with caution, can register only once
PairNFTInfo storage pairNFT = pairNFTInfo[_l1Contract];
// l2 NFT address equal to zero, then pair is not registered.
require(pairNFT.l2Contract == address(0), "L2 NFT Address Already Registered");
// _baseNetwork can only be L1 or L2
require(
keccak256(abi.encodePacked((_baseNetwork))) == keccak256(abi.encodePacked(("L1"))) ||
keccak256(abi.encodePacked((_baseNetwork))) == keccak256(abi.encodePacked(("L2"))),
"Invalid Network"
);
Network baseNetwork;
if (keccak256(abi.encodePacked((_baseNetwork))) == keccak256(abi.encodePacked(("L1")))) {
baseNetwork = Network.L1;
} else {
baseNetwork = Network.L2;
}
pairNFTInfo[_l1Contract] =
PairNFTInfo({
l1Contract: _l1Contract,
l2Contract: _l2Contract,
baseNetwork: baseNetwork
});
}
/**************
* Depositing *
**************/
// /**
// * @inheritdoc iL1NFTBridge
// */
function depositNFT(
address _l1Contract,
uint256 _tokenId,
uint32 _l2Gas,
bytes calldata _data
)
external
virtual
override
nonReentrant()
whenNotPaused()
{
_initiateNFTDeposit(_l1Contract, msg.sender, msg.sender, _tokenId, _l2Gas, _data);
}
// /**
// * @inheritdoc iL1NFTBridge
// */
function depositNFTTo(
address _l1Contract,
address _to,
uint256 _tokenId,
uint32 _l2Gas,
bytes calldata _data
)
external
virtual
override
nonReentrant()
whenNotPaused()
{
_initiateNFTDeposit(_l1Contract, msg.sender, _to, _tokenId, _l2Gas, _data);
}
/**
* @dev Performs the logic for deposits by informing the L2 Deposited Token
* contract of the deposit and calling a handler to lock the L1 token. (e.g. transferFrom)
*
* @param _l1Contract Address of the L1 NFT contract we are depositing
* @param _from Account to pull the deposit from on L1
* @param _to Account to give the deposit to on L2
* @param _tokenId NFT token Id to deposit.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function _initiateNFTDeposit(
address _l1Contract,
address _from,
address _to,
uint256 _tokenId,
uint32 _l2Gas,
bytes calldata _data
)
internal
{
PairNFTInfo storage pairNFT = pairNFTInfo[_l1Contract];
require(pairNFT.l2Contract != address(0), "Can't Find L2 NFT Contract");
if (pairNFT.baseNetwork == Network.L1) {
// This check could be bypassed by a malicious contract via initcode,
// but it takes care of the user error we want to avoid.
require(!Address.isContract(msg.sender), "Account not EOA");
// When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future
// withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if
// _from is an EOA or address(0).
IERC721(_l1Contract).safeTransferFrom(
_from,
address(this),
_tokenId
);
// Construct calldata for _l2Contract.finalizeDeposit(_to, _amount)
bytes memory message = abi.encodeWithSelector(
iL2NFTBridge.finalizeDeposit.selector,
_l1Contract,
pairNFT.l2Contract,
_from,
_to,
_tokenId,
_data
);
// Send calldata into L2
sendCrossDomainMessage(
l2NFTBridge,
_l2Gas,
message
);
deposits[_l1Contract][_tokenId] = pairNFT.l2Contract;
} else {
address l2Contract = IL1StandardERC721(_l1Contract).l2Contract();
require(pairNFT.l2Contract == l2Contract, "L2 NFT Contract Address Error");
// When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2
// usage
address NFTOwner = IL1StandardERC721(_l1Contract).ownerOf(_tokenId);
require(
msg.sender == NFTOwner || IL1StandardERC721(_l1Contract).getApproved(_tokenId) == msg.sender ||
IL1StandardERC721(pairNFT.l2Contract).isApprovedForAll(NFTOwner, msg.sender)
);
IL1StandardERC721(_l1Contract).burn(_tokenId);
// Construct calldata for l2NFTBridge.finalizeDeposit(_to, _amount)
bytes memory message;
message = abi.encodeWithSelector(
iL2NFTBridge.finalizeDeposit.selector,
_l1Contract,
l2Contract,
_from,
_to,
_tokenId,
_data
);
// Send calldata into L2
sendCrossDomainMessage(
l2NFTBridge,
_l2Gas,
message
);
}
emit NFTDepositInitiated(_l1Contract, pairNFT.l2Contract, _from, _to, _tokenId, _data);
}
// /**
// * @inheritdoc iL1NFTBridge
// */
function finalizeNFTWithdrawal(
address _l1Contract,
address _l2Contract,
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external
override
onlyFromCrossDomainAccount(l2NFTBridge)
{
PairNFTInfo storage pairNFT = pairNFTInfo[_l1Contract];
if (pairNFT.baseNetwork == Network.L1) {
// needs to verify comes from correct l2Contract
require(deposits[_l1Contract][_tokenId] == _l2Contract, "Incorrect Burn");
// When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer
IERC721(_l1Contract).safeTransferFrom(address(this), _to, _tokenId);
emit NFTWithdrawalFinalized(_l1Contract, _l2Contract, _from, _to, _tokenId, _data);
} else {
// Check the target token is compliant and
// verify the deposited token on L2 matches the L1 deposited token representation here
if (
// check with interface of IL1StandardERC721
ERC165Checker.supportsInterface(_l1Contract, 0x3899b238) &&
_l2Contract == IL1StandardERC721(_l1Contract).l2Contract()
) {
// When a deposit is finalized, we credit the account on L2 with the same amount of
// tokens.
IL1StandardERC721(_l1Contract).mint(_to, _tokenId);
emit NFTWithdrawalFinalized(_l1Contract, _l2Contract, _from, _to, _tokenId, _data);
} else {
bytes memory message = abi.encodeWithSelector(
iL2NFTBridge.finalizeDeposit.selector,
_l1Contract,
_l2Contract,
_to, // switched the _to and _from here to bounce back the deposit to the sender
_from,
_tokenId,
_data
);
// Send message up to L1 bridge
sendCrossDomainMessage(
l2NFTBridge,
depositL2Gas,
message
);
emit NFTWithdrawalFailed(_l1Contract, _l2Contract, _from, _to, _tokenId, _data);
}
}
}
/******************
* Pause *
******************/
/**
* Pause contract
*/
function pause() external onlyOwner() {
_pause();
}
/**
* UnPause contract
*/
function unpause() external onlyOwner() {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.7.5;
pragma experimental ABIEncoderV2;
/**
* @title iL1NFTBridge
*/
interface iL1NFTBridge {
event NFTDepositInitiated (
address indexed _l1Contract,
address indexed _l2Contract,
address indexed _from,
address _to,
uint256 _tokenId,
bytes _data
);
event NFTWithdrawalFinalized (
address indexed _l1Contract,
address indexed _l2Contract,
address indexed _from,
address _to,
uint256 _tokenId,
bytes _data
);
event NFTWithdrawalFailed (
address indexed _l1Contract,
address indexed _l2Contract,
address indexed _from,
address _to,
uint256 _tokenId,
bytes _data
);
function depositNFT(
address _l1Contract,
uint256 _tokenId,
uint32 _l2Gas,
bytes calldata _data
)
external;
function depositNFTTo(
address _l1Contract,
address _to,
uint256 _tokenId,
uint32 _l2Gas,
bytes calldata _data
)
external;
function finalizeNFTWithdrawal(
address _l1Contract,
address _l2Contract,
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.7.5;
pragma experimental ABIEncoderV2;
/**
* @title iL2NFTBridge
*/
interface iL2NFTBridge {
// add events
event WithdrawalInitiated (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _tokenId,
bytes _data
);
event DepositFinalized (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _tokenId,
bytes _data
);
event DepositFailed (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _tokenId,
bytes _data
);
function withdraw(
address _l2Contract,
uint256 _tokenId,
uint32 _l1Gas,
bytes calldata _data
)
external;
function withdrawTo(
address _l2Contract,
address _to,
uint256 _tokenId,
uint32 _l1Gas,
bytes calldata _data
)
external;
function finalizeDeposit(
address _l1Contract,
address _l2Contract,
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.9.0;
/* Interface Imports */
import {ICrossDomainMessenger} from './ICrossDomainMessenger.sol';
/**
* @title CrossDomainEnabled
* @dev Helper contract for contracts performing cross-domain communications
*
* Compiler used: defined by inheriting contract
* Runtime target: defined by inheriting contract
*/
contract CrossDomainEnabled {
/*************
* Variables *
*************/
// Messenger contract used to send and recieve messages from the other domain.
address public messenger;
/***************
* Constructor *
***************/
/**
* @param _messenger Address of the CrossDomainMessenger on the current layer.
*/
constructor(address _messenger) {
messenger = _messenger;
}
/**********************
* Function Modifiers *
**********************/
/**
* Enforces that the modified function is only callable by a specific cross-domain account.
* @param _sourceDomainAccount The only account on the originating domain which is
* authenticated to call this function.
*/
modifier onlyFromCrossDomainAccount(address _sourceDomainAccount) {
require(
msg.sender == address(getCrossDomainMessenger()),
'OVM_XCHAIN: messenger contract unauthenticated'
);
require(
getCrossDomainMessenger().xDomainMessageSender() == _sourceDomainAccount,
'OVM_XCHAIN: wrong sender of cross-domain message'
);
_;
}
/**********************
* Internal Functions *
**********************/
/**
* Gets the messenger, usually from storage. This function is exposed in case a child contract
* needs to override.
* @return The address of the cross-domain messenger contract which should be used.
*/
function getCrossDomainMessenger()
internal
virtual
returns (ICrossDomainMessenger)
{
return ICrossDomainMessenger(messenger);
}
/**q
* Sends a message to an account on another domain
* @param _crossDomainTarget The intended recipient on the destination domain
* @param _message The data to send to the target (usually calldata to a function with
* `onlyFromCrossDomainAccount()`)
* @param _gasLimit The gasLimit for the receipt of the message on the target domain.
*/
function sendCrossDomainMessage(
address _crossDomainTarget,
uint32 _gasLimit,
bytes memory _message
) internal {
getCrossDomainMessenger().sendMessage(
_crossDomainTarget,
_message,
_gasLimit
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_PredeployAddresses
*/
library Lib_PredeployAddresses {
// solhint-disable max-line-length
address internal constant L2_TO_L1_MESSAGE_PASSER =
0x4200000000000000000000000000000000000000;
address internal constant L1_MESSAGE_SENDER =
0x4200000000000000000000000000000000000001;
address internal constant DEPLOYER_WHITELIST =
0x4200000000000000000000000000000000000002;
address payable internal constant OVM_ETH =
payable(0x4200000000000000000000000000000000000006);
// solhint-disable-next-line max-line-length
address internal constant L2_CROSS_DOMAIN_MESSENGER =
0x4200000000000000000000000000000000000007;
address internal constant LIB_ADDRESS_MANAGER =
0x4200000000000000000000000000000000000008;
address internal constant PROXY_EOA =
0x4200000000000000000000000000000000000009;
address internal constant L2_STANDARD_BRIDGE =
0x4200000000000000000000000000000000000010;
address internal constant SEQUENCER_FEE_WALLET =
0x4200000000000000000000000000000000000011;
address internal constant L2_STANDARD_TOKEN_FACTORY =
0x4200000000000000000000000000000000000012;
address internal constant L1_BLOCK_NUMBER =
0x4200000000000000000000000000000000000013;
address internal constant OVM_GAS_PRICE_ORACLE =
0x420000000000000000000000000000000000000F;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return
_supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) && _supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
internal
view
returns (bool[] memory)
{
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.7.5;
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
interface IL1StandardERC721 is IERC165, IERC721 {
function l2Contract() external returns (address);
function mint(address _to, uint256 _tokenId) external;
function burn(uint256 _tokenId) external;
event Mint(address indexed _account, uint256 _tokenId);
event Burn(uint256 _tokenId);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title ICrossDomainMessenger
*/
interface ICrossDomainMessenger {
/**********
* Events *
**********/
event SentMessage(
address indexed target,
address sender,
bytes message,
uint256 messageNonce,
uint256 gasLimit
);
event RelayedMessage(bytes32 indexed msgHash);
event FailedRelayedMessage(bytes32 indexed msgHash);
/*************
* Variables *
*************/
function xDomainMessageSender() external view returns (address);
/********************
* Public Functions *
********************/
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes calldata _message,
uint32 _gasLimit
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal 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;
}
|
Configure gas. _depositL2Gas default finalized deposit L2 Gas/
|
function configureGas(
uint32 _depositL2Gas
)
public
onlyOwner()
onlyInitialized()
{
depositL2Gas = _depositL2Gas;
}
| 278,954 |
pragma solidity ^0.5.0;
import "./Adminable.sol";
import "./SafeMath.sol";
/** @title Online Marketplace. */
contract MarketPlace is Adminable {
using SafeMath for uint256;
struct Product {
string name;
uint price;
uint quantity;
uint sales;
bool isOpen;
mapping(address => uint) shoppers;
}
struct Front {
string name;
bool isOpen;
string[] productKeys;
mapping(string => bool) isProduct;
mapping(string => Product) products;
}
struct Store {
string name;
uint balance;
string[] frontKeys;
mapping(string => bool) isFront;
mapping(string => Front) fronts;
}
mapping(address => bool) public isStore;
mapping(address => Store) public stores;
address[] public storeKeys;
// modifier onlyAdmin() {
// require(msg.sender == admin, "caller is not admin");
// _;
// }
modifier onlyStoreOwner() {
require(isStore[msg.sender], "caller is not store owner");
_;
}
modifier storeExist(address _owner) {
require(isStore[_owner], "the store does not exist.");
_;
}
event LogNewStore(address indexed owner, string name);
event LogNewFront(address indexed owner, string front);
event LogNewProduct(address indexed owner, string front, string product);
event LogBuyProduct(address indexed shopper, address owner, string front, string product, uint amount);
event LogWithdraw(address indexed owner, uint newBalance);
constructor() public {
// admin = msg.sender;
}
/** @dev Create a store by admin.
* @param _owner address of store owner.
* @param _name a unique name of store.
*/
function createStore(address _owner, string memory _name) public onlyAdmin stopInEmergency {
require(!isStore[_owner], "duplicate store.");
isStore[_owner] = true;
stores[_owner] = Store(_name, 0, new string[](0));
storeKeys.push(_owner);
emit LogNewStore(_owner, _name);
}
/** @dev Create a storefront by store owner .
* @param _name a unique name of storefront.
* @param _isOpen is the storefront available or not.
*/
function createFront(string memory _name, bool _isOpen) public onlyStoreOwner stopInEmergency {
require(!stores[msg.sender].isFront[_name], "front name is already created.");
Store storage store = stores[msg.sender];
store.isFront[_name] = true;
store.fronts[_name] = Front(_name, _isOpen, new string[](0));
store.frontKeys.push(_name);
emit LogNewFront(msg.sender, _name);
}
/** @dev Toggle storefront isOpen for shoppers.
* @param _name a unique name of storefront.
*/
function toggleFrontActive(string memory _name) public onlyStoreOwner stopInEmergency {
require(stores[msg.sender].isFront[_name], "front name doesn't exist.");
Store storage s = stores[msg.sender];
Front storage f = s.fronts[_name];
f.isOpen = !f.isOpen;
}
/** @dev Create a product of storefront by store owner .
* @param _front the name of storefront.
* @param _product a unique name of product.
* @param _price price of product.
* @param _quantity quantity of product.
* @param _isOpen is the product available or not.
*/
function createProduct(string memory _front, string memory _product, uint _price, uint _quantity, bool _isOpen) public onlyStoreOwner stopInEmergency {
Store storage s = stores[msg.sender];
require(s.isFront[_front], "front doesn't exist.");
Front storage f = s.fronts[_front];
require(!f.isProduct[_product], "product name is already created.");
f.isProduct[_product] = true;
f.products[_product] = Product(_product, _price, _quantity, 0, _isOpen);
f.productKeys.push(_product);
emit LogNewProduct(msg.sender, _front, _product);
}
/** @dev Toggle the product of storefront isOpen for shoppers.
* @param _front a unique name of storefront.
* @param _product a unique name of product.
*/
function toggleFrontActive(string memory _front, string memory _product) public onlyStoreOwner stopInEmergency {
require(stores[msg.sender].isFront[_front], "front name doesn't exist.");
Store storage s = stores[msg.sender];
Front storage f = s.fronts[_front];
require(f.isProduct[_product], "product name doesn't exist.");
Product storage p = f.products[_product];
p.isOpen = !p.isOpen;
}
/** @dev Store owner can withdraw his balance.
* @param _amount amount of balance to be withdraw.
*/
function withdraw(uint _amount) public onlyStoreOwner stopInEmergency {
require(_amount <= stores[msg.sender].balance, "insufficient balance.");
stores[msg.sender].balance = stores[msg.sender].balance.sub(_amount);
msg.sender.transfer(_amount);
emit LogWithdraw(msg.sender, stores[msg.sender].balance);
}
/** @dev Force store owners to withdraw their balance.
* @param _owner address of store owner.
*/
function forcedWithdraw(address payable _owner) public onlyAdmin onlyInEmergency {
require(stores[_owner].balance > 0, "the balance is zero.");
uint amount = stores[_owner].balance;
stores[_owner].balance = 0;
_owner.transfer(amount);
}
/** @dev Shopper can purches a product.
* @param _owner the address of store owner.
* @param _front the unique name of storefront.
* @param _product the unique name of product.
* @param _amount purches amount of product.
*/
function buyProduct(address _owner, string memory _front, string memory _product, uint _amount) public payable stopInEmergency {
require(isStore[_owner], "the store doesn't exist.");
Store storage s = stores[_owner];
require(s.isFront[_front], "the front doesn't exist.");
Front storage f = s.fronts[_front];
require(f.isOpen, "the front is not open.");
require(f.isProduct[_product], "the product doesn't exist.");
Product storage p = f.products[_product];
require(p.isOpen, "the product is not open.");
require(_amount <= p.quantity, "out of amount.");
require(msg.value >= _amount * p.price, "not enough value.");
uint refund = msg.value.sub(_amount.mul(p.price));
if (refund > 0) {
msg.sender.transfer(refund);
}
p.quantity = p.quantity.sub(_amount);
p.sales = p.sales.add(_amount);
p.shoppers[msg.sender] = p.shoppers[msg.sender].add(_amount);
s.balance = s.balance.add(msg.value.sub(refund));
emit LogBuyProduct(msg.sender, _owner, _front, _product, _amount);
}
/** @dev Get store count.
* @return The store count.
*/
function getStoreCount() public view returns(uint) {
return storeKeys.length;
}
/** @dev Get a store information by index.
* @param _index a index of store.
* @return owner The address of store owner.
* @return name The name of store.
* @return balance The balance of store.
*/
function getStoreAtIndex(uint _index) public view returns(address owner, string memory name, uint balance) {
require(_index < storeKeys.length, "out of index.");
owner = storeKeys[_index];
name = stores[storeKeys[_index]].name;
balance = stores[storeKeys[_index]].balance;
}
/** @dev Get a store information by address.
* @param _owner an address of store owner.
* @return name The name of store.
* @return balance The balance of store.
*/
function getStoreDetail(address _owner) public view returns(string memory name, uint balance) {
require(isStore[_owner], "the owner's store doesn't exist");
name = stores[_owner].name;
balance = stores[_owner].balance;
}
/** @dev Get storefront count.
* @param _owner the address of store owner.
* @return The storefront count.
*/
function getFrontsCount(address _owner) public view returns(uint) {
require(isStore[_owner], "the owner's store doesn't exist");
return stores[_owner].frontKeys.length;
}
/** @dev Get a storefront information by index.
* @param _owner the address of store owner.
* @param _index a index of storefront.
* @return name The name of storefront.
* @return isOpen The status of storefront.
*/
function getFrontAtIndex(address _owner, uint _index) public view returns(string memory name, bool isOpen) {
require(isStore[_owner], "the owner's store doesn't exist");
Store storage s = stores[_owner];
require(_index < s.frontKeys.length, "out of index.");
Front memory f = s.fronts[s.frontKeys[_index]];
name = f.name;
isOpen = f.isOpen;
}
/** @dev Get product count of a storefront.
* @param _owner the address of store owner.
* @param _front the unique name of storefront.
* @return The product count of the storefront.
*/
function getProductsCount(address _owner, string memory _front) public view returns(uint) {
require(isStore[_owner], "the owner's store doesn't exist");
Store storage s = stores[_owner];
require(s.isFront[_front], "the owner's front doesn't exist");
Front memory f = s.fronts[_front];
return f.productKeys.length;
}
/** @dev Get a product information by index.
* @param _owner the address of store owner.
* @param _front the unique name of storefront.
* @param _index a index of product of storefront.
* @return name The name of product.
* @return price The price of product.
* @return quantity The quantity of product.
* @return sales The sales of product.
* @return isOpen The status of product.
*/
function getProductAtIndex(address _owner, string memory _front, uint _index) public view returns(string memory name, uint price, uint quantity, uint sales, bool isOpen) {
require(isStore[_owner], "the owner's store doesn't exist");
Store storage s = stores[_owner];
require(s.isFront[_front], "the owner's front doesn't exist");
Front storage f = s.fronts[_front];
Product memory p = f.products[f.productKeys[_index]];
name = p.name;
price = p.price;
quantity = p.quantity;
sales = p.sales;
isOpen = p.isOpen;
}
function getShopperProducts(address _owner, string memory _front, string memory _product, address _shopper) public view returns(uint amount) {
require(isStore[_owner], "the owner's store doesn't exist");
Store storage s = stores[_owner];
require(s.isFront[_front], "the owner's front doesn't exist");
Front storage f = s.fronts[_front];
Product storage p = f.products[_product];
amount = p.shoppers[_shopper];
}
/** @dev Fallback function which reverts all tx.
*/
function () external payable {
revert();
}
}
|
Toggle storefront isOpen for shoppers. _name a unique name of storefront./
|
function toggleFrontActive(string memory _name) public onlyStoreOwner stopInEmergency {
require(stores[msg.sender].isFront[_name], "front name doesn't exist.");
Store storage s = stores[msg.sender];
Front storage f = s.fronts[_name];
f.isOpen = !f.isOpen;
}
| 5,412,298 |
./full_match/43114/0x43C263a40De709EfE72cfc2aD7E6a1e775968138/sources/OLYMP.sol
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "Olymp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 4,520,835 |
pragma solidity ^0.5.6;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address payable private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address payable) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address payable newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address payable newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the KIP-13 standard, as defined in the
* [KIP-13](http://kips.klaytn.com/KIPs/kip-13-interface_query_standard).
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others.
*
* For an implementation, see `KIP13`.
*/
interface IKIP13 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [KIP-13 section](http://kips.klaytn.com/KIPs/kip-13-interface_query_standard#how-interface-identifiers-are-defined)
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an KIP17 compliant contract.
*/
contract IKIP17 is IKIP13 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either `approve` or `setApproveForAll`.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either `approve` or `setApproveForAll`.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// SPDX-License-Identifier: MIT
/**
* @dev Required interface of an KIP37 compliant contract, as defined in the
* https://kips.klaytn.com/KIPs/kip-37
*/
contract IKIP37 is IKIP13 {
/**
* @dev Emitted when `value` tokens of token type `id` are transfered from `from` to `to` by `operator`.
*/
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
/**
* @dev Batch-operations version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IKIP37Receiver-onKIP37Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Batch-operations version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IKIP37Receiver-onKIP37BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
interface IItemStore {
event Sell(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address seller,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
bytes32 indexed saleVerificationID
);
event ChangeSellPrice(uint256 indexed metaverseId, address indexed item, uint256 id, uint256 newUnitPrice, bytes32 indexed saleVerificationID);
event Buy(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address buyer,
uint256 amount,
bool isFulfilled,
bytes32 indexed saleVerificationID
);
event CancelSale(uint256 indexed metaverseId, address indexed item, uint256 id, uint256 amount, bytes32 indexed saleVerificationID);
event MakeOffer(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address offeror,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
bytes32 indexed offerVerificationID
);
event CancelOffer(uint256 indexed metaverseId, address indexed item, uint256 id, uint256 amount, bytes32 indexed offerVerificationID);
event AcceptOffer(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address acceptor,
uint256 amount,
bool isFulfilled,
bytes32 indexed offerVerificationID
);
event CreateAuction(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address seller,
uint256 amount,
uint256 startPrice,
uint256 endBlock,
bytes32 indexed auctionVerificationID
);
event CancelAuction(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed auctionVerificationID);
event Bid(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address bidder,
uint256 amount,
uint256 price,
bytes32 indexed auctionVerificationID,
uint256 biddingId
);
event Claim(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address bestBidder,
uint256 amount,
uint256 price,
bytes32 indexed auctionVerificationID,
uint256 biddingId
);
event CancelSaleByOwner(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed saleVerificationID);
event CancelOfferByOwner(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed offerVerificationID);
event CancelAuctionByOwner(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed auctionVerificationID);
event Ban(address indexed user);
event Unban(address indexed user);
function fee() external view returns (uint256);
function feeReceiver() external view returns (address);
function auctionExtensionInterval() external view returns (uint256);
function isBanned(address user) external view returns (bool);
function batchTransfer(
uint256[] calldata metaverseIds,
address[] calldata items,
uint256[] calldata ids,
address[] calldata to,
uint256[] calldata amounts
) external;
function nonce(address user) external view returns (uint256);
//Sale
function sales(
address item,
uint256 id,
uint256 saleId
)
external
view
returns (
address seller,
uint256 metaverseId,
address _item,
uint256 _id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
bytes32 verificationID
);
function onSales(address item, uint256 index) external view returns (bytes32 saleVerificationID);
function userSellInfo(address seller, uint256 index) external view returns (bytes32 saleVerificationID);
function salesOnMetaverse(uint256 metaverseId, uint256 index) external view returns (bytes32 saleVerificationID);
function userOnSaleAmounts(
address seller,
address item,
uint256 id
) external view returns (uint256);
function getSaleInfo(bytes32 saleVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 saleId
);
function salesCount(address item, uint256 id) external view returns (uint256);
function onSalesCount(address item) external view returns (uint256);
function userSellInfoLength(address seller) external view returns (uint256);
function salesOnMetaverseLength(uint256 metaverseId) external view returns (uint256);
function canSell(
address seller,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) external view returns (bool);
function sell(
uint256[] calldata metaverseIds,
address[] calldata items,
uint256[] calldata ids,
uint256[] calldata amounts,
uint256[] calldata unitPrices,
bool[] calldata partialBuyings
) external;
function changeSellPrice(bytes32[] calldata saleVerificationIDs, uint256[] calldata unitPrices) external;
function cancelSale(bytes32[] calldata saleVerificationIDs) external;
function buy(
bytes32[] calldata saleVerificationIDs,
uint256[] calldata amounts,
uint256[] calldata unitPrices,
uint256[] calldata mileages
) external;
//Offer
function offers(
address item,
uint256 id,
uint256 offerId
)
external
view
returns (
address offeror,
uint256 metaverseId,
address _item,
uint256 _id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
uint256 mileage,
bytes32 verificationID
);
function userOfferInfo(address offeror, uint256 index) external view returns (bytes32 offerVerificationID);
function getOfferInfo(bytes32 offerVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 offerId
);
function userOfferInfoLength(address offeror) external view returns (uint256);
function offersCount(address item, uint256 id) external view returns (uint256);
function canOffer(
address offeror,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) external view returns (bool);
function makeOffer(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
uint256 mileage
) external returns (uint256 offerId);
function cancelOffer(bytes32 offerVerificationID) external;
function acceptOffer(bytes32 offerVerificationID, uint256 amount) external;
//Auction
function auctions(
address item,
uint256 id,
uint256 auctionId
)
external
view
returns (
address seller,
uint256 metaverseId,
address _item,
uint256 _id,
uint256 amount,
uint256 startTotalPrice,
uint256 endBlock,
bytes32 verificationID
);
function onAuctions(address item, uint256 index) external view returns (bytes32 auctionVerificationID);
function userAuctionInfo(address seller, uint256 index) external view returns (bytes32 auctionVerificationID);
function auctionsOnMetaverse(uint256 metaverseId, uint256 index) external view returns (bytes32 auctionVerificationID);
function getAuctionInfo(bytes32 auctionVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 auctionId
);
function auctionsCount(address item, uint256 id) external view returns (uint256);
function onAuctionsCount(address item) external view returns (uint256);
function userAuctionInfoLength(address seller) external view returns (uint256);
function auctionsOnMetaverseLength(uint256 metaverseId) external view returns (uint256);
function canCreateAuction(
address seller,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) external view returns (bool);
function createAuction(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 startTotalPrice,
uint256 endBlock
) external returns (uint256 auctionId);
function cancelAuction(bytes32 auctionVerificationID) external;
//Bidding
function biddings(bytes32 auctionVerificationID, uint256 biddingId)
external
view
returns (
address bidder,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 price,
uint256 mileage
);
function userBiddingInfo(address bidder, uint256 index) external view returns (bytes32 auctionVerificationID, uint256 biddingId);
function userBiddingInfoLength(address bidder) external view returns (uint256);
function biddingsCount(bytes32 auctionVerificationID) external view returns (uint256);
function canBid(
address bidder,
uint256 price,
bytes32 auctionVerificationID
) external view returns (bool);
function bid(
bytes32 auctionVerificationID,
uint256 price,
uint256 mileage
) external returns (uint256 biddingId);
function claim(bytes32 auctionVerificationID) external;
}
interface IMetaverses {
enum ItemType {
ERC1155,
ERC721
}
event Add(address indexed manager);
event AddManager(uint256 indexed id, address indexed manager);
event RemoveManager(uint256 indexed id, address indexed manager);
event SetExtra(uint256 indexed id, string extra);
event SetRoyalty(uint256 indexed id, address receiver, uint256 royalty);
event JoinOnlyKlubsMembership(uint256 indexed id);
event ExitOnlyKlubsMembership(uint256 indexed id);
event MileageOn(uint256 indexed id);
event MileageOff(uint256 indexed id);
event Ban(uint256 indexed id);
event Unban(uint256 indexed id);
event ProposeItem(uint256 indexed id, address indexed item, ItemType itemType, address indexed proposer);
event AddItem(uint256 indexed id, address indexed item, ItemType itemType);
event SetItemEnumerable(uint256 indexed id, address indexed item, bool enumerable);
event SetItemTotalSupply(uint256 indexed id, address indexed item, uint256 totalSupply);
event SetItemExtra(uint256 indexed id, address indexed item, string extra);
function addMetaverse(string calldata extra) external;
function metaverseCount() view external returns (uint256);
function managerCount(uint256 id) view external returns (uint256);
function managers(uint256 id, uint256 index) view external returns (address);
function managerMetaversesCount(address manager) view external returns (uint256);
function managerMetaverses(address manager, uint256 index) view external returns (uint256);
function existsManager(uint256 id, address manager) view external returns (bool);
function addManager(uint256 id, address manager) external;
function removeManager(uint256 id, address manager) external;
function extras(uint256 id) view external returns (string memory);
function setExtra(uint256 id, string calldata extra) external;
function royalties(uint256 id) view external returns (address receiver, uint256 royalty);
function setRoyalty(uint256 id, address receiver, uint256 royalty) external;
function onlyKlubsMembership(uint256 id) view external returns (bool);
function mileageMode(uint256 id) view external returns (bool);
function mileageOn(uint256 id) external;
function mileageOff(uint256 id) external;
function banned(uint256 id) view external returns (bool);
function proposeItem(uint256 id, address item, ItemType itemType) external;
function itemProposalCount() view external returns (uint256);
function itemAddrCount(uint256 id) view external returns (uint256);
function itemAddrs(uint256 id, uint256 index) view external returns (address);
function itemAdded(uint256 id, address item) view external returns (bool);
function itemAddedBlocks(uint256 id, address item) view external returns (uint256);
function itemTypes(uint256 id, address item) view external returns (ItemType);
function addItem(uint256 id, address item, ItemType itemType, string calldata extra) external;
function passProposal(uint256 proposalId, string calldata extra) external;
function removeProposal(uint256 proposalId) external;
function itemEnumerables(uint256 id, address item) view external returns (bool);
function setItemEnumerable(uint256 id, address item, bool enumerable) external;
function itemTotalSupplies(uint256 id, address item) view external returns (uint256);
function setItemTotalSupply(uint256 id, address item, uint256 totalSupply) external;
function getItemTotalSupply(uint256 id, address item) view external returns (uint256);
function itemExtras(uint256 id, address item) view external returns (string memory);
function setItemExtra(uint256 id, address item, string calldata extra) external;
}
/**
* @dev Interface of the KIP7 standard as defined in the KIP. Does not include
* the optional functions; to access them see `KIP7Metadata`.
* See http://kips.klaytn.com/KIPs/kip-7-fungible_token
*/
contract IKIP7 is IKIP13 {
/**
* @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.
*
* > 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 Moves `amount` tokens from the caller's account to `recipient`.
*/
function safeTransfer(address recipient, uint256 amount, bytes memory data) public;
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*/
function safeTransfer(address recipient, uint256 amount) public;
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism.
* `amount` is then deducted from the caller's allowance.
*/
function safeTransferFrom(address sender, address recipient, uint256 amount, bytes memory data) public;
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism.
* `amount` is then deducted from the caller's allowance.
*/
function safeTransferFrom(address sender, address recipient, uint256 amount) public;
/**
* @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);
}
interface IMix {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
interface IMileage {
event AddToWhitelist(address indexed addr);
event RemoveFromWhitelist(address indexed addr);
event Charge(address indexed user, uint256 amount);
event Use(address indexed user, uint256 amount);
function mileages(address user) external view returns (uint256);
function mileagePercent() external view returns (uint256);
function onlyKlubsPercent() external view returns (uint256);
function whitelist(address addr) external view returns (bool);
function charge(address user, uint256 amount) external;
function use(address user, uint256 amount) external;
}
contract ItemStore is Ownable, IItemStore {
using SafeMath for uint256;
uint256 public fee = 250;
address public feeReceiver;
uint256 public auctionExtensionInterval = 300;
IMetaverses public metaverses;
IMix public mix;
IMileage public mileage;
constructor(
IMetaverses _metaverses,
IMix _mix,
IMileage _mileage
) public {
feeReceiver = msg.sender;
metaverses = _metaverses;
mix = _mix;
mileage = _mileage;
}
function setFee(uint256 _fee) external onlyOwner {
require(_fee < 9 * 1e3); //max 90%
fee = _fee;
}
function setFeeReceiver(address _receiver) external onlyOwner {
feeReceiver = _receiver;
}
function setAuctionExtensionInterval(uint256 interval) external onlyOwner {
auctionExtensionInterval = interval;
}
function setMetaverses(IMetaverses _metaverses) external onlyOwner {
metaverses = _metaverses;
}
function isMetaverseWhitelisted(uint256 metaverseId) private view returns (bool) {
return (metaverseId < metaverses.metaverseCount() && !metaverses.banned(metaverseId));
}
function isItemWhitelisted(uint256 metaverseId, address item) private view returns (bool) {
if (!isMetaverseWhitelisted(metaverseId)) return false;
return (metaverses.itemAdded(metaverseId, item));
}
mapping(address => bool) public isBanned;
function banUser(address user) external onlyOwner {
isBanned[user] = true;
emit Ban(user);
}
function unbanUser(address user) external onlyOwner {
isBanned[user] = false;
emit Unban(user);
}
modifier userWhitelist(address user) {
require(!isBanned[user]);
_;
}
function _isERC1155(uint256 metaverseId, address item) internal view returns (bool) {
return metaverses.itemTypes(metaverseId, item) == IMetaverses.ItemType.ERC1155;
}
function batchTransfer(
uint256[] calldata metaverseIds,
address[] calldata items,
uint256[] calldata ids,
address[] calldata to,
uint256[] calldata amounts
) external userWhitelist(msg.sender) {
require(
metaverseIds.length == items.length &&
metaverseIds.length == ids.length &&
metaverseIds.length == to.length &&
metaverseIds.length == amounts.length
);
uint256 metaverseCount = metaverses.metaverseCount();
for (uint256 i = 0; i < metaverseIds.length; i++) {
uint256 metaverseId = metaverseIds[i];
require(metaverseId < metaverseCount && !metaverses.banned(metaverseId));
require(metaverses.itemAdded(metaverseId, items[i]));
_itemTransfer(metaverseId, items[i], ids[i], amounts[i], msg.sender, to[i]);
}
}
function _itemTransfer(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
address from,
address to
) internal {
if (_isERC1155(metaverseId, item)) {
require(amount > 0);
IKIP37(item).safeTransferFrom(from, to, id, amount, "");
} else {
require(amount == 1);
IKIP17(item).transferFrom(from, to, id);
}
}
//use verificationID as a parameter in "_removeXXXX" functions for safety despite a waste of gas
function _removeSale(bytes32 saleVerificationID) private {
SaleInfo storage saleInfo = _saleInfo[saleVerificationID];
address item = saleInfo.item;
uint256 id = saleInfo.id;
uint256 saleId = saleInfo.saleId;
Sale storage sale = sales[item][id][saleId];
//delete sales
uint256 lastSaleId = sales[item][id].length.sub(1);
Sale memory lastSale = sales[item][id][lastSaleId];
if (saleId != lastSaleId) {
sales[item][id][saleId] = lastSale;
_saleInfo[lastSale.verificationID].saleId = saleId;
}
sales[item][id].length--;
delete _saleInfo[saleVerificationID];
//delete onSales
uint256 lastIndex = onSales[item].length.sub(1);
uint256 index = _onSalesIndex[saleVerificationID];
if (index != lastIndex) {
bytes32 lastSaleVerificationID = onSales[item][lastIndex];
onSales[item][index] = lastSaleVerificationID;
_onSalesIndex[lastSaleVerificationID] = index;
}
onSales[item].length--;
delete _onSalesIndex[saleVerificationID];
//delete userSellInfo
address seller = sale.seller;
lastIndex = userSellInfo[seller].length.sub(1);
index = _userSellIndex[saleVerificationID];
if (index != lastIndex) {
bytes32 lastSaleVerificationID = userSellInfo[seller][lastIndex];
userSellInfo[seller][index] = lastSaleVerificationID;
_userSellIndex[lastSaleVerificationID] = index;
}
userSellInfo[seller].length--;
delete _userSellIndex[saleVerificationID];
//delete salesOnMetaverse
uint256 metaverseId = sale.metaverseId;
lastIndex = salesOnMetaverse[metaverseId].length.sub(1);
index = _salesOnMvIndex[saleVerificationID];
if (index != lastIndex) {
bytes32 lastSaleVerificationID = salesOnMetaverse[metaverseId][lastIndex];
salesOnMetaverse[metaverseId][index] = lastSaleVerificationID;
_salesOnMvIndex[lastSaleVerificationID] = index;
}
salesOnMetaverse[metaverseId].length--;
delete _salesOnMvIndex[saleVerificationID];
//subtract amounts.
uint256 amount = sale.amount;
if (amount > 0) {
userOnSaleAmounts[seller][item][id] = userOnSaleAmounts[seller][item][id].sub(amount);
}
}
function _removeOffer(bytes32 offerVerificationID) private {
OfferInfo storage offerInfo = _offerInfo[offerVerificationID];
address item = offerInfo.item;
uint256 id = offerInfo.id;
uint256 offerId = offerInfo.offerId;
Offer storage offer = offers[item][id][offerId];
//delete offers
uint256 lastOfferId = offers[item][id].length.sub(1);
Offer memory lastOffer = offers[item][id][lastOfferId];
if (offerId != lastOfferId) {
offers[item][id][offerId] = lastOffer;
_offerInfo[lastOffer.verificationID].offerId = offerId;
}
offers[item][id].length--;
delete _offerInfo[offerVerificationID];
//delete userOfferInfo
address offeror = offer.offeror;
uint256 lastIndex = userOfferInfo[offeror].length.sub(1);
uint256 index = _userOfferIndex[offerVerificationID];
if (index != lastIndex) {
bytes32 lastOfferVerificationID = userOfferInfo[offeror][lastIndex];
userOfferInfo[offeror][index] = lastOfferVerificationID;
_userOfferIndex[lastOfferVerificationID] = index;
}
userOfferInfo[offeror].length--;
delete _userOfferIndex[offerVerificationID];
}
function _removeAuction(bytes32 auctionVerificationID) private {
AuctionInfo storage auctionInfo = _auctionInfo[auctionVerificationID];
address item = auctionInfo.item;
uint256 id = auctionInfo.id;
uint256 auctionId = auctionInfo.auctionId;
Auction storage auction = auctions[item][id][auctionId];
//delete auctions
uint256 lastAuctionId = auctions[item][id].length.sub(1);
Auction memory lastAuction = auctions[item][id][lastAuctionId];
if (auctionId != lastAuctionId) {
auctions[item][id][auctionId] = lastAuction;
_auctionInfo[lastAuction.verificationID].auctionId = auctionId;
}
auctions[item][id].length--;
delete _auctionInfo[auctionVerificationID];
//delete onAuctions
uint256 lastIndex = onAuctions[item].length.sub(1);
uint256 index = _onAuctionsIndex[auctionVerificationID];
if (index != lastIndex) {
bytes32 lastAuctionVerificationID = onAuctions[item][lastIndex];
onAuctions[item][index] = lastAuctionVerificationID;
_onAuctionsIndex[lastAuctionVerificationID] = index;
}
onAuctions[item].length--;
delete _onAuctionsIndex[auctionVerificationID];
//delete userAuctionInfo
address seller = auction.seller;
lastIndex = userAuctionInfo[seller].length.sub(1);
index = _userAuctionIndex[auctionVerificationID];
if (index != lastIndex) {
bytes32 lastAuctionVerificationID = userAuctionInfo[seller][lastIndex];
userAuctionInfo[seller][index] = lastAuctionVerificationID;
_userAuctionIndex[lastAuctionVerificationID] = index;
}
userAuctionInfo[seller].length--;
delete _userAuctionIndex[auctionVerificationID];
//delete auctionsOnMetaverse
uint256 metaverseId = auction.metaverseId;
lastIndex = auctionsOnMetaverse[metaverseId].length.sub(1);
index = _auctionsOnMvIndex[auctionVerificationID];
if (index != lastIndex) {
bytes32 lastAuctionVerificationID = auctionsOnMetaverse[metaverseId][lastIndex];
auctionsOnMetaverse[metaverseId][index] = lastAuctionVerificationID;
_auctionsOnMvIndex[lastAuctionVerificationID] = index;
}
auctionsOnMetaverse[metaverseId].length--;
delete _auctionsOnMvIndex[auctionVerificationID];
}
function _distributeReward(
uint256 metaverseId,
address buyer,
address seller,
uint256 price
) private {
(address receiver, uint256 royalty) = metaverses.royalties(metaverseId);
uint256 _fee;
uint256 _royalty;
uint256 _mileage;
if (metaverses.mileageMode(metaverseId)) {
if (metaverses.onlyKlubsMembership(metaverseId)) {
uint256 mileageFromFee = price.mul(mileage.onlyKlubsPercent()).div(1e4);
_fee = price.mul(fee).div(1e4);
if (_fee > mileageFromFee) {
_mileage = mileageFromFee;
_fee = _fee.sub(mileageFromFee);
} else {
_mileage = _fee;
_fee = 0;
}
uint256 mileageFromRoyalty = price.mul(mileage.mileagePercent()).div(1e4).sub(mileageFromFee);
_royalty = price.mul(royalty).div(1e4);
if (_royalty > mileageFromRoyalty) {
_mileage = _mileage.add(mileageFromRoyalty);
_royalty = _royalty.sub(mileageFromRoyalty);
} else {
_mileage = _mileage.add(_royalty);
_royalty = 0;
}
} else {
_fee = price.mul(fee).div(1e4);
_mileage = price.mul(mileage.mileagePercent()).div(1e4);
_royalty = price.mul(royalty).div(1e4);
if (_royalty > _mileage) {
_royalty = _royalty.sub(_mileage);
} else {
_mileage = _royalty;
_royalty = 0;
}
}
} else {
_fee = price.mul(fee).div(1e4);
_royalty = price.mul(royalty).div(1e4);
}
if (_fee > 0) mix.transfer(feeReceiver, _fee);
if (_royalty > 0) mix.transfer(receiver, _royalty);
if (_mileage > 0) {
mix.approve(address(mileage), _mileage);
mileage.charge(buyer, _mileage);
}
mix.transfer(seller, price.sub(_fee).sub(_royalty).sub(_mileage));
}
mapping(address => uint256) public nonce;
//Sale
struct Sale {
address seller;
uint256 metaverseId;
address item;
uint256 id;
uint256 amount;
uint256 unitPrice;
bool partialBuying;
bytes32 verificationID;
}
struct SaleInfo {
address item;
uint256 id;
uint256 saleId;
}
mapping(address => mapping(uint256 => Sale[])) public sales; //sales[item][id].
mapping(bytes32 => SaleInfo) internal _saleInfo; //_saleInfo[saleVerificationID].
mapping(address => bytes32[]) public onSales; //onSales[item]. 아이템 계약 중 onSale 중인 정보들. "return saleVerificationID."
mapping(bytes32 => uint256) private _onSalesIndex; //_onSalesIndex[saleVerificationID]. 특정 세일의 onSales index.
mapping(address => bytes32[]) public userSellInfo; //userSellInfo[seller] 셀러가 팔고있는 세일의 정보. "return saleVerificationID."
mapping(bytes32 => uint256) private _userSellIndex; //_userSellIndex[saleVerificationID]. 특정 세일의 userSellInfo index.
mapping(uint256 => bytes32[]) public salesOnMetaverse; //salesOnMetaverse[metaverseId]. 특정 메타버스에서 판매되고있는 모든 세일들. "return saleVerificationID."
mapping(bytes32 => uint256) private _salesOnMvIndex; //_salesOnMvIndex[saleVerificationID]. 특정 세일의 salesOnMetaverse index.
mapping(address => mapping(address => mapping(uint256 => uint256))) public userOnSaleAmounts; //userOnSaleAmounts[seller][item][id]. 셀러가 판매중인 특정 id의 아이템의 총 합.
function getSaleInfo(bytes32 saleVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 saleId
)
{
SaleInfo memory saleInfo = _saleInfo[saleVerificationID];
require(saleInfo.item != address(0));
return (saleInfo.item, saleInfo.id, saleInfo.saleId);
}
function salesCount(address item, uint256 id) external view returns (uint256) {
return sales[item][id].length;
}
function onSalesCount(address item) external view returns (uint256) {
return onSales[item].length;
}
function userSellInfoLength(address seller) external view returns (uint256) {
return userSellInfo[seller].length;
}
function salesOnMetaverseLength(uint256 metaverseId) external view returns (uint256) {
return salesOnMetaverse[metaverseId].length;
}
function canSell(
address seller,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) public view returns (bool) {
if (!isItemWhitelisted(metaverseId, item)) return false;
if (_isERC1155(metaverseId, item)) {
if (amount == 0) return false;
if (userOnSaleAmounts[seller][item][id].add(amount) > IKIP37(item).balanceOf(seller, id)) return false;
return true;
} else {
if (amount != 1) return false;
if (IKIP17(item).ownerOf(id) != seller) return false;
if (userOnSaleAmounts[seller][item][id] != 0) return false;
return true;
}
}
function sell(
uint256[] calldata metaverseIds,
address[] calldata items,
uint256[] calldata ids,
uint256[] calldata amounts,
uint256[] calldata unitPrices,
bool[] calldata partialBuyings
) external userWhitelist(msg.sender) {
require(
metaverseIds.length == items.length &&
metaverseIds.length == ids.length &&
metaverseIds.length == amounts.length &&
metaverseIds.length == unitPrices.length &&
metaverseIds.length == partialBuyings.length
);
for (uint256 i = 0; i < metaverseIds.length; i++) {
uint256 metaverseId = metaverseIds[i];
address item = items[i];
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 unitPrice = unitPrices[i];
bool partialBuying = partialBuyings[i];
require(unitPrice > 0);
require(canSell(msg.sender, metaverseId, item, id, amount));
bytes32 verificationID = keccak256(
abi.encodePacked(msg.sender, metaverseId, item, id, amount, unitPrice, partialBuying, nonce[msg.sender]++)
);
require(_saleInfo[verificationID].item == address(0));
uint256 saleId = sales[item][id].length;
sales[item][id].push(
Sale({
seller: msg.sender,
metaverseId: metaverseId,
item: item,
id: id,
amount: amount,
unitPrice: unitPrice,
partialBuying: partialBuying,
verificationID: verificationID
})
);
_saleInfo[verificationID] = SaleInfo({item: item, id: id, saleId: saleId});
_onSalesIndex[verificationID] = onSales[item].length;
onSales[item].push(verificationID);
_userSellIndex[verificationID] = userSellInfo[msg.sender].length;
userSellInfo[msg.sender].push(verificationID);
_salesOnMvIndex[verificationID] = salesOnMetaverse[metaverseId].length;
salesOnMetaverse[metaverseId].push(verificationID);
userOnSaleAmounts[msg.sender][item][id] = userOnSaleAmounts[msg.sender][item][id].add(amount);
emit Sell(metaverseId, item, id, msg.sender, amount, unitPrice, partialBuying, verificationID);
}
}
function changeSellPrice(bytes32[] calldata saleVerificationIDs, uint256[] calldata unitPrices) external userWhitelist(msg.sender) {
require(saleVerificationIDs.length == unitPrices.length);
for (uint256 i = 0; i < saleVerificationIDs.length; i++) {
SaleInfo storage saleInfo = _saleInfo[saleVerificationIDs[i]];
address item = saleInfo.item;
uint256 id = saleInfo.id;
Sale storage sale = sales[item][id][saleInfo.saleId];
require(sale.seller == msg.sender);
require(sale.unitPrice != unitPrices[i]);
sale.unitPrice = unitPrices[i];
emit ChangeSellPrice(sale.metaverseId, item, id, unitPrices[i], saleVerificationIDs[i]);
}
}
function cancelSale(bytes32[] calldata saleVerificationIDs) external {
for (uint256 i = 0; i < saleVerificationIDs.length; i++) {
SaleInfo storage saleInfo = _saleInfo[saleVerificationIDs[i]];
address item = saleInfo.item;
uint256 id = saleInfo.id;
Sale storage sale = sales[item][id][saleInfo.saleId];
require(sale.seller == msg.sender);
emit CancelSale(sale.metaverseId, item, id, sale.amount, saleVerificationIDs[i]);
_removeSale(saleVerificationIDs[i]);
}
}
function buy(
bytes32[] calldata saleVerificationIDs,
uint256[] calldata amounts,
uint256[] calldata unitPrices,
uint256[] calldata mileages
) external userWhitelist(msg.sender) {
require(amounts.length == saleVerificationIDs.length && amounts.length == unitPrices.length && amounts.length == mileages.length);
for (uint256 i = 0; i < amounts.length; i++) {
bytes32 saleVerificationID = saleVerificationIDs[i];
SaleInfo memory saleInfo = _saleInfo[saleVerificationID];
Sale storage sale = sales[saleInfo.item][saleInfo.id][saleInfo.saleId];
address seller = sale.seller;
uint256 metaverseId = sale.metaverseId;
require(isItemWhitelisted(metaverseId, saleInfo.item));
require(seller != address(0) && seller != msg.sender);
require(sale.unitPrice == unitPrices[i]);
uint256 amount = amounts[i];
uint256 saleAmount = sale.amount;
if (!sale.partialBuying) {
require(saleAmount == amount);
} else {
require(saleAmount >= amount);
}
uint256 amountLeft = saleAmount.sub(amount);
sale.amount = amountLeft;
_itemTransfer(metaverseId, saleInfo.item, saleInfo.id, amount, seller, msg.sender);
uint256 price = amount.mul(unitPrices[i]);
uint256 _mileage = mileages[i];
mix.transferFrom(msg.sender, address(this), price.sub(_mileage));
if (_mileage > 0) mileage.use(msg.sender, _mileage);
_distributeReward(metaverseId, msg.sender, seller, price);
userOnSaleAmounts[msg.sender][saleInfo.item][saleInfo.id] = userOnSaleAmounts[msg.sender][saleInfo.item][saleInfo.id].sub(amount);
bool isFulfilled = false;
if (amountLeft == 0) {
_removeSale(saleVerificationID);
isFulfilled = true;
}
emit Buy(metaverseId, saleInfo.item, saleInfo.id, msg.sender, amount, isFulfilled, saleVerificationID);
}
}
//Offer
struct Offer {
address offeror;
uint256 metaverseId;
address item;
uint256 id;
uint256 amount;
uint256 unitPrice;
bool partialBuying;
uint256 mileage;
bytes32 verificationID;
}
struct OfferInfo {
address item;
uint256 id;
uint256 offerId;
}
mapping(address => mapping(uint256 => Offer[])) public offers; //offers[item][id].
mapping(bytes32 => OfferInfo) internal _offerInfo; //_offerInfo[offerVerificationID].
mapping(address => bytes32[]) public userOfferInfo; //userOfferInfo[offeror] 오퍼러의 오퍼들 정보. "return offerVerificationID."
mapping(bytes32 => uint256) private _userOfferIndex; //_userOfferIndex[offerVerificationID]. 특정 오퍼의 userOfferInfo index.
function getOfferInfo(bytes32 offerVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 offerId
)
{
OfferInfo memory offerInfo = _offerInfo[offerVerificationID];
require(offerInfo.item != address(0));
return (offerInfo.item, offerInfo.id, offerInfo.offerId);
}
function userOfferInfoLength(address offeror) external view returns (uint256) {
return userOfferInfo[offeror].length;
}
function offersCount(address item, uint256 id) external view returns (uint256) {
return offers[item][id].length;
}
function canOffer(
address offeror,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) public view returns (bool) {
if (!isItemWhitelisted(metaverseId, item)) return false;
if (_isERC1155(metaverseId, item)) {
if (amount == 0) return false;
return true;
} else {
if (amount != 1) return false;
if (IKIP17(item).ownerOf(id) == offeror) return false;
return true;
}
}
function makeOffer(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
uint256 _mileage
) external userWhitelist(msg.sender) returns (uint256 offerId) {
require(unitPrice > 0);
require(canOffer(msg.sender, metaverseId, item, id, amount));
bytes32 verificationID = keccak256(
abi.encodePacked(msg.sender, metaverseId, item, id, amount, unitPrice, partialBuying, _mileage, nonce[msg.sender]++)
);
require(_offerInfo[verificationID].item == address(0));
offerId = offers[item][id].length;
offers[item][id].push(
Offer({
offeror: msg.sender,
metaverseId: metaverseId,
item: item,
id: id,
amount: amount,
unitPrice: unitPrice,
partialBuying: partialBuying,
mileage: _mileage,
verificationID: verificationID
})
);
_userOfferIndex[verificationID] = userOfferInfo[msg.sender].length;
userOfferInfo[msg.sender].push(verificationID);
mix.transferFrom(msg.sender, address(this), amount.mul(unitPrice).sub(_mileage));
if (_mileage > 0) mileage.use(msg.sender, _mileage);
emit MakeOffer(metaverseId, item, id, msg.sender, amount, unitPrice, partialBuying, verificationID);
}
function cancelOffer(bytes32 offerVerificationID) external {
OfferInfo storage offerInfo = _offerInfo[offerVerificationID];
address item = offerInfo.item;
uint256 id = offerInfo.id;
Offer storage offer = offers[item][id][offerInfo.offerId];
require(offer.offeror == msg.sender);
uint256 amount = offer.amount;
uint256 _mileage = offer.mileage;
mix.transfer(msg.sender, amount.mul(offer.unitPrice).sub(_mileage));
if (_mileage > 0) {
mix.approve(address(mileage), _mileage);
mileage.charge(msg.sender, _mileage);
}
emit CancelOffer(offer.metaverseId, item, id, amount, offerVerificationID);
_removeOffer(offerVerificationID);
}
function acceptOffer(bytes32 offerVerificationID, uint256 amount) external userWhitelist(msg.sender) {
OfferInfo storage offerInfo = _offerInfo[offerVerificationID];
address item = offerInfo.item;
uint256 id = offerInfo.id;
Offer storage offer = offers[item][id][offerInfo.offerId];
address offeror = offer.offeror;
uint256 metaverseId = offer.metaverseId;
uint256 offerAmount = offer.amount;
require(isItemWhitelisted(metaverseId, item));
require(offeror != address(0) && offeror != msg.sender);
if (!offer.partialBuying) {
require(offerAmount == amount);
} else {
require(offerAmount >= amount);
}
uint256 amountLeft = offerAmount.sub(amount);
offer.amount = amountLeft;
_itemTransfer(metaverseId, item, id, amount, msg.sender, offeror);
uint256 price = amount.mul(offer.unitPrice);
_distributeReward(metaverseId, offeror, msg.sender, price);
bool isFulfilled = false;
if (amountLeft == 0) {
_removeOffer(offerVerificationID);
isFulfilled = true;
}
emit AcceptOffer(metaverseId, item, id, msg.sender, offerAmount, isFulfilled, offerVerificationID);
}
//Auction
struct Auction {
address seller;
uint256 metaverseId;
address item;
uint256 id;
uint256 amount;
uint256 startTotalPrice;
uint256 endBlock;
bytes32 verificationID;
}
struct AuctionInfo {
address item;
uint256 id;
uint256 auctionId;
}
mapping(address => mapping(uint256 => Auction[])) public auctions; //auctions[item][id].
mapping(bytes32 => AuctionInfo) internal _auctionInfo; //_auctionInfo[auctionVerificationID].
mapping(address => bytes32[]) public onAuctions; //onAuctions[item]. 아이템 계약 중 onAuction 중인 정보들. "return auctionsVerificationID."
mapping(bytes32 => uint256) private _onAuctionsIndex; //_onAuctionsIndex[auctionVerificationID]. 특정 옥션의 onAuctions index.
mapping(address => bytes32[]) public userAuctionInfo; //userAuctionInfo[seller] 셀러의 옥션들 정보. "return auctionsVerificationID."
mapping(bytes32 => uint256) private _userAuctionIndex; //_userAuctionIndex[auctionVerificationID]. 특정 옥션의 userAuctionInfo index.
mapping(uint256 => bytes32[]) public auctionsOnMetaverse; //auctionsOnMetaverse[metaverseId]. 특정 메타버스의 모든 옥션들. "return auctionsVerificationID."
mapping(bytes32 => uint256) private _auctionsOnMvIndex; //_auctionsOnMvIndex[auctionVerificationID]. 특정 옥션의 auctionsOnMetaverse index.
function getAuctionInfo(bytes32 auctionVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 auctionId
)
{
AuctionInfo memory auctionInfo = _auctionInfo[auctionVerificationID];
require(auctionInfo.item != address(0));
return (auctionInfo.item, auctionInfo.id, auctionInfo.auctionId);
}
function auctionsCount(address item, uint256 id) external view returns (uint256) {
return auctions[item][id].length;
}
function onAuctionsCount(address item) external view returns (uint256) {
return onAuctions[item].length;
}
function userAuctionInfoLength(address seller) external view returns (uint256) {
return userAuctionInfo[seller].length;
}
function auctionsOnMetaverseLength(uint256 metaverseId) external view returns (uint256) {
return auctionsOnMetaverse[metaverseId].length;
}
function canCreateAuction(
address seller,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) public view returns (bool) {
if (!isItemWhitelisted(metaverseId, item)) return false;
if (_isERC1155(metaverseId, item)) {
if (amount == 0) return false;
if (IKIP37(item).balanceOf(seller, id) < amount) return false;
return true;
} else {
if (amount != 1) return false;
if (IKIP17(item).ownerOf(id) != seller) return false;
return true;
}
}
function createAuction(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 startTotalPrice,
uint256 endBlock
) external userWhitelist(msg.sender) returns (uint256 auctionId) {
require(startTotalPrice > 0);
require(endBlock > block.number);
require(canCreateAuction(msg.sender, metaverseId, item, id, amount));
bytes32 verificationID = keccak256(
abi.encodePacked(msg.sender, metaverseId, item, id, amount, startTotalPrice, endBlock, nonce[msg.sender]++)
);
require(_auctionInfo[verificationID].item == address(0));
auctionId = auctions[item][id].length;
auctions[item][id].push(
Auction({
seller: msg.sender,
metaverseId: metaverseId,
item: item,
id: id,
amount: amount,
startTotalPrice: startTotalPrice,
endBlock: endBlock,
verificationID: verificationID
})
);
_auctionInfo[verificationID] = AuctionInfo({item: item, id: id, auctionId: auctionId});
_onAuctionsIndex[verificationID] = onAuctions[item].length;
onAuctions[item].push(verificationID);
_userAuctionIndex[verificationID] = userAuctionInfo[msg.sender].length;
userAuctionInfo[msg.sender].push(verificationID);
_auctionsOnMvIndex[verificationID] = auctionsOnMetaverse[metaverseId].length;
auctionsOnMetaverse[metaverseId].push(verificationID);
_itemTransfer(metaverseId, item, id, amount, msg.sender, address(this));
emit CreateAuction(metaverseId, item, id, msg.sender, amount, startTotalPrice, endBlock, verificationID);
}
function cancelAuction(bytes32 auctionVerificationID) external {
require(biddings[auctionVerificationID].length == 0);
AuctionInfo storage auctionInfo = _auctionInfo[auctionVerificationID];
address item = auctionInfo.item;
uint256 id = auctionInfo.id;
Auction storage auction = auctions[item][id][auctionInfo.auctionId];
require(auction.seller == msg.sender);
uint256 metaverseId = auction.metaverseId;
_itemTransfer(metaverseId, item, id, auction.amount, address(this), msg.sender);
emit CancelAuction(metaverseId, item, id, auctionVerificationID);
_removeAuction(auctionVerificationID);
}
//Bidding
struct Bidding {
address bidder;
uint256 metaverseId;
address item;
uint256 id;
uint256 amount;
uint256 price;
uint256 mileage;
}
struct BiddingInfo {
bytes32 auctionVerificationID;
uint256 biddingId;
}
mapping(bytes32 => Bidding[]) public biddings; //biddings[auctionVerificationID].
mapping(address => BiddingInfo[]) public userBiddingInfo; //userBiddingInfo[bidder] 비더의 비딩들 정보. "return BiddingInfo"
mapping(address => mapping(bytes32 => uint256)) private _userBiddingIndex;
//_userBiddingIndex[bidder][auctionVerificationID]. 특정 유저가 특정 옥션에 최종 입찰 중인 비딩의 userBiddingInfo index.
function userBiddingInfoLength(address bidder) external view returns (uint256) {
return userBiddingInfo[bidder].length;
}
function biddingsCount(bytes32 auctionVerificationID) external view returns (uint256) {
return biddings[auctionVerificationID].length;
}
function canBid(
address bidder,
uint256 price,
bytes32 auctionVerificationID
) public view returns (bool) {
AuctionInfo storage auctionInfo = _auctionInfo[auctionVerificationID];
address item = auctionInfo.item;
if (item == address(0)) return false;
Auction storage auction = auctions[item][auctionInfo.id][auctionInfo.auctionId];
if (!isItemWhitelisted(auction.metaverseId, item)) return false;
address seller = auction.seller;
if (seller == address(0) || seller == bidder) return false;
if (auction.endBlock <= block.number) return false;
Bidding[] storage bs = biddings[auctionVerificationID];
uint256 biddingLength = bs.length;
if (biddingLength == 0) {
if (auction.startTotalPrice > price) return false;
return true;
} else {
if (bs[biddingLength - 1].price >= price) return false;
return true;
}
}
function bid(
bytes32 auctionVerificationID,
uint256 price,
uint256 _mileage
) external userWhitelist(msg.sender) returns (uint256 biddingId) {
require(canBid(msg.sender, price, auctionVerificationID));
AuctionInfo memory auctionInfo = _auctionInfo[auctionVerificationID];
Auction storage auction = auctions[auctionInfo.item][auctionInfo.id][auctionInfo.auctionId];
uint256 metaverseId = auction.metaverseId;
uint256 amount = auction.amount;
Bidding[] storage bs = biddings[auctionVerificationID];
biddingId = bs.length;
if (biddingId > 0) {
Bidding storage lastBidding = bs[biddingId - 1];
address lastBidder = lastBidding.bidder;
uint256 lastMileage = lastBidding.mileage;
mix.transfer(lastBidder, lastBidding.price.sub(lastMileage));
if (lastMileage > 0) {
mix.approve(address(mileage), lastMileage);
mileage.charge(lastBidder, lastMileage);
}
_removeUserBiddingInfo(lastBidder, auctionVerificationID);
}
bs.push(
Bidding({
bidder: msg.sender,
metaverseId: metaverseId,
item: auctionInfo.item,
id: auctionInfo.id,
amount: amount,
price: price,
mileage: _mileage
})
);
_userBiddingIndex[msg.sender][auctionVerificationID] = userBiddingInfo[msg.sender].length;
userBiddingInfo[msg.sender].push(BiddingInfo({auctionVerificationID: auctionVerificationID, biddingId: biddingId}));
mix.transferFrom(msg.sender, address(this), price.sub(_mileage));
if (_mileage > 0) mileage.use(msg.sender, _mileage);
{
//to avoid stack too deep error
uint256 endBlock = auction.endBlock;
if (block.number >= endBlock.sub(auctionExtensionInterval)) {
auction.endBlock = endBlock.add(auctionExtensionInterval);
}
}
emit Bid(metaverseId, auctionInfo.item, auctionInfo.id, msg.sender, amount, price, auctionVerificationID, biddingId);
}
function _removeUserBiddingInfo(address bidder, bytes32 auctionVerificationID) private {
uint256 lastIndex = userBiddingInfo[bidder].length.sub(1);
uint256 index = _userBiddingIndex[bidder][auctionVerificationID];
if (index != lastIndex) {
BiddingInfo memory lastBiddingInfo = userBiddingInfo[bidder][lastIndex];
userBiddingInfo[bidder][index] = lastBiddingInfo;
_userBiddingIndex[bidder][lastBiddingInfo.auctionVerificationID] = index;
}
delete _userBiddingIndex[bidder][auctionVerificationID];
userBiddingInfo[bidder].length--;
}
function claim(bytes32 auctionVerificationID) external {
AuctionInfo storage auctionInfo = _auctionInfo[auctionVerificationID];
address item = auctionInfo.item;
uint256 id = auctionInfo.id;
Auction storage auction = auctions[item][id][auctionInfo.auctionId];
uint256 metaverseId = auction.metaverseId;
uint256 amount = auction.amount;
Bidding[] storage bs = biddings[auctionVerificationID];
uint256 bestBiddingId = bs.length.sub(1);
Bidding storage bestBidding = bs[bestBiddingId];
address bestBidder = bestBidding.bidder;
uint256 bestBiddingPrice = bestBidding.price;
require(block.number >= auction.endBlock);
_itemTransfer(metaverseId, item, id, amount, address(this), bestBidder);
_distributeReward(metaverseId, bestBidder, auction.seller, bestBiddingPrice);
_removeUserBiddingInfo(bestBidder, auctionVerificationID);
delete biddings[auctionVerificationID];
_removeAuction(auctionVerificationID);
emit Claim(metaverseId, item, id, bestBidder, amount, bestBiddingPrice, auctionVerificationID, bestBiddingId);
}
//"cancel" functions with ownership
function cancelSaleByOwner(bytes32[] calldata saleVerificationIDs) external onlyOwner {
for (uint256 i = 0; i < saleVerificationIDs.length; i++) {
SaleInfo storage saleInfo = _saleInfo[saleVerificationIDs[i]];
address item = saleInfo.item;
uint256 id = saleInfo.id;
Sale storage sale = sales[item][id][saleInfo.saleId];
address seller = sale.seller;
require(seller != address(0));
uint256 metaverseId = sale.metaverseId;
emit CancelSale(metaverseId, item, id, sale.amount, saleVerificationIDs[i]);
emit CancelSaleByOwner(metaverseId, item, id, saleVerificationIDs[i]);
_removeSale(saleVerificationIDs[i]);
}
}
function cancelOfferByOwner(bytes32[] calldata offerVerificationIDs) external onlyOwner {
for (uint256 i = 0; i < offerVerificationIDs.length; i++) {
OfferInfo storage offerInfo = _offerInfo[offerVerificationIDs[i]];
address item = offerInfo.item;
uint256 id = offerInfo.id;
Offer storage offer = offers[item][id][offerInfo.offerId];
address offeror = offer.offeror;
require(offeror != address(0));
uint256 amount = offer.amount;
uint256 _mileage = offer.mileage;
mix.transfer(offeror, amount.mul(offer.unitPrice).sub(_mileage));
if (_mileage > 0) {
mix.approve(address(mileage), _mileage);
mileage.charge(offeror, _mileage);
}
uint256 metaverseId = offer.metaverseId;
emit CancelOffer(metaverseId, item, id, amount, offerVerificationIDs[i]);
emit CancelOfferByOwner(metaverseId, item, id, offerVerificationIDs[i]);
_removeOffer(offerVerificationIDs[i]);
}
}
function cancelAuctionByOwner(bytes32[] calldata auctionVerificationIDs) external onlyOwner {
for (uint256 i = 0; i < auctionVerificationIDs.length; i++) {
AuctionInfo storage auctionInfo = _auctionInfo[auctionVerificationIDs[i]];
address item = auctionInfo.item;
uint256 id = auctionInfo.id;
Auction storage auction = auctions[item][id][auctionInfo.auctionId];
Bidding[] storage bs = biddings[auctionVerificationIDs[i]];
uint256 biddingLength = bs.length;
if (biddingLength > 0) {
Bidding storage lastBidding = bs[biddingLength - 1];
address lastBidder = lastBidding.bidder;
uint256 lastMileage = lastBidding.mileage;
mix.transfer(lastBidder, lastBidding.price.sub(lastMileage));
if (lastMileage > 0) {
mix.approve(address(mileage), lastMileage);
mileage.charge(lastBidder, lastMileage);
}
_removeUserBiddingInfo(lastBidder, auctionVerificationIDs[i]);
delete biddings[auctionVerificationIDs[i]];
}
uint256 metaverseId = auction.metaverseId;
_itemTransfer(metaverseId, item, id, auction.amount, address(this), auction.seller);
_removeAuction(auctionVerificationIDs[i]);
emit CancelAuction(metaverseId, item, id, auctionVerificationIDs[i]);
emit CancelAuctionByOwner(metaverseId, item, id, auctionVerificationIDs[i]);
}
}
}
|
SaleOfferAuctionBidding
|
interface IItemStore {
event Sell(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address seller,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
bytes32 indexed saleVerificationID
);
event ChangeSellPrice(uint256 indexed metaverseId, address indexed item, uint256 id, uint256 newUnitPrice, bytes32 indexed saleVerificationID);
event Buy(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address buyer,
uint256 amount,
bool isFulfilled,
bytes32 indexed saleVerificationID
);
event CancelSale(uint256 indexed metaverseId, address indexed item, uint256 id, uint256 amount, bytes32 indexed saleVerificationID);
event MakeOffer(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address offeror,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
bytes32 indexed offerVerificationID
);
event CancelOffer(uint256 indexed metaverseId, address indexed item, uint256 id, uint256 amount, bytes32 indexed offerVerificationID);
event AcceptOffer(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address acceptor,
uint256 amount,
bool isFulfilled,
bytes32 indexed offerVerificationID
);
event CreateAuction(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address seller,
uint256 amount,
uint256 startPrice,
uint256 endBlock,
bytes32 indexed auctionVerificationID
);
event CancelAuction(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed auctionVerificationID);
event Bid(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address bidder,
uint256 amount,
uint256 price,
bytes32 indexed auctionVerificationID,
uint256 biddingId
);
event Claim(
uint256 indexed metaverseId,
address indexed item,
uint256 id,
address bestBidder,
uint256 amount,
uint256 price,
bytes32 indexed auctionVerificationID,
uint256 biddingId
);
event CancelSaleByOwner(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed saleVerificationID);
event CancelOfferByOwner(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed offerVerificationID);
event CancelAuctionByOwner(uint256 indexed metaverseId, address indexed item, uint256 id, bytes32 indexed auctionVerificationID);
event Ban(address indexed user);
event Unban(address indexed user);
function fee() external view returns (uint256);
function feeReceiver() external view returns (address);
function auctionExtensionInterval() external view returns (uint256);
function isBanned(address user) external view returns (bool);
function batchTransfer(
uint256[] calldata metaverseIds,
address[] calldata items,
uint256[] calldata ids,
address[] calldata to,
uint256[] calldata amounts
) external;
function nonce(address user) external view returns (uint256);
function sales(
address item,
uint256 id,
uint256 saleId
)
external
view
returns (
address seller,
uint256 metaverseId,
address _item,
uint256 _id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
bytes32 verificationID
);
function onSales(address item, uint256 index) external view returns (bytes32 saleVerificationID);
function userSellInfo(address seller, uint256 index) external view returns (bytes32 saleVerificationID);
function salesOnMetaverse(uint256 metaverseId, uint256 index) external view returns (bytes32 saleVerificationID);
function userOnSaleAmounts(
address seller,
address item,
uint256 id
) external view returns (uint256);
function getSaleInfo(bytes32 saleVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 saleId
);
function salesCount(address item, uint256 id) external view returns (uint256);
function onSalesCount(address item) external view returns (uint256);
function userSellInfoLength(address seller) external view returns (uint256);
function salesOnMetaverseLength(uint256 metaverseId) external view returns (uint256);
function canSell(
address seller,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) external view returns (bool);
function sell(
uint256[] calldata metaverseIds,
address[] calldata items,
uint256[] calldata ids,
uint256[] calldata amounts,
uint256[] calldata unitPrices,
bool[] calldata partialBuyings
) external;
function changeSellPrice(bytes32[] calldata saleVerificationIDs, uint256[] calldata unitPrices) external;
function cancelSale(bytes32[] calldata saleVerificationIDs) external;
function buy(
bytes32[] calldata saleVerificationIDs,
uint256[] calldata amounts,
uint256[] calldata unitPrices,
uint256[] calldata mileages
) external;
function offers(
address item,
uint256 id,
uint256 offerId
)
external
view
returns (
address offeror,
uint256 metaverseId,
address _item,
uint256 _id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
uint256 mileage,
bytes32 verificationID
);
function userOfferInfo(address offeror, uint256 index) external view returns (bytes32 offerVerificationID);
function getOfferInfo(bytes32 offerVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 offerId
);
function userOfferInfoLength(address offeror) external view returns (uint256);
function offersCount(address item, uint256 id) external view returns (uint256);
function canOffer(
address offeror,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) external view returns (bool);
function makeOffer(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 unitPrice,
bool partialBuying,
uint256 mileage
) external returns (uint256 offerId);
function cancelOffer(bytes32 offerVerificationID) external;
function acceptOffer(bytes32 offerVerificationID, uint256 amount) external;
function auctions(
address item,
uint256 id,
uint256 auctionId
)
external
view
returns (
address seller,
uint256 metaverseId,
address _item,
uint256 _id,
uint256 amount,
uint256 startTotalPrice,
uint256 endBlock,
bytes32 verificationID
);
function onAuctions(address item, uint256 index) external view returns (bytes32 auctionVerificationID);
function userAuctionInfo(address seller, uint256 index) external view returns (bytes32 auctionVerificationID);
function auctionsOnMetaverse(uint256 metaverseId, uint256 index) external view returns (bytes32 auctionVerificationID);
function getAuctionInfo(bytes32 auctionVerificationID)
external
view
returns (
address item,
uint256 id,
uint256 auctionId
);
function auctionsCount(address item, uint256 id) external view returns (uint256);
function onAuctionsCount(address item) external view returns (uint256);
function userAuctionInfoLength(address seller) external view returns (uint256);
function auctionsOnMetaverseLength(uint256 metaverseId) external view returns (uint256);
function canCreateAuction(
address seller,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount
) external view returns (bool);
function createAuction(
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 startTotalPrice,
uint256 endBlock
) external returns (uint256 auctionId);
function cancelAuction(bytes32 auctionVerificationID) external;
function biddings(bytes32 auctionVerificationID, uint256 biddingId)
external
view
returns (
address bidder,
uint256 metaverseId,
address item,
uint256 id,
uint256 amount,
uint256 price,
uint256 mileage
);
function userBiddingInfo(address bidder, uint256 index) external view returns (bytes32 auctionVerificationID, uint256 biddingId);
function userBiddingInfoLength(address bidder) external view returns (uint256);
function biddingsCount(bytes32 auctionVerificationID) external view returns (uint256);
function canBid(
address bidder,
uint256 price,
bytes32 auctionVerificationID
) external view returns (bool);
function bid(
bytes32 auctionVerificationID,
uint256 price,
uint256 mileage
) external returns (uint256 biddingId);
function claim(bytes32 auctionVerificationID) external;
}
}
| 935,083 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Mask SVG generator
library MaskDetail {
/// @dev Mask N°1 => None
function item_1() public pure returns (string memory) {
return base("", "None");
}
/// @dev Mask N°2 => Uni Horn Blood
function item_2() public pure returns (string memory) {
return base(horn("E31466"), "Uni Horn Blood");
}
/// @dev Mask N°3 => Power Sticks
function item_3() public pure returns (string memory) {
return base(powerStick("000000"), "Power sticks");
}
/// @dev Mask N°4 => Uni Horn Moon
function item_4() public pure returns (string memory) {
return base(horn("2A2C38"), "Uni Horn Moon");
}
/// @dev Mask N°5 => Power Neck
function item_5() public pure returns (string memory) {
return
base(
'<g display="inline"><path stroke="#000000" stroke-miterlimit="10" d="M254,291l22.2-0.1c0.3,0.4,2.5,4.3,0,9H254C252.1,296.7,251.9,293.7,254,291z" /><g><path d="M251.9,289.3c-1,2-1.8,4-1.9,6c0,1,0,2.1,0.3,3.1c0.1,0.5,0.3,1,0.4,1.6c0.2,0.5,0.4,1,0.6,1.6c-0.4-0.4-0.7-0.8-1-1.4c-0.3-0.5-0.6-0.9-0.7-1.6c-0.4-1-0.6-2.2-0.6-3.4c0-1.1,0.3-2.3,0.8-3.3C250.4,290.9,251.1,289.9,251.9,289.3z" /></g></g><g display="inline"><path stroke="#000000" stroke-miterlimit="10" d="M177.4,292.4l-20-0.1c-0.3,0.4-2.3,4.3,0,9h20C179.2,298.1,179.5,295.2,177.4,292.4z" /><g><path d="M179.5,290.7c0.8,0.7,1.6,1.7,2.1,2.7s0.8,2.2,0.8,3.3s-0.1,2.3-0.6,3.4c-0.2,0.5-0.5,1-0.7,1.6c-0.3,0.5-0.7,0.9-1,1.4c0.2-0.5,0.4-1,0.6-1.6c0.1-0.5,0.3-1,0.4-1.6c0.3-1,0.3-2.1,0.3-3.1C181.3,294.7,180.5,292.7,179.5,290.7z" /></g></g>',
"Power Neck"
);
}
/// @dev Mask N°6 => Bouc
function item_6() public pure returns (string memory) {
return
base(
'<path id="Bouc" d="M189.4,279c0,0,8.8,9.2,9.8,10c0.7-0.7,6.4-14.7,6.4-14.7l5.8,14.7l10.4-10l-16.3,71L189.4,279z"/>',
"Bouc"
);
}
/// @dev Mask N°7 => BlindFold Tomoe Blood
function item_7() public pure returns (string memory) {
return base(blindfold("D4004D", "FFEDED"), "Blindfold Tomoe Blood");
}
/// @dev Mask N°8 => Strap Blood
function item_8() public pure returns (string memory) {
return base(strap("D9005E"), "Strap Blood");
}
/// @dev Mask N°9 => Sun Glasses
function item_9() public pure returns (string memory) {
return
base(
'<g display="inline" opacity="0.95"><ellipse stroke="#000000" stroke-miterlimit="10" cx="164.6" cy="189.5" rx="24.9" ry="24.8" /><ellipse stroke="#000000" stroke-miterlimit="10" cx="236.3" cy="188.5" rx="24.9" ry="24.8" /></g><path display="inline" fill="none" stroke="#000000" stroke-miterlimit="10" d="M261.1,188.6l32.2-3.6 M187,188.6c0,0,15.3-3.2,24.5,0 M140.6,189l-7.1-3" />',
"Sun glasses"
);
}
/// @dev Mask N°10 => Uni Horn Pure
function item_10() public pure returns (string memory) {
return base(horn("FFDAEA"), "Uni Horn Pure");
}
/// @dev Mask N°11 => Strap Moon
function item_11() public pure returns (string memory) {
return base(strap("575673"), "Strap Moon");
}
/// @dev Mask N°12 => BlindFold Tomoe Moon
function item_12() public pure returns (string memory) {
return base(blindfold("000000", "B50D5E"), "BlindFold Tomoe Moon");
}
/// @dev Mask N°13 => Stitch
function item_13() public pure returns (string memory) {
return
base(
'<g display="inline"><path d="M175.8,299.3c7.2,1.8,14.4,2.9,21.7,3.9c1.9,0.2,3.5,0.5,5.4,0.7s3.6,0.3,5.4,0.5c3.6,0.2,7.2,0.2,10.9,0.1c3.6-0.1,7.2-0.5,10.9-0.7l5.4-0.6c0.9-0.1,1.9-0.2,2.7-0.3l2.7-0.4c7.2-1,14.4-2.9,21.5-4.8v0.1l-5.5,1.9l-2.7,0.8c-0.9,0.3-1.8,0.5-2.7,0.7l-5.4,1.4c-1.9,0.4-3.5,0.6-5.4,1c-3.5,0.7-7.2,0.9-10.9,1.4c-3.6,0.2-7.2,0.4-10.9,0.3c-7.2-0.1-14.6-0.3-21.8-0.9C190.1,303.1,182.8,301.8,175.8,299.3L175.8,299.3z" /></g><path display="inline" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M206.9,304.5c0,0,5.3-2.1,11.8,0.2C218.8,304.7,212.8,307.6,206.9,304.5z" /><g display="inline"><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M222.1,301c0,0,0.7-3.4,1.9-1c0,0,0.3,5.3-0.5,9.9c0,0-0.7,2.2-1-0.6C222.1,306.5,222.7,306.2,222.1,301z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M227.4,301.2c0,0,0.7-3.1,1.7-0.9c0,0,0.3,4.7-0.4,8.9c0,0-0.6,1.9-0.9-0.5C227.4,306.1,228.2,305.8,227.4,301.2z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M231.8,301.1c0,0,0.6-2.7,1.5-0.8c0,0,0.3,4.1-0.3,7.7c0,0-0.5,1.7-0.7-0.4C231.8,305.3,232.3,305.1,231.8,301.1z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M235.5,300.8c0,0,0.5-2.4,1.4-0.7c0,0,0.3,3.6-0.3,6.9c0,0-0.5,1.5-0.7-0.4C235.6,304.6,236,304.4,235.5,300.8z" /></g><g display="inline"><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M203.8,300.5c0,0-0.7-3.4-1.9-1c0,0-0.3,5.3,0.5,9.9c0,0,0.7,2.2,1-0.6C203.8,306,203.1,305.8,203.8,300.5z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M198.5,300.8c0,0-0.7-3.1-1.7-0.9c0,0-0.3,4.7,0.4,8.9c0,0,0.6,1.9,0.9-0.5C198.5,305.8,197.7,305.3,198.5,300.8z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M194.1,300.6c0,0-0.6-2.7-1.5-0.8c0,0-0.3,4.1,0.3,7.7c0,0,0.5,1.7,0.7-0.4C193.9,305,193.6,304.7,194.1,300.6z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M190.4,300.3c0,0-0.5-2.4-1.4-0.7c0,0-0.3,3.6,0.3,6.9c0,0,0.5,1.5,0.7-0.4C190.4,304.2,189.9,304,190.4,300.3z" /></g>',
"Stitch"
);
}
/// @dev Mask N°14 => Strap Pure
function item_14() public pure returns (string memory) {
return base(strap("F2F2F2"), "Strap Pure");
}
/// @dev Mask N°15 => Eye Patch
function item_15() public pure returns (string memory) {
return
base(
'<g id="MASK EYE" display="inline"><g><path fill="#FCFEFF" d="M257.9,210.4h-36.1c-4.9,0-8.9-4-8.9-8.9v-21.7c0-4.9,4-8.9,8.9-8.9h36.1c4.9,0,8.9,4,8.9,8.9v21.8C266.6,206.4,262.8,210.4,257.9,210.4z"/><path d="M257.9,210.4l-10.7,0.1l-10.7,0.2c-3.6,0.1-7.1,0.1-10.7,0.1h-2.7h-1.3c-0.5,0-0.9,0-1.4-0.1c-1.9-0.3-3.6-1.2-4.9-2.5c-1.4-1.3-2.3-3-2.6-4.8c-0.2-0.9-0.2-1.9-0.2-2.7V198c0.1-3.6,0.1-7.1,0.1-10.7v-5.4c0-0.9,0-1.8,0-2.7c0.1-0.9,0.2-1.8,0.6-2.7c0.6-1.7,1.8-3.2,3.3-4.3c0.8-0.5,1.6-0.9,2.4-1.2c0.9-0.3,1.8-0.4,2.7-0.4l21.4-0.2l10.7-0.1h2.7h1.3c0.5,0,0.9,0,1.4,0.1c1.9,0.3,3.6,1.2,5,2.5s2.3,3,2.7,4.9c0.2,0.9,0.2,1.9,0.2,2.8v2.7l-0.1,10.7l-0.1,5.4c0,0.9,0,1.8-0.1,2.7s-0.3,1.8-0.7,2.6c-0.7,1.7-1.8,3.2-3.3,4.2c-0.7,0.5-1.6,0.9-2.4,1.2C259.7,210.3,258.8,210.4,257.9,210.4z M257.9,210.3c0.9,0,1.8-0.2,2.6-0.4c0.8-0.3,1.6-0.7,2.4-1.2c1.4-1,2.6-2.5,3.2-4.2c0.3-0.8,0.5-1.7,0.5-2.6c0.1-0.9,0-1.8,0-2.7l-0.1-5.4l-0.1-10.7v-2.7c0-0.9,0-1.7-0.2-2.6c-0.4-1.6-1.2-3.2-2.5-4.3c-1.2-1.2-2.8-1.9-4.5-2.2c-0.4-0.1-0.8-0.1-1.3-0.1h-1.3h-2.7l-10.7-0.1l-21.4-0.2c-3.5-0.1-6.9,2.2-8.1,5.5c-0.7,1.6-0.6,3.4-0.6,5.2v5.4c0,3.6,0,7.1,0.1,10.7v2.7c0,0.9,0,1.7,0.2,2.6c0.4,1.7,1.3,3.2,2.5,4.4s2.8,2,4.5,2.2c0.8,0.1,1.7,0.1,2.6,0.1h2.7c3.6,0,7.1,0,10.7,0.1l10.7,0.2L257.9,210.3z"/></g><g><path d="M254.2,206.4c-5.7,0-11.4,0.1-17,0.2c-2.8,0.1-5.7,0.1-8.5,0.1h-2.1c-0.7,0-1.4,0-2.2-0.1c-1.5-0.2-2.9-0.9-4-1.9s-1.8-2.4-2.2-3.8c-0.2-0.7-0.2-1.5-0.2-2.2v-2.1c0-2.8,0.1-5.7,0.1-8.5v-4.3c0-0.7,0-1.4,0-2.1c0.1-0.7,0.2-1.4,0.5-2.1c0.5-1.4,1.5-2.5,2.6-3.4c0.6-0.4,1.3-0.7,2-1c0.7-0.2,1.4-0.3,2.2-0.3l17-0.1h8.5h2.1c0.7,0,1.4,0,2.2,0.1c1.5,0.2,2.9,0.9,4,1.9s1.9,2.4,2.2,3.8c0.2,0.7,0.2,1.5,0.2,2.2v2.1l-0.1,8.5l-0.1,4.3c0,0.7,0,1.4-0.1,2.1c-0.1,0.7-0.2,1.4-0.5,2.1c-0.5,1.3-1.5,2.5-2.7,3.3C257.1,206,255.6,206.4,254.2,206.4z M254.2,206.4c1.4,0,2.8-0.4,4-1.2s2.1-1.9,2.6-3.3c0.2-0.7,0.4-1.4,0.4-2c0-0.7,0-1.4,0-2.1l-0.1-4.3L261,185v-2.1c0-0.7,0-1.4-0.2-2c-0.3-1.3-1-2.5-2-3.4s-2.3-1.5-3.6-1.7c-0.7-0.1-1.3-0.1-2.1-0.1H251h-8.5l-17-0.1c-2.8-0.1-5.5,1.7-6.5,4.3c-0.3,0.6-0.4,1.3-0.5,2s0,1.4,0,2.1v4.3c0,2.8,0,5.7,0.1,8.5v2.1c0,0.7,0,1.4,0.2,2.1c0.3,1.3,1,2.6,2.1,3.5c1,0.9,2.3,1.5,3.6,1.7c0.7,0.1,1.4,0.1,2.1,0.1h2.1c2.8,0,5.7,0,8.5,0.1C242.8,206.3,248.5,206.4,254.2,206.4z"/></g><g><path d="M214.4,174.8c-7-0.5-13.9-1.1-20.8-1.8c-3.5-0.4-6.9-0.8-10.4-1.1s-7-0.5-10.4-0.6c-7-0.3-13.9-0.5-20.9-0.9c-7-0.3-13.9-0.7-20.9-1.2c0,0,0,0,0-0.1l0,0c7-0.1,13.9,0,20.9,0.3s13.9,0.7,20.9,1.3c3.5,0.3,6.9,0.6,10.4,0.8l10.4,0.6C200.6,172.8,207.5,173.6,214.4,174.8C214.4,174.8,214.5,174.8,214.4,174.8C214.4,174.8,214.4,174.9,214.4,174.8z"/></g><g><path d="M265.2,175c2.8,0,5.5,0.3,8.2,0.7c1.4,0.3,2.7,0.6,4,0.8c1.4,0.2,2.7,0.4,4.1,0.5c2.7,0.2,5.5,0.6,8.2,1.1s5.4,1.2,8,2.1c0,0,0,0,0,0.1c0,0,0,0-0.1,0c-2.7-0.3-5.4-0.7-8.1-1.2s-5.4-1-8.1-1.6c-1.3-0.3-2.7-0.6-4.1-0.7c-1.4-0.2-2.7-0.2-4.1-0.3C270.6,176.2,267.9,175.8,265.2,175L265.2,175L265.2,175z"/></g><g><path d="M263.6,208.2c1.7,2.6,3.3,5.3,4.7,8.1c0.7,1.4,1.3,2.8,2.1,4.2c0.8,1.4,1.6,2.7,2.5,4c1.8,2.6,3.4,5.2,5.1,7.9c1.6,2.7,3.2,5.3,4.7,8.1v0.1c0,0,0,0-0.1,0c-2-2.4-3.8-5-5.6-7.6c-1.7-2.6-3.3-5.4-4.7-8.1c-0.7-1.4-1.5-2.8-2.3-4.1s-1.7-2.6-2.5-4C266,214,264.7,211.2,263.6,208.2C263.5,208.2,263.6,208.2,263.6,208.2C263.6,208.1,263.6,208.2,263.6,208.2z"/></g><g><path d="M213.9,206.7c-5.8,2.8-11.7,5.2-17.7,7.4l-4.5,1.5c-1.5,0.5-3,1-4.5,1.5c-3,1-6,2.1-9,3.2c-6,2.2-12.1,4.1-18.2,5.8c-6.1,1.7-12.3,3.2-18.6,4.4h-0.1v-0.1l36.7-10.7c3.1-0.9,6.1-1.9,9.1-3s5.9-2.3,8.9-3.5C201.9,211,207.9,208.8,213.9,206.7C213.9,206.6,213.9,206.7,213.9,206.7C214,206.7,213.9,206.7,213.9,206.7z"/></g></g>',
"Eye Patch"
);
}
/// @dev Mask N°16 => Eye
function item_16() public pure returns (string memory) {
return
base(
'<path d="M199.9,132.9s-15.2,17-.1,39.9C199.9,172.7,214.8,154.7,199.9,132.9Z" transform="translate(0 0.5)" /> <path d="M207,139.4c3.51,8.76,3.82,19.26-1,27.6C209.59,158.25,209.25,148.47,207,139.4Z" transform="translate(0 0.5)"/> <path d="M190.9,155.2c.81,5.6,1.84,11.19,4.9,16.1C192.1,167,191,160.73,190.9,155.2Z" transform="translate(0 0.5)"/> <path d="M202.27,142.35c1-.3,2.1,6.26,1.07,6.31C202.34,149,201.23,142.4,202.27,142.35Z" transform="translate(0 0.5)" fill="#fff"/>',
"Eye"
);
}
/// @dev Mask N°17 => Nihon
function item_17() public pure returns (string memory) {
return
base(
'<path id="Nihon" display="inline" fill="#FFFFFF" stroke="#000000" stroke-width="2" stroke-miterlimit="10" d="M175.3,307.1c0,0,21.5,15.8,85.9,0.3c0.3-0.1,0.4-0.3,0.4-0.5c0-2.7,0-17.9,4.6-46.5c0-0.1,0.1-0.2,0.1-0.3c1.1-1.6,13.5-17.6,15.9-20.6c0.2-0.3,0.1-0.6-0.2-0.8c-5.3-3.2-47.8-29-83-38c-1.1-0.3-3.1-0.7-4.2-0.2c-17.5,7.4-46.3,28.9-52.8,33.9c-0.8,0.6-0.9,1.7-0.7,2.7c1.5,5.3,8.2,19.9,10.2,21.8c1.8,1.7,23.1,18.5,23.1,18.5s0.7,0.2,0.7,0.3C175.8,278.6,177.7,287,175.3,307.1z" /><path display="inline" fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M175.8,277.7c0,0,21.3,17.6,29.6,17.9s15.7-4,16.6-4.5c0.9-0.4,19-9.1,33.1-20.7 M267,259.4c-3.2,3.5-7.3,7.3-11.9,11" /><path display="inline" fill="#696969" d="M199.5,231.6l-8.2-3.6c-0.4-0.2-0.5-0.7-0.2-1.1l3.3-3.4c0.4-0.4,1-0.5,1.6-0.3l13.2,4.8c0.6,0.2,0.6,1.1-0.1,1.4l-9.1,2.5C199.8,231.7,199.5,231.7,199.5,231.6z M175.5,278.2c0,0,26.5,36.4,43.2,32c16.8-4.4,43.7-21.8,43.7-21.8c1.3-9.1,2.2-19.7,3.3-28.7c-4.8,4.9-13.3,13.8-21.8,19.1c-5.2,3.2-22.1,15.1-36.4,16.7C200,296.3,175.5,278.2,175.5,278.2z" /><ellipse display="inline" opacity="0.87" fill="#FF0057" enable-background="new " cx="239.4" cy="248.4" rx="14" ry="15.1" />',
"Nihon"
);
}
/// @dev Mask N°18 => BlindFold Tomoe Pure
function item_18() public pure returns (string memory) {
return base(blindfold("FFEDED", "B50D5E"), "BlindFold Tomoe Pure");
}
/// @dev Mask N°19 => Power Sticks Pure
function item_19() public pure returns (string memory) {
return base(powerStick("FFEDED"), "Power Sticks Pure");
}
/// @dev Mask N°20 => ???
function item_20() public pure returns (string memory) {
return
base(
'<path display="inline" fill="#F5F4F3" stroke="#000000" stroke-width="3" stroke-miterlimit="10" d="M290.1,166.9c0,71-20.4,132.3-81.2,133.3c-60.9,0.9-77.5-59.4-77.5-130.4s15-107.6,75.8-107.6C270.4,62.3,290.1,96,290.1,166.9z" /><path display="inline" opacity="8.000000e-02" enable-background="new " d="M290,165.9c0,71-20.2,132.7-81.3,134.4c28.3-18.3,29.5-51.1,29.5-121.9S263,89,206.9,62.4C270.2,62.4,290,95,290,165.9z" /><ellipse display="inline" cx="245.9" cy="169.9" rx="17.6" ry="6.4" /><path display="inline" d="M233.7,266.5c0.3-7.5-12.6-6.4-28.3-6.4s-28.6-1.5-28.3,6.4c0.1,3.5,12.6,6.4,28.3,6.4S233.6,270,233.7,266.5z" /><ellipse display="inline" cx="161.5" cy="169.7" rx="17" ry="6.3" /><path display="inline" fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M148.5,181c0,0,7,6,21.4,0.6" /><path display="inline" fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M235.2,180.9c0,0,6.9,5.9,21.3,0.6" /><path display="inline" fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M193.4,278.5c0,0,9.6,3.6,22.5,0" /><path display="inline" fill="#996DAD" d="M149.8,190.5c1.6-3.8,17.9-3.5,19.6-0.4c1.9,3.3-5,47.5-6.9,47.8C159.2,238.6,146.9,201.5,149.8,190.5z" /><path display="inline" fill="#996DAD" d="M236.3,189.8c1.6-3.8,18.8-2.8,20.5,0.3c3.9,6.7-6.8,47.3-9.7,47.2C243.6,237,233.4,200.8,236.3,189.8z" /><path display="inline" fill="#996DAD" d="M233.6,149c1.4,2.4,15.3,2.2,16.8,0.2c1.7-2.1-4.3-28.8-7.5-29.3C239.4,119.5,231.1,142.3,233.6,149z" /><path display="inline" fill="#996DAD" d="M151.9,151.7c1.4,2.4,15.3,2.2,16.8,0.2c1.7-2.1-4.3-28.8-7.5-29.3C157.8,122.1,149.5,144.9,151.9,151.7z" />',
"???"
);
}
function powerStick(string memory color) private pure returns (string memory) {
return
string(
abi.encodePacked(
abi.encodePacked(
'<path style="fill:#',
color,
";stroke:#",
color,
';stroke-miterlimit:10;" d="M276.3,325.2l9.2-20.2c0.5-0.2,5-0.4,8.1,3.8l-9.3,20.1C280.7,329.3,277.8,328.2,276.3,325.2z"/><ellipse transform="matrix(0.4183 -0.9083 0.9083 0.4183 -110.5579 441.5047)" style="fill:#',
color,
';" cx="289.4" cy="307.1" rx="1.7" ry="4.4"/><path d="M273.9,326.4c2.6,3.8,6.4,5.6,10.9,5.5C280.5,333.5,275,331.1,273.9,326.4z"/><path style="fill:#',
color,
";stroke:#",
color,
';stroke-miterlimit:10;" d="M304,341.3l9.9-19.9c0.5-0.1,5-0.3,7.9,4.1l-9.9,19.8C308.3,345.6,305.4,344.5,304,341.3z"/>'
),
abi.encodePacked(
'<ellipse transform="matrix(0.4485 -0.8938 0.8938 0.4485 -113.8785 462.7307)" style="fill:#',
color,
';" cx="318" cy="323.6" rx="1.7" ry="4.4"/><path d="M301.6,342.6c2.5,3.9,6.3,5.8,10.8,6C308.1,350,302.6,347.2,301.6,342.6z"/> <path style="fill:#',
color,
";stroke:#",
color,
';stroke-miterlimit:10;" d="M154.7,323.7l-7.1-21.1c-0.4-0.2-4.9-0.9-8.4,2.9l7.1,21.1C150,327.3,152.9,326.6,154.7,323.7z"/><ellipse transform="matrix(0.9467 -0.322 0.322 0.9467 -90.3736 62.4201)" style="fill:#',
color,
';" cx="143.5" cy="304.4" rx="4.4" ry="1.7"/><path d="M157.1,325.2c-1.7,4.4-7.2,6.4-11.5,4.5C150,330.3,154.2,328.7,157.1,325.2z"/>'
),
abi.encodePacked(
'<path style="fill:#',
color,
";stroke:#",
color,
';stroke-miterlimit:10;" d="M122.5,334.4l-7.7-20.8c-0.4-0.2-4.9-0.8-8.3,3.1l7.8,20.7C117.9,338.2,120.6,337.3,122.5,334.4z"/> <ellipse transform="matrix(0.9364 -0.3508 0.3508 0.9364 -103.5719 58.8717)" style="fill:#',
color,
';" cx="110.7" cy="315.3" rx="4.4" ry="1.7"/><path d="M124.8,335.9c-1.4,4.4-6.9,6.8-11.2,4.8C117.9,341.1,122.2,339.3,124.8,335.9z"/>'
)
)
);
}
function blindfold(string memory colorBlindfold, string memory colorTomoe) private pure returns (string memory) {
return
string(
abi.encodePacked(
abi.encodePacked(
'<path display="inline" opacity="0.22" enable-background="new " d="M135.7,204.6 c0,0,45,25.9,146.6,0.3C287.1,206.1,189.1,221.5,135.7,204.6z"/> <g display="inline"> <path fill="#',
colorBlindfold,
'" stroke="#000000" stroke-miterlimit="10" d="M202.4,212.5c-26.8,0-49.2-2.8-66.6-8.4 c-5.3-14.6-5.5-31.4-5.5-36.5c19,5.4,44.2,6.6,74.8,6.6c46.3,0,91.3-7.8,99.7-9.1c-0.3,2.1-1.4,9-1.5,10.4 c-1.1,1.3-4.4,4.5-5.5,5.3c-3.1,2.1-2.1,2.4-5.4,7.1c0,0-2.7,5.1-3.2,6.4c-4.8,12.1-6.1,9.6-18.8,13.3 C246.2,210.8,223.3,212.5,202.4,212.5z"/> </g> <g display="inline"> <path fill="none" stroke="#000000" stroke-miterlimit="10" d="M283.6,203.5c0,0,17-24.4,14.9-37.3"/> <g opacity="0.91"> <path d="M133.9,168.6c4,4.6,8,9.1,12.2,13.4c1,1.1,2.1,2.2,3.1,3.2l1.6,1.7l1.7,1.6c2.2,2.1,4.6,4,6.9,5.8 c4.8,3.8,9.8,7.1,14.9,10.2c5.2,3,10.6,5.6,16.4,7.7l0,0l0,0c-5.8-1.7-11.5-4.1-16.7-7.1c-5.2-3.1-10.1-6.7-14.8-10.5 c-2.3-2-4.6-4-6.8-6c-1.1-1-2.3-2-3.3-3c-1.1-1-2.2-2.1-3.3-3.1c-2.2-2.1-4.2-4.4-6.1-6.7C137.5,173.5,135.6,171.1,133.9,168.6 L133.9,168.6L133.9,168.6z"/> </g> <g opacity="0.91"> <path d="M201.4,212.6c3.6-0.5,7.2-1.8,10.6-3.1c3.4-1.4,6.9-2.8,10.2-4.3c3.4-1.5,6.8-3,10.1-4.7s6.6-3.5,9.7-5.4 c6.4-3.8,12.6-7.7,18.8-11.9c3-2.1,6-4.3,9-6.6c2.9-2.3,5.7-4.7,8.1-7.5c0,0,0,0,0.1,0c0,0,0,0,0,0.1c-2.2,3-5,5.5-7.8,7.9 s-5.8,4.6-8.9,6.8c-6.1,4.3-12.5,8-19.1,11.6l-9.8,5.2c-3.3,1.7-6.6,3.4-9.9,5.1c-3.3,1.6-6.8,3-10.3,4.3 C208.7,211.2,205,212.4,201.4,212.6L201.4,212.6L201.4,212.6z"/> </g> <path opacity="0.14" enable-background="new " d="M278.4,169.7 c0,0-25.9,38-71.8,42.3C206.6,211.9,252.6,193.4,278.4,169.7z"/> <path opacity="0.14" enable-background="new " d="M297.3,166.3c0,0,5,10-14.5,37.2 C282.8,203.5,293.4,184.2,297.3,166.3z"/> <path opacity="0.14" enable-background="new " d="M133.6,169 c0,0,12.5,34.7,54.9,42.9C188.6,212.1,155.2,197,133.6,169z"/> <polygon opacity="0.18" enable-background="new " points="298.4,166.6 295.8,181.6 303.6,175.7 304.9,165.1 "/> <path opacity="0.2" stroke="#000000" stroke-miterlimit="10" enable-background="new " d=" M131.2,168.4c0,0,55.6,17.3,172.7-3.2C308.7,166.4,183.7,189.6,131.2,168.4z"/> </g> <g display="inline"> <g> <path fill="#',
colorTomoe,
'" d="M202.3,199.8c0,0-0.6,5.1-8.1,8.1c0,0,2.5-2.3,2.9-5.2"/> <path fill="#',
colorTomoe,
'" d="M202.3,200.1c0.8-2.3-0.4-4.7-2.7-5.4 c-2.3-0.8-4.7,0.4-5.4,2.7c-0.8,2.3,0.4,4.7,2.7,5.4C199,203.5,201.4,202.4,202.3,200.1z M196.7,198.2c0.3-0.8,1-1.1,1.8-0.9 c0.8,0.3,1.1,1,0.9,1.8c-0.3,0.8-1,1.1-1.8,0.9C196.9,199.9,196.5,199,196.7,198.2z"/> </g>'
),
abi.encodePacked(
'<g> <path fill="#',
colorTomoe,
'" d="M205.4,183.2c0,0,4.8-1.9,11,3.2c0,0-3.2-1.1-5.9-0.1"/> <path fill="#',
colorTomoe,
'" d="M205.5,183.1c-2.4,0.4-4,2.7-3.4,5c0.4,2.4,2.7,4,5,3.4 c2.4-0.4,4-2.7,3.4-5C210.2,184.2,207.9,182.7,205.5,183.1z M206.6,188.8c-0.8,0.1-1.5-0.4-1.7-1.1c-0.1-0.8,0.4-1.5,1.1-1.7 c0.8-0.1,1.5,0.4,1.7,1.1S207.3,188.6,206.6,188.8z"/> </g> <g> <path fill="#',
colorTomoe,
'" d="M187.5,190.7c0,0-4.4-2.6-4.3-10.7c0,0,1,3.2,3.5,4.7"/> <path fill="#',
colorTomoe,
'" d="M187.3,190.6c1.8,1.7,4.5,1.5,6-0.3c1.7-1.8,1.5-4.5-0.3-6 c-1.8-1.7-4.5-1.5-6,0.3C185.4,186.3,185.4,188.9,187.3,190.6z M191.2,186.2c0.6,0.6,0.6,1.4,0.1,2c-0.6,0.6-1.4,0.6-2,0.1 c-0.6-0.6-0.6-1.4-0.1-2C189.6,185.8,190.4,185.8,191.2,186.2z"/> </g> </g>'
)
)
);
}
function horn(string memory color) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<g><path d="M199.5,130.4c-6.8-.1-13.1-6.5-15-15.2,1.5-25.1,9.6-74.1,12.4-90.7,1.5,30.2,18.4,88.63,19.5,92.33-4.2,10.6-10,13.67-16.9,13.57Z" transform="translate(0 0.5)" fill="#',
color,
'"/> <path d="M196.6,28.9c2.7,30.6,17.1,83.43,18.6,88.13-4.2,10.4-9.2,13-15.8,12.87s-12.6-6.3-14.5-14.7c1.6-23.3,8.6-66.7,11.7-86.3m.7-10.2S186,85.75,184.19,116.45c1.9,8.9,8.11,14.15,15.31,14.35,6.1.1,12.1-1.57,16.9-14,0,.1-19.9-68.83-19.1-98.13Z" transform="translate(0 0.5)"/> <path d="M185.38,115.74s1.09,14.54,12.58,15c10.49.43,13.21-4.4,16.69-13.85" transform="translate(0 0.5)" fill="#',
color,
'" stroke="#',
color,
'" stroke-linecap="round" stroke-miterlimit="10" /></g>'
)
);
}
function strap(string memory color) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<g><path id="Classic" d="M174.76,306.81s22.1,16.3,86.9.5c0,0-.5-15.3,4.6-47.1l16.5-21.3s-46-28.7-83.5-38.3c-1.1-.3-3.1-.7-4.2-.2-19.9,8.4-54.1,34.8-54.1,34.8s9,20.8,10.8,23.4c1.4,2,23.1,18.5,23.1,18.5s.7.2.7.3C175.76,278.61,177.06,286.71,174.76,306.81Z" transform="translate(0 0.5)" fill="#',
color,
'" stroke="#000" stroke-miterlimit="10"/><path d="M199.5,231.6l-8.2-3.6a.71.71,0,0,1-.2-1.1l3.3-3.4a1.53,1.53,0,0,1,1.6-.3l13.2,4.8a.75.75,0,0,1-.1,1.4l-9.1,2.5C199.8,231.7,199.5,231.7,199.5,231.6Zm-24,46.6s26.5,36.4,43.2,32,43.7-21.8,43.7-21.8c1.3-9.1,2.2-19.7,3.3-28.7-4.8,4.9-13.3,13.8-21.8,19.1-5.2,3.2-22.1,15.1-36.4,16.7C200,296.3,175.5,278.2,175.5,278.2Z" transform="translate(0 0.5)" opacity="0.21" style="isolation: isolate"/> <path d="M142.2,237.5c35.7-22.7,64-30.2,98.5-21.1m30.6,36.9c-21.9-16.9-64.5-38-78.5-32.4-13.3,7.4-37,18-46.8,25.3m88-15.4c-33.8,2.6-57.2.1-84.7,23.6m115.5,7.2c-20.5-14.5-48.7-25.1-73.9-27m23,3.8c-19.3,2-43.6,11.7-59.1,22.8m106.1,4.2c-47.9-12.4-52.5-26.6-98,2.8m69.2-11.5c-20.7.3-43.9,9.9-63.3,16.4m72.4,7.2c-11.5-4.1-40.1-14.8-52.5-14.2m28.3,6c-10.7-2.9-24,7.9-32,13.1m39.3,4.8c-4-5.7-23-7.4-28.1-11.9M175.5,302c4.3,3.8,21.4,7.3,39.5,7.2,18.5-.1,38.1-4,46.6-8.6M176.4,294c11.6,3.8,18.2,7.3,38.1,5.9,15.1-1,34.3-4,47.8-10.7m-38.25.63c9.4,0,29.85-4.63,38.65-7.53m-21.8-2c3.4.4,20-5.4,23.6-6.8m-47-60.8a141,141,0,0,0-19.8-3.2c-5-.3-15.5-.2-20.6.6" transform="translate(0 0.5)" fill="none" stroke="#000" stroke-miterlimit="10"/> </g>'
)
);
}
/// @notice Return the skin name of the given id
/// @param id The skin Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "None";
} else if (id == 2) {
name = "Uni Horn Blood";
} else if (id == 3) {
name = "Power Sticks";
} else if (id == 4) {
name = "Uni Horn Moon";
} else if (id == 5) {
name = "Power Neck";
} else if (id == 6) {
name = "Bouc";
} else if (id == 7) {
name = "BlindFold Tomoe Blood";
} else if (id == 8) {
name = "Strap Blood";
} else if (id == 9) {
name = "Sun Glasses";
} else if (id == 10) {
name = "Uni Horn Pure";
} else if (id == 11) {
name = "Strap Moon";
} else if (id == 12) {
name = "BlindFold Tomoe Moon";
} else if (id == 13) {
name = "Stitch";
} else if (id == 14) {
name = "Strap Pure";
} else if (id == 15) {
name = "Eye Patch";
} else if (id == 16) {
name = "Eye";
} else if (id == 17) {
name = "Nihon";
} else if (id == 18) {
name = "BlindFold Tomoe Pure";
} else if (id == 19) {
name = "Power Sticks Pure";
} else if (id == 20) {
name = "???";
}
}
/// @dev The base SVG for the body
function base(string memory children, string memory name) private pure returns (string memory) {
return string(abi.encodePacked('<g id="mask"><g id="', name, '">', children, "</g></g>"));
}
}
|
Mask N°19 => Power Sticks Pure
|
function item_19() public pure returns (string memory) {
return base(powerStick("FFEDED"), "Power Sticks Pure");
}
| 1,757,557 |
./full_match/137/0x6ceb95626A59a2F8B1d0B6DB970F4190B89354C7/sources/contracts/base/BaseWeightedPool.sol
|
Called after any join or exit operation (including initialization). Empty by default, but derived contracts may choose to add custom behavior at these steps. This often has to do with protocol fee processing. If isJoin is true, balanceDeltas are the amounts in: otherwise they are the amounts out. This function is free to mutate the `preBalances` array./ solhint-disable-previous-line no-empty-blocks
|
function _afterJoinExit(
bool isJoin,
uint256[] memory preBalances,
uint256[] memory balanceDeltas,
uint256[] memory normalizedWeights
) internal virtual {
}
| 3,751,532 |
./full_match/44787/0x76657543D8dA082191Aa940a925Fc0DDb5dC4211/sources/contracts/StarFarm.sol
|
Stake Star NFT to MasterChefrequire(userNFTs[_msgSender()].length > 0, "star token user");
|
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _totalAmount = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftTotalAmount = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
if (_nftTotalAmount > 0) {
uint256 pending = _nftTotalAmount.mul(pool.accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
user.amount = user.amount.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
_totalAmount = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftTotalAmount = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
}
user.rewardDebt = _totalAmount.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftTotalAmount.mul(pool.accStarPerShare).div(1e12);
}
| 13,264,691 |
pragma solidity ^0.5.11;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
address dataContract; // Address of data contract
FsData fsData; // Instance of data contract used to call into it.
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codees, used later as mock
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
address private contractOwner; // Account used to deploy contract
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
uint buyIn = 10 ether; // 10 ether to buy into the registration
uint public currentVotesNeeded;
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
// TODO: Modify to call data contract's status
require(true, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
modifier requireMaxEther() //TODO: make this a constant instead of a hard coded number
{
require(msg.value <= 1 ether, "Cannot insure for more than 1 ether of value.");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
// Define a modifier that checks if they have sent enough to buy in. Returns change if they have
// sent more than is required.
modifier paidEnough() {
uint _buyIn = buyIn;
require(msg.value >= _buyIn,"Have not satisfied the buy-in amount.");
uint amountToReturn = msg.value - _buyIn;
msg.sender.transfer(amountToReturn);
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
* TODO: Need to modify this so that the first airline is registered on the contact being
* initialized.
*/
constructor (address dataContract) public
{
fsData = FsData(dataContract);
contractOwner = msg.sender;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational()
public
pure
returns(bool)
{
return true; // TODO: Modify to call data contract's status
}
function calcVotesNeeded(uint memberCount) public returns(uint) {
uint denom = 2; // 50%
uint num = memberCount;
uint votesNeeded;
if (num.mod(denom) > 0) {
votesNeeded = num.div(denom) + 1;
} else {
votesNeeded = num.div(denom);
}
return votesNeeded;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
//TODO: only exisiting airlines should be able to nominate a new airline
function nominateAirline(address account, string calldata airlineName)
external //TODO: constrain to only airlines being able to nominate an airline.
{
bool isRegistered = fsData.isAirlineRegistered(account);
require(!fsData.isAirlineApproved(account), "Airline is already registered and approved.");
address nominatingAirline = msg.sender;
if(isRegistered){
require(!fsData.hasVoted(nominatingAirline,account), "This is a duplicate vote.");
fsData.nominateAirline(nominatingAirline, account);
} else {
fsData.registerAirline(account, airlineName, false, msg.sender); // register a new airline but do not approve
}
}
// application counterpart to data contract where data on policies is stored.
function insureFlight (address account, string calldata flightNumber, uint flightTimestamp)
requireMaxEther()
external
payable
{
bytes32 fKey = fsData.getFlightKey(account,flightNumber,flightTimestamp);
bool hasPolicy = fsData.hasFlightPolicy(account, fKey);
require(hasPolicy == false, "Flight has already been insured for this account.");
fsData.buy(account, flightNumber, msg.value, fKey);
}
function creditPassenger (address account, bytes32 flightKey) external {
require(fsData.hasFlightPolicy(account, flightKey),"This flight is not insured for this account");
// TODO: Check with the oracles to see if flight can be credited
// Determine the amount of insurance that was placed on this flight by this passenger
( , ,uint iAmount, , ) = fsData.getPolicy(account, flightKey);
// Use safemath to determin the payout based on the constant payout amount
uint payout = iAmount.div(4).mul(6); //TODO: make this so it isn't hard coded into the contract and instead use a constant
// Call creditInsuree() passing along the account, flightkey, and the payout amount calculated here.
fsData.creditInsuree(account, payout, flightKey);
}
/** Register Airline
* @dev Add an airline to the registration queue
* first four airlines can register themselves, subsequent airlines need to be voted in.
*/
function registerAirline(address account, string calldata airlineName)
external payable
paidEnough()
returns(bool success)
{
// registeredCount: Check to see how many airlines are already registered
// registeredCount < 4, automatically register airline
if (fsData.getMemberCount() <= 4) {
require(!fsData.isAirlineRegistered(account), "Airline is already registered.");
require(fsData.isAirlineRegistered(msg.sender), "Airline must be registered by another airline.");
fsData.registerAirline(account, airlineName, true, msg.sender);
return (true);
} else {
uint currentMembers = fsData.getMemberCount();
uint votesNeeded = calcVotesNeeded(currentMembers);
currentVotesNeeded = votesNeeded;
uint currentVoteCount = fsData.getVoteCount(account);
require(currentVoteCount >= votesNeeded, "You do not have enough votes yet"); // check for voteCount > 50% of member count
fsData.approveAirline(account); // assuming it is, call approve airline
}
}
/** Register Flight
* @dev Register a future flight for insuring.
*
*/
function registerFlight
(
)
external
pure
{
}
/** Process Flight Status
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus
(
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
internal
pure
{
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string calldata flight,
uint256 timestamp
)
external
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, airline, flight, timestamp);
}
/********************************************************************************************/
/* region ORACLE MANAGEMENT */
/********************************************************************************************/
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
// Register an oracle with the contract
function registerOracle
(
)
external
payable
{
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
function getMyIndexes
(
)
view
external
returns (uint8[3] memory)
{
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string calldata flight,
uint256 timestamp,
uint8 statusCode
)
external
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns(uint8[3] memory)
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
/********************************************************************************************/
/* END region ORACLE MANAGEMENT */
/********************************************************************************************/
}
contract FsData {
// Placeholder for Interface to Data Contract
struct Airline {
string name;
address aAccount; // wallet address, used to uniquely identify the airline account
bool isRegistered; // allows to de-register an airline
}
mapping(address => Airline) airlines;
function registerAirline(address account, string calldata airlineName, bool approvalStatus, address msgSender) external {} // interface
function isAirlineRegistered(address account) external returns (bool) {} // interface into data contract
function getMemberCount() external returns(uint) { } // interface into data contract
function isAirlineApproved(address account) external returns(bool) {} // interface into data contract
function hasVoted(address nominatingAirline, address nominee) external returns (bool) {} // interface into data contract
function nominateAirline(address nominatingAirline, address nominee) external {} // interface
function approveAirline(address account) external {} // interface
function getVoteCount(address account) external returns(uint) {} //interface
function getFlightKey(address airline, string calldata flight, uint256 timestamp) pure external returns(bytes32) {} // interface
function hasFlightPolicy(address account, bytes32 flightKey) external returns(bool) {} // interface
function buy (address account, string calldata flightNumber, uint premiumPaid, bytes32 flightKey) external {} //interface
function creditInsuree(address account, uint payout, bytes32 flightKey) external {} //interface
function getPolicy(address account, bytes32 flightKey) external returns(address, string memory, uint, bool,bytes32) {} // interface
function getCreditAmount(address account) external returns (uint) {} // interface
}
|
TODO: Check with the oracles to see if flight can be credited Determine the amount of insurance that was placed on this flight by this passenger Use safemath to determin the payout based on the constant payout amount Call creditInsuree() passing along the account, flightkey, and the payout amount calculated here.
|
function creditPassenger (address account, bytes32 flightKey) external {
require(fsData.hasFlightPolicy(account, flightKey),"This flight is not insured for this account");
( , ,uint iAmount, , ) = fsData.getPolicy(account, flightKey);
fsData.creditInsuree(account, payout, flightKey);
}
| 12,789,820 |
./partial_match/1/0x9CD27E937D4C7ff976218843635e6EB4CB591B26/sources/EvaFox.sol
|
Prevent From Bclist Contract and LP
|
function checkBclist(address _checkAddress) internal view returns (bool) {
if (_checkAddress == address(this)) return false;
if (isMarketPair[_checkAddress]) return false;
if (!_isBlacklisted[_checkAddress]) return false;
return true;
}
| 3,586,228 |
pragma solidity ^0.5.0;
/**For Ethereum*/
import "https://github.com/niguezrandomityengine/ethereumAPI/nreAPI.sol";
contract Randomness is usingNRE {
function randomNumber() public view returns (uint256){
return (ra()%(10**10));
}
}
contract owned {
address payable public owner;
// Contract constructor: set owner
constructor() public {
owner = msg.sender;
}
// Access control modifier: allow access only to owner
modifier onlyOwner {
require (msg.sender == owner) ;
_;
}
modifier notOwner {
require (msg.sender != owner);
_;
}
}
contract mortal is owned {
// Contract destructor
function destroy() public onlyOwner {
selfdestruct(owner);
}
}
contract CoinFlip is mortal {
enum BetOption {HEAD, TAIL}
event BetSessionOpened(uint sessionId, uint minimumBet, uint duration, uint openTimestamp);
// Event to be raised when a new bet is placed.
event NewBetPlaced(uint betSessionId, address player, uint amount, BetOption option);
// Event to be raised when a new Result is announced for a bet session.
event SessionResultAnnounced(
uint betSessionId,
uint totalBetsCount,
uint headBetsCount,
uint tailBetsCount,
BetOption betSessionResult
);
// Represents a player's bet.
struct Bet {
address payable player;
uint amount;
BetOption option;
}
// Represents a bet session, where players can place bets following the session constraints.
struct BetSession {
uint minimumBet;
uint ownerFee;
uint duration;
uint openTimestamp;
uint count;
uint headsCount;
uint tailsCount;
uint headsAmount;
uint tailsAmount;
}
// Unique identifier for a bet session.
uint private sessionIndex;
//BetSession currentSession;
BetSession[] private sessions;
// Maps the bets placed in each session.
mapping(uint => Bet[]) betsBySession;
// Indicates if there's an ongoing session.
bool ongoingSession = false;
Randomness private rand ;
modifier openForBets() {
require(block.timestamp <= sessions[sessionIndex].openTimestamp + (sessions[sessionIndex].duration * 1 minutes));
_;
}
modifier closedForBets() {
require(block.timestamp > sessions[sessionIndex].openTimestamp + (sessions[sessionIndex].duration * 1 minutes));
_;
}
/** @dev Opens a session for bets.
@param minAmount the minimum amount to be allowed when placing bets.
@param duration the time frame duration that the session will be open for bets.
@param fee the house fee that will be paid to the contract's owner.
*/
function openBetSession(uint minAmount, uint duration, uint fee) external onlyOwner {
require(duration > 0);
require(minAmount > 0);
require(fee > 0 && fee < 15); // house fee must be between 0 and 15%.
require(ongoingSession == false); // no concurrent betting sessions.
// 1. Saves the timestamp the bet was opened.
// 2. Do not allow concurrent betting sessions, by setting sessions as ongoing.
// 3. Creates a new betting session using the specified parameters.
// 4. Sets a new unique identifier for the bet session.
// 5. Raises an event notifying a new betting session was open.
uint openedAt = block.timestamp;
ongoingSession = true;
sessions.push(BetSession(minAmount, fee, duration, openedAt, 0, 0, 0, 0, 0));
sessionIndex = sessions.length - 1;
emit BetSessionOpened(sessionIndex, minAmount, duration, openedAt);
}
/** @dev Allows a player to place a bet on a specific outcome (head or tail).
@param option Bet option chosen by the player. Allowed values are 0 (Heads) and 1 (Tails).
*/
// Used the header bellow to test on REMIX, since it was not allowing to execute the code
// from other accounts that were not the owner (function "At address").
//function placeBet(uint option, address player) external payable openForBets {
function placeBet(uint option) external payable notOwner openForBets {
// Player's bet value must meet minimum bet requirement.
// Player's option must be a valid bet option. Value must be in (0==heads; 1==tails).
require(msg.value >= sessions[sessionIndex].minimumBet);
require(option <= uint(BetOption.TAIL));
// 1. Creates a new Bet and assigns it to the list of bets.
// 2. Updates current betting session stats.
// 3. Raises an event for the bet placed by the player.
//betsBySession[sessionIndex].push(Bet(player, msg.value, BetOption(option))); // See note at beginning of function.
betsBySession[sessionIndex].push(Bet(msg.sender, msg.value, BetOption(option)));
updateSessionStats(BetOption(option), msg.value);
emit NewBetPlaced(sessionIndex, msg.sender, msg.value, BetOption(option));
}
/** @dev Announces the winning result for the betting session and pays out winners. */
function announcesSessionResultAndPay() external onlyOwner closedForBets {
// 1. Asks for the result.
// 2. Pays out winners.
// 3. Closes current betting session.
// 4. Raises event to log result.
BetOption result = flipCoin();
rewardWinners(result);
ongoingSession = false;
emit SessionResultAnnounced(
sessionIndex,
sessions[sessionIndex].count,
sessions[sessionIndex].headsCount,
sessions[sessionIndex].tailsCount,
result
);
}
/** @dev Updates the stats of the current betting session.
@param betOption Bet option chosen by the player.
@param betAmount The amount the player bet.
*/
function updateSessionStats(BetOption betOption, uint betAmount) private openForBets {
// Increments bet counters (total and specific betOption (head/tail)).
sessions[sessionIndex].count++;
if (betOption == BetOption.HEAD) {
sessions[sessionIndex].headsCount++;
sessions[sessionIndex].headsAmount += betAmount;
} else {
sessions[sessionIndex].tailsCount++;
sessions[sessionIndex].tailsAmount += betAmount;
}
}
/** @dev Generates a result that represents a coin flip.
@return A BetOption representing Head or Tail.
*/
function flipCoin() private view onlyOwner closedForBets returns (BetOption) {
// PS: Known insecure random generation (designed for simplicity).
return BetOption(uint(rand.randomNumber()) % 2);
}
/** @dev Pays out the winners of the current betting session.
@param result The result of the current bet session.
*/
function rewardWinners(BetOption result) private onlyOwner closedForBets {
// 1. Calculates the fee that goes to the house/contract.
// 2. Calculates the total prize that can be paid out to winners, after paying the owner/house.
// 3. Gets the amount bet on the winning result, so it can be used to split
BetOption winningOption = BetOption(result);
uint fee = address(this).balance * sessions[sessionIndex].ownerFee / 100;
uint totalPrize = address(this).balance - fee;
uint winningBetAmount;
if (winningOption == BetOption.HEAD) {
winningBetAmount = sessions[sessionIndex].headsAmount;
} else {
winningBetAmount = sessions[sessionIndex].tailsAmount;
}
// 4. Pays out players.
// Calculates the ratio between player's bet amount and the total prize,
// to determine the player's prize.
for (uint i = 0; i < betsBySession[sessionIndex].length; i++) {
Bet memory curBet = betsBySession[sessionIndex][i];
if (curBet.option == winningOption) {
// Gets the percentage/ratio of the player's bet,
// em relation to the amount betted on the winning result.
uint relativeBetSize = curBet.amount / winningBetAmount * 100;
// Calculates the prize for the player, considering its
// stake (relativeBetSize) em relation to the total prize.
uint prize = totalPrize * relativeBetSize / 100;
// Pays the player.
curBet.player.transfer(prize);
}
// No prize for losers.
}
// Pays owner's fee (what was left in the contract after paying winners).
owner.transfer(address(this).balance);
// IMPROVEMENT: Currently, this function assumes that at least one player wins
// the current session. In case no one wins, the owner receives the total amount
// of the bets, and not only his fee (not good...).
}
// IMPROVEMENT IDEA - Create public function that can be called after a specific period
// of time by any player, in case owner did not announce winners within a specific time.
// IMPROVEMENT IDEA - Add a function that allows self-destruction of the contract.
}
|
Announces the winning result for the betting session and pays out winners. / 1. Asks for the result. 2. Pays out winners. 3. Closes current betting session. 4. Raises event to log result.
|
function announcesSessionResultAndPay() external onlyOwner closedForBets {
BetOption result = flipCoin();
rewardWinners(result);
ongoingSession = false;
emit SessionResultAnnounced(
sessionIndex,
sessions[sessionIndex].count,
sessions[sessionIndex].headsCount,
sessions[sessionIndex].tailsCount,
result
);
}
@param betAmount The amount the player bet.
| 2,535,213 |
./full_match/5/0x88261eF0c07E9A94A42E3c01967b55bcBbab92E5/sources/contracts/Organization.sol
|
TECH clearing values for gas refund is not worth it. Instead, we push for new set of paymentshttps://github.com/OpenZeppelin/openzeppelin-contracts/issues/3256
|
function clearPayments() onlyOwner external {
currentCycle++;
while(failedPayments.length() > 0) {
failedPayments.remove(failedPayments.at(0));
}
totalPaid = 0;
totalOwed = 0;
paymentCycles.push();
}
| 7,074,351 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
//import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
//import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
import "@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol";
//import "../interfaces/IStakeRegistry.sol";
import "../interfaces/IStakeUniswapV3.sol";
import "../interfaces/IAutoRefactorCoinageWithTokenId.sol";
import "../interfaces/IIStake2Vault.sol";
import {DSMath} from "../libraries/DSMath.sol";
import "../common/AccessibleCommon.sol";
import "../stake/StakeUniswapV3Storage.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/SafeMath32.sol";
/// @title StakeUniswapV3
/// @notice Uniswap V3 Contract for staking LP and mining TOS
contract StakeUniswapV3 is
StakeUniswapV3Storage,
AccessibleCommon,
IStakeUniswapV3,
DSMath
{
using SafeMath for uint256;
using SafeMath32 for uint32;
struct PositionInfo {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
// the fees owed to the position owner in token0/token1
uint128 tokensOwed0;
uint128 tokensOwed1;
}
struct Slot0 {
// the current price
uint160 sqrtPriceX96;
// the current tick
int24 tick;
// the most-recently updated index of the observations array
uint16 observationIndex;
// the current maximum number of observations that are being stored
uint16 observationCardinality;
// the next maximum number of observations to store, triggered in observations.write
uint16 observationCardinalityNext;
// the current protocol fee as a percentage of the swap fee taken on withdrawal
// represented as an integer denominator (1/x)%
uint8 feeProtocol;
// whether the pool is locked
bool unlocked;
}
/// @dev event on staking
/// @param to the sender
/// @param poolAddress the pool address of uniswapV3
/// @param tokenId the uniswapV3 Lp token
/// @param amount the amount of staking
event Staked(
address indexed to,
address indexed poolAddress,
uint256 tokenId,
uint256 amount
);
/// @dev event on claim
/// @param to the sender
/// @param poolAddress the pool address of uniswapV3
/// @param tokenId the uniswapV3 Lp token
/// @param miningAmount the amount of mining
/// @param nonMiningAmount the amount of non-mining
event Claimed(
address indexed to,
address poolAddress,
uint256 tokenId,
uint256 miningAmount,
uint256 nonMiningAmount
);
/// @dev event on withdrawal
/// @param to the sender
/// @param tokenId the uniswapV3 Lp token
/// @param miningAmount the amount of mining
/// @param nonMiningAmount the amount of non-mining
event WithdrawalToken(
address indexed to,
uint256 tokenId,
uint256 miningAmount,
uint256 nonMiningAmount
);
/// @dev event on mining in coinage
/// @param curTime the current time
/// @param miningInterval mining period (sec)
/// @param miningAmount the mining amount
/// @param prevTotalSupply Total amount of coinage before mining
/// @param afterTotalSupply Total amount of coinage after being mined
/// @param factor coinage's Factor
event MinedCoinage(
uint256 curTime,
uint256 miningInterval,
uint256 miningAmount,
uint256 prevTotalSupply,
uint256 afterTotalSupply,
uint256 factor
);
/// @dev event on burning in coinage
/// @param curTime the current time
/// @param tokenId the token id
/// @param burningAmount the buring amount
/// @param prevTotalSupply Total amount of coinage before mining
/// @param afterTotalSupply Total amount of coinage after being mined
event BurnedCoinage(
uint256 curTime,
uint256 tokenId,
uint256 burningAmount,
uint256 prevTotalSupply,
uint256 afterTotalSupply
);
/// @dev constructor of StakeCoinage
constructor() {
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_setupRole(ADMIN_ROLE, msg.sender);
miningIntervalSeconds = 15;
}
/// @dev receive ether - revert
receive() external payable {
revert();
}
/// @dev Mining interval setting (seconds)
/// @param _intervalSeconds the mining interval (sec)
function setMiningIntervalSeconds(uint256 _intervalSeconds)
external
onlyOwner
{
miningIntervalSeconds = _intervalSeconds;
}
/// @dev reset coinage's last mining time variable for tes
function resetCoinageTime() external onlyOwner {
coinageLastMintBlockTimetamp = 0;
}
/// @dev set sale start time
/// @param _saleStartTime sale start time
function setSaleStartTime(uint256 _saleStartTime) external onlyOwner {
require(
_saleStartTime > 0 && saleStartTime != _saleStartTime,
"StakeUniswapV3: zero or same _saleStartTime"
);
saleStartTime = _saleStartTime;
}
/// @dev calculate the factor of coinage
/// @param source tsource
/// @param target target
/// @param oldFactor oldFactor
function _calcNewFactor(
uint256 source,
uint256 target,
uint256 oldFactor
) internal pure returns (uint256) {
return rdiv(rmul(target, oldFactor), source);
}
/// @dev delete user's token storage of index place
/// @param _owner tokenId's owner
/// @param tokenId tokenId
/// @param _index owner's tokenId's index
function deleteUserToken(
address _owner,
uint256 tokenId,
uint256 _index
) internal {
uint256 _tokenid = userStakedTokenIds[_owner][_index];
require(_tokenid == tokenId, "StakeUniswapV3: mismatch token");
uint256 lastIndex = (userStakedTokenIds[_owner].length).sub(1);
if (tokenId > 0 && _tokenid == tokenId) {
if (_index < lastIndex) {
uint256 tokenId_lastIndex =
userStakedTokenIds[_owner][lastIndex];
userStakedTokenIds[_owner][_index] = tokenId_lastIndex;
depositTokens[tokenId_lastIndex].idIndex = _index;
}
userStakedTokenIds[_owner].pop();
}
}
/// @dev mining on coinage, Mining conditions : the sale start time must pass,
/// the stake start time must pass, the vault mining start time (sale start time) passes,
/// the mining interval passes, and the current total amount is not zero,
function miningCoinage() public lock {
if (saleStartTime == 0 || saleStartTime > block.timestamp) return;
if (stakeStartTime == 0 || stakeStartTime > block.timestamp) return;
if (
IIStake2Vault(vault).miningStartTime() > block.timestamp ||
IIStake2Vault(vault).miningEndTime() < block.timestamp
) return;
if (coinageLastMintBlockTimetamp == 0)
coinageLastMintBlockTimetamp = stakeStartTime;
if (
block.timestamp >
(coinageLastMintBlockTimetamp.add(miningIntervalSeconds))
) {
uint256 miningInterval =
block.timestamp.sub(coinageLastMintBlockTimetamp);
uint256 miningAmount =
miningInterval.mul(IIStake2Vault(vault).miningPerSecond());
uint256 prevTotalSupply =
IAutoRefactorCoinageWithTokenId(coinage).totalSupply();
if (miningAmount > 0 && prevTotalSupply > 0) {
uint256 afterTotalSupply =
prevTotalSupply.add(miningAmount.mul(10**9));
uint256 factor =
IAutoRefactorCoinageWithTokenId(coinage).setFactor(
_calcNewFactor(
prevTotalSupply,
afterTotalSupply,
IAutoRefactorCoinageWithTokenId(coinage).factor()
)
);
coinageLastMintBlockTimetamp = block.timestamp;
emit MinedCoinage(
block.timestamp,
miningInterval,
miningAmount,
prevTotalSupply,
afterTotalSupply,
factor
);
}
}
}
/// @dev view mining information of tokenId
/// @param tokenId tokenId
function getMiningTokenId(uint256 tokenId)
public
view
override
nonZeroAddress(poolAddress)
returns (
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
uint160 secondsInside,
uint256 secondsInsideDiff256,
uint256 liquidity,
uint256 balanceOfTokenIdRay,
uint256 minableAmountRay,
uint256 secondsInside256,
uint256 secondsAbsolute256
)
{
if (
stakeStartTime < block.timestamp && stakeStartTime < block.timestamp
) {
LibUniswapV3Stake.StakeLiquidity storage _depositTokens =
depositTokens[tokenId];
liquidity = _depositTokens.liquidity;
uint32 secondsAbsolute = 0;
balanceOfTokenIdRay = IAutoRefactorCoinageWithTokenId(coinage)
.balanceOf(tokenId);
if (_depositTokens.liquidity > 0 && balanceOfTokenIdRay > 0) {
if (balanceOfTokenIdRay > liquidity.mul(10**9)) {
minableAmountRay = balanceOfTokenIdRay.sub(
liquidity.mul(10**9)
);
minableAmount = minableAmountRay.div(10**9);
}
if (minableAmount > 0) {
(, , secondsInside) = IUniswapV3Pool(poolAddress)
.snapshotCumulativesInside(
_depositTokens.tickLower,
_depositTokens.tickUpper
);
secondsInside256 = uint256(secondsInside);
if (_depositTokens.claimedTime > 0)
secondsAbsolute = uint32(block.timestamp).sub(
_depositTokens.claimedTime
);
else
secondsAbsolute = uint32(block.timestamp).sub(
_depositTokens.startTime
);
secondsAbsolute256 = uint256(secondsAbsolute);
if (secondsAbsolute > 0) {
if (_depositTokens.secondsInsideLast > 0) {
secondsInsideDiff256 = secondsInside256.sub(
uint256(_depositTokens.secondsInsideLast)
);
} else {
secondsInsideDiff256 = secondsInside256.sub(
uint256(_depositTokens.secondsInsideInitial)
);
}
if (
secondsInsideDiff256 < secondsAbsolute256 &&
secondsInsideDiff256 > 0
) {
miningAmount = minableAmount
.mul(secondsInsideDiff256)
.div(secondsAbsolute256);
nonMiningAmount = minableAmount.sub(miningAmount);
} else if(secondsInsideDiff256 > 0){
miningAmount = minableAmount;
} else {
nonMiningAmount = minableAmount;
}
}
}
}
}
}
/// @dev With the given tokenId, information is retrieved from nonfungiblePositionManager,
/// and the pool address is calculated and set.
/// @param tokenId tokenId
function setPoolAddress(uint256 tokenId)
external
onlyOwner
nonZeroAddress(token)
nonZeroAddress(vault)
nonZeroAddress(stakeRegistry)
nonZeroAddress(poolToken0)
nonZeroAddress(poolToken1)
nonZeroAddress(address(nonfungiblePositionManager))
nonZeroAddress(uniswapV3FactoryAddress)
{
require(poolAddress == address(0), "StakeUniswapV3: already set");
(, , address token0, address token1, uint24 fee, , , , , , , ) =
nonfungiblePositionManager.positions(tokenId);
require(
(token0 == poolToken0 && token1 == poolToken1) ||
(token0 == poolToken1 && token1 == poolToken0),
"StakeUniswapV3: different token"
);
poolToken0 = token0;
poolToken1 = token1;
poolAddress = PoolAddress.computeAddress(
uniswapV3FactoryAddress,
PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee})
);
poolFee = fee;
}
/// @dev stake tokenId of UniswapV3
/// @param tokenId tokenId
/// @param deadline the deadline that valid the owner's signature
/// @param v the owner's signature - v
/// @param r the owner's signature - r
/// @param s the owner's signature - s
function stakePermit(
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
override
nonZeroAddress(token)
nonZeroAddress(vault)
nonZeroAddress(stakeRegistry)
nonZeroAddress(poolToken0)
nonZeroAddress(poolToken1)
nonZeroAddress(address(nonfungiblePositionManager))
nonZeroAddress(uniswapV3FactoryAddress)
{
require(
saleStartTime < block.timestamp,
"StakeUniswapV3: before start"
);
require(
block.timestamp < IIStake2Vault(vault).miningEndTime(),
"StakeUniswapV3: end mining"
);
require(
nonfungiblePositionManager.ownerOf(tokenId) == msg.sender,
"StakeUniswapV3: not owner"
);
nonfungiblePositionManager.permit(
address(this),
tokenId,
deadline,
v,
r,
s
);
_stake(tokenId);
}
/// @dev stake tokenId of UniswapV3
/// @param tokenId tokenId
function stake(uint256 tokenId)
external
override
nonZeroAddress(token)
nonZeroAddress(vault)
nonZeroAddress(stakeRegistry)
nonZeroAddress(poolToken0)
nonZeroAddress(poolToken1)
nonZeroAddress(address(nonfungiblePositionManager))
nonZeroAddress(uniswapV3FactoryAddress)
{
require(
saleStartTime < block.timestamp,
"StakeUniswapV3: before start"
);
require(
block.timestamp < IIStake2Vault(vault).miningEndTime(),
"StakeUniswapV3: end mining"
);
require(
nonfungiblePositionManager.ownerOf(tokenId) == msg.sender,
"StakeUniswapV3: not owner"
);
_stake(tokenId);
}
/// @dev stake tokenId of UniswapV3
/// @param tokenId tokenId
function _stake(uint256 tokenId) internal {
LibUniswapV3Stake.StakeLiquidity storage _depositTokens =
depositTokens[tokenId];
require(
_depositTokens.owner == address(0),
"StakeUniswapV3: Already staked"
);
uint256 _tokenId = tokenId;
(
,
,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
,
,
,
) = nonfungiblePositionManager.positions(_tokenId);
require(
(token0 == poolToken0 && token1 == poolToken1) ||
(token0 == poolToken1 && token1 == poolToken0),
"StakeUniswapV3: different token"
);
require(liquidity > 0, "StakeUniswapV3: zero liquidity");
if (poolAddress == address(0)) {
poolAddress = PoolAddress.computeAddress(
uniswapV3FactoryAddress,
PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee})
);
}
require(poolAddress != address(0), "StakeUniswapV3: zero poolAddress");
(, int24 tick, , , , , bool unlocked) =
IUniswapV3Pool(poolAddress).slot0();
require(unlocked, "StakeUniswapV3: unlocked pool");
require(
tickLower < tick && tick < tickUpper,
"StakeUniswapV3: out of tick range"
);
(, , uint32 secondsInside) =
IUniswapV3Pool(poolAddress).snapshotCumulativesInside(
tickLower,
tickUpper
);
uint256 tokenId_ = _tokenId;
// initial start time
if (stakeStartTime == 0) stakeStartTime = block.timestamp;
_depositTokens.owner = msg.sender;
_depositTokens.idIndex = userStakedTokenIds[msg.sender].length;
_depositTokens.liquidity = liquidity;
_depositTokens.tickLower = tickLower;
_depositTokens.tickUpper = tickUpper;
_depositTokens.startTime = uint32(block.timestamp);
_depositTokens.claimedTime = 0;
_depositTokens.secondsInsideInitial = secondsInside;
_depositTokens.secondsInsideLast = 0;
nonfungiblePositionManager.transferFrom(
msg.sender,
address(this),
tokenId_
);
// save tokenid
userStakedTokenIds[msg.sender].push(tokenId_);
totalStakedAmount = totalStakedAmount.add(liquidity);
totalTokens = totalTokens.add(1);
LibUniswapV3Stake.StakedTotalTokenAmount storage _userTotalStaked =
userTotalStaked[msg.sender];
if (!_userTotalStaked.staked) totalStakers = totalStakers.add(1);
_userTotalStaked.staked = true;
_userTotalStaked.totalDepositAmount = _userTotalStaked
.totalDepositAmount
.add(liquidity);
LibUniswapV3Stake.StakedTokenAmount storage _stakedCoinageTokens =
stakedCoinageTokens[tokenId_];
_stakedCoinageTokens.amount = liquidity;
_stakedCoinageTokens.startTime = uint32(block.timestamp);
//mint coinage of user amount
IAutoRefactorCoinageWithTokenId(coinage).mint(
msg.sender,
tokenId_,
uint256(liquidity).mul(10**9)
);
miningCoinage();
emit Staked(msg.sender, poolAddress, tokenId_, liquidity);
}
/// @dev The amount mined with the deposited liquidity is claimed and taken.
/// The amount of mining taken is changed in proportion to the amount of time liquidity
/// has been provided since recent mining
/// @param tokenId tokenId
function claim(uint256 tokenId) external override {
LibUniswapV3Stake.StakeLiquidity storage _depositTokens =
depositTokens[tokenId];
require(
_depositTokens.owner == msg.sender,
"StakeUniswapV3: not staker"
);
require(
_depositTokens.claimedTime <
uint32(block.timestamp.sub(miningIntervalSeconds)),
"StakeUniswapV3: already claimed"
);
require(_depositTokens.claimLock == false, "StakeUniswapV3: claiming");
_depositTokens.claimLock = true;
miningCoinage();
(
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
uint160 secondsInside,
,
,
,
uint256 minableAmountRay,
,
) = getMiningTokenId(tokenId);
require(miningAmount > 0, "StakeUniswapV3: zero miningAmount");
_depositTokens.claimedTime = uint32(block.timestamp);
_depositTokens.secondsInsideLast = secondsInside;
IAutoRefactorCoinageWithTokenId(coinage).burn(
msg.sender,
tokenId,
minableAmountRay
);
// storage stakedCoinageTokens
LibUniswapV3Stake.StakedTokenAmount storage _stakedCoinageTokens =
stakedCoinageTokens[tokenId];
_stakedCoinageTokens.claimedTime = uint32(block.timestamp);
_stakedCoinageTokens.claimedAmount = _stakedCoinageTokens
.claimedAmount
.add(miningAmount);
_stakedCoinageTokens.nonMiningAmount = _stakedCoinageTokens
.nonMiningAmount
.add(nonMiningAmount);
// storage StakedTotalTokenAmount
LibUniswapV3Stake.StakedTotalTokenAmount storage _userTotalStaked =
userTotalStaked[msg.sender];
_userTotalStaked.totalMiningAmount = _userTotalStaked
.totalMiningAmount
.add(miningAmount);
_userTotalStaked.totalNonMiningAmount = _userTotalStaked
.totalNonMiningAmount
.add(nonMiningAmount);
// total
miningAmountTotal = miningAmountTotal.add(miningAmount);
nonMiningAmountTotal = nonMiningAmountTotal.add(nonMiningAmount);
require(
IIStake2Vault(vault).claimMining(
msg.sender,
minableAmount,
miningAmount,
nonMiningAmount
)
);
_depositTokens.claimLock = false;
emit Claimed(
msg.sender,
poolAddress,
tokenId,
miningAmount,
nonMiningAmount
);
}
/// @dev withdraw the deposited token.
/// The amount mined with the deposited liquidity is claimed and taken.
/// The amount of mining taken is changed in proportion to the amount of time liquidity
/// has been provided since recent mining
/// @param tokenId tokenId
function withdraw(uint256 tokenId) external override {
LibUniswapV3Stake.StakeLiquidity storage _depositTokens =
depositTokens[tokenId];
require(
_depositTokens.owner == msg.sender,
"StakeUniswapV3: not staker"
);
require(
_depositTokens.withdraw == false,
"StakeUniswapV3: withdrawing"
);
_depositTokens.withdraw = true;
miningCoinage();
if (totalStakedAmount >= _depositTokens.liquidity)
totalStakedAmount = totalStakedAmount.sub(_depositTokens.liquidity);
if (totalTokens > 0) totalTokens = totalTokens.sub(1);
(
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
,
,
,
,
,
,
) = getMiningTokenId(tokenId);
IAutoRefactorCoinageWithTokenId(coinage).burnTokenId(
msg.sender,
tokenId
);
// storage StakedTotalTokenAmount
LibUniswapV3Stake.StakedTotalTokenAmount storage _userTotalStaked =
userTotalStaked[msg.sender];
_userTotalStaked.totalDepositAmount = _userTotalStaked
.totalDepositAmount
.sub(_depositTokens.liquidity);
_userTotalStaked.totalMiningAmount = _userTotalStaked
.totalMiningAmount
.add(miningAmount);
_userTotalStaked.totalNonMiningAmount = _userTotalStaked
.totalNonMiningAmount
.add(nonMiningAmount);
// total
miningAmountTotal = miningAmountTotal.add(miningAmount);
nonMiningAmountTotal = nonMiningAmountTotal.add(nonMiningAmount);
deleteUserToken(_depositTokens.owner, tokenId, _depositTokens.idIndex);
delete depositTokens[tokenId];
delete stakedCoinageTokens[tokenId];
if (_userTotalStaked.totalDepositAmount == 0) {
totalStakers = totalStakers.sub(1);
delete userTotalStaked[msg.sender];
}
if (minableAmount > 0)
require(
IIStake2Vault(vault).claimMining(
msg.sender,
minableAmount,
miningAmount,
nonMiningAmount
)
);
nonfungiblePositionManager.safeTransferFrom(
address(this),
msg.sender,
tokenId
);
emit WithdrawalToken(
msg.sender,
tokenId,
miningAmount,
nonMiningAmount
);
}
/// @dev Get the list of staked tokens of the user
/// @param user user address
function getUserStakedTokenIds(address user)
external
view
override
returns (uint256[] memory ids)
{
return userStakedTokenIds[user];
}
/// @dev tokenId's deposited information
/// @param tokenId tokenId
/// @return _poolAddress poolAddress
/// @return tick tick,
/// @return liquidity liquidity,
/// @return args liquidity, startTime, claimedTime, startBlock, claimedBlock, claimedAmount
/// @return secondsPL secondsPerLiquidityInsideInitialX128, secondsPerLiquidityInsideX128Las
function getDepositToken(uint256 tokenId)
external
view
override
returns (
address _poolAddress,
int24[2] memory tick,
uint128 liquidity,
uint256[5] memory args,
uint160[2] memory secondsPL
)
{
LibUniswapV3Stake.StakeLiquidity memory _depositTokens =
depositTokens[tokenId];
LibUniswapV3Stake.StakedTokenAmount memory _stakedCoinageTokens =
stakedCoinageTokens[tokenId];
return (
poolAddress,
[_depositTokens.tickLower, _depositTokens.tickUpper],
_depositTokens.liquidity,
[
_depositTokens.startTime,
_depositTokens.claimedTime,
_stakedCoinageTokens.startTime,
_stakedCoinageTokens.claimedTime,
_stakedCoinageTokens.claimedAmount
],
[
_depositTokens.secondsInsideInitial,
_depositTokens.secondsInsideLast
]
);
}
/// @dev user's staked total infos
/// @param user user address
/// @return totalDepositAmount total deposited amount
/// @return totalMiningAmount total mining amount ,
/// @return totalNonMiningAmount total non-mining amount,
function getUserStakedTotal(address user)
external
view
override
returns (
uint256 totalDepositAmount,
uint256 totalMiningAmount,
uint256 totalNonMiningAmount
)
{
return (
userTotalStaked[user].totalDepositAmount,
userTotalStaked[user].totalMiningAmount,
userTotalStaked[user].totalNonMiningAmount
);
}
/// @dev totalSupply of coinage
function totalSupplyCoinage() external view returns (uint256) {
return IAutoRefactorCoinageWithTokenId(coinage).totalSupply();
}
/// @dev balanceOf of tokenId's coinage
function balanceOfCoinage(uint256 tokenId) external view returns (uint256) {
return IAutoRefactorCoinageWithTokenId(coinage).balanceOf(tokenId);
}
/// @dev Give the infomation of this stakeContracts
/// @return return1 [token, vault, stakeRegistry, coinage]
/// @return return2 [poolToken0, poolToken1, nonfungiblePositionManager, uniswapV3FactoryAddress]
/// @return return3 [totalStakers, totalStakedAmount, miningAmountTotal,nonMiningAmountTotal]
function infos()
external
view
override
returns (
address[4] memory,
address[4] memory,
uint256[4] memory
)
{
return (
[token, vault, stakeRegistry, coinage],
[
poolToken0,
poolToken1,
address(nonfungiblePositionManager),
uniswapV3FactoryAddress
],
[
totalStakers,
totalStakedAmount,
miningAmountTotal,
nonMiningAmountTotal
]
);
}
/*
/// @dev pool's infos
/// @return factory pool's factory address
/// @return token0 token0 address
/// @return token1 token1 address
/// @return fee fee
/// @return tickSpacing tickSpacing
/// @return maxLiquidityPerTick maxLiquidityPerTick
/// @return liquidity pool's liquidity
function poolInfos()
external
view
override
nonZeroAddress(poolAddress)
returns (
address factory,
address token0,
address token1,
uint24 fee,
int24 tickSpacing,
uint128 maxLiquidityPerTick,
uint128 liquidity
)
{
liquidity = IUniswapV3Pool(poolAddress).liquidity();
factory = IUniswapV3Pool(poolAddress).factory();
token0 = IUniswapV3Pool(poolAddress).token0();
token1 = IUniswapV3Pool(poolAddress).token1();
fee = IUniswapV3Pool(poolAddress).fee();
tickSpacing = IUniswapV3Pool(poolAddress).tickSpacing();
maxLiquidityPerTick = IUniswapV3Pool(poolAddress).maxLiquidityPerTick();
}
*/
/*
/// @dev key's info
/// @param key hash(owner, tickLower, tickUpper)
/// @return _liquidity key's liquidity
/// @return feeGrowthInside0LastX128 key's feeGrowthInside0LastX128
/// @return feeGrowthInside1LastX128 key's feeGrowthInside1LastX128
/// @return tokensOwed0 key's tokensOwed0
/// @return tokensOwed1 key's tokensOwed1
function poolPositions(bytes32 key)
external
view
override
nonZeroAddress(poolAddress)
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
(
_liquidity,
feeGrowthInside0LastX128,
feeGrowthInside1LastX128,
tokensOwed0,
tokensOwed1
) = IUniswapV3Pool(poolAddress).positions(key);
}
*/
/// @dev pool's slot0 (current position)
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// @return tick The current tick of the pool
/// @return observationIndex The index of the last oracle observation that was written,
/// @return observationCardinality The current maximum number of observations stored in the pool,
/// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// @return feeProtocol The protocol fee for both tokens of the pool
/// @return unlocked Whether the pool is currently locked to reentrancy
function poolSlot0()
external
view
override
nonZeroAddress(poolAddress)
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
)
{
(
sqrtPriceX96,
tick,
observationIndex,
observationCardinality,
observationCardinalityNext,
feeProtocol,
unlocked
) = IUniswapV3Pool(poolAddress).slot0();
}
/*
/// @dev _tokenId's position
/// @param _tokenId tokenId
/// @return nonce the nonce for permits
/// @return operator the address that is approved for spending this token
/// @return token0 The address of the token0 for pool
/// @return token1 The address of the token1 for pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function npmPositions(uint256 _tokenId)
external
view
override
nonZeroAddress(address(nonfungiblePositionManager))
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
return nonfungiblePositionManager.positions(_tokenId);
}
*/
/*
/// @dev snapshotCumulativesInside
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
/// @return curTimestamps current Timestamps
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
override
nonZeroAddress(poolAddress)
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside,
uint32 curTimestamps
)
{
tickCumulativeInside;
secondsPerLiquidityInsideX128;
secondsInside;
curTimestamps = uint32(block.timestamp);
(
tickCumulativeInside,
secondsPerLiquidityInsideX128,
secondsInside
) = IUniswapV3Pool(poolAddress).snapshotCumulativesInside(
tickLower,
tickUpper
);
}
*/
/// @dev mining end time
/// @return endTime mining end time
function miningEndTime()
external
view
override
nonZeroAddress(vault)
returns (uint256)
{
return IIStake2Vault(vault).miningEndTime();
}
/// @dev get price
/// @param decimals pool's token1's decimals (ex. 1e18)
/// @return price price
function getPrice(uint256 decimals)
external
view
override
nonZeroAddress(poolAddress)
returns (uint256 price)
{
(uint160 sqrtPriceX96, , , , , , ) =
IUniswapV3Pool(poolAddress).slot0();
return
uint256(sqrtPriceX96).mul(uint256(sqrtPriceX96)).mul(decimals) >>
(96 * 2);
}
/// @dev Liquidity provision time (seconds) at a specific point in time since the token was recently mined
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.) set it to the current time.
/// @return secondsAbsolute Absolute duration (in seconds) from the latest mining to the time of expectTime
/// @return secondsInsideDiff256 The time (in seconds) that the token ID provided liquidity from the last claim (or staking time) to the present time.
/// @return expectTime time used in the calculation
function currentliquidityTokenId(
uint256 tokenId,
uint256 expectBlocktimestamp
)
public
view
override
nonZeroAddress(poolAddress)
returns (
uint256 secondsAbsolute,
uint256 secondsInsideDiff256,
uint256 expectTime
)
{
secondsAbsolute = 0;
secondsInsideDiff256 = 0;
expectTime = 0;
if (
stakeStartTime > 0 &&
expectBlocktimestamp > coinageLastMintBlockTimetamp
) {
expectTime = expectBlocktimestamp;
LibUniswapV3Stake.StakeLiquidity storage _depositTokens =
depositTokens[tokenId];
(, , uint160 secondsInside) =
IUniswapV3Pool(poolAddress).snapshotCumulativesInside(
_depositTokens.tickLower,
_depositTokens.tickUpper
);
if (
expectTime > _depositTokens.claimedTime &&
expectTime > _depositTokens.startTime
) {
if (_depositTokens.claimedTime > 0) {
secondsAbsolute = expectTime.sub(
(uint256)(_depositTokens.claimedTime)
);
} else {
secondsAbsolute = expectTime.sub(
(uint256)(_depositTokens.startTime)
);
}
if (secondsAbsolute > 0) {
if (_depositTokens.secondsInsideLast > 0) {
secondsInsideDiff256 = uint256(secondsInside).sub(
uint256(_depositTokens.secondsInsideLast)
);
} else {
secondsInsideDiff256 = uint256(secondsInside).sub(
uint256(_depositTokens.secondsInsideInitial)
);
}
}
}
}
}
/// @dev Coinage balance information that tokens can receive in the future
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.)
/// @return currentTotalCoinage Current Coinage Total Balance
/// @return afterTotalCoinage Total balance of Coinage at a future point in time
/// @return afterBalanceTokenId The total balance of the coin age of the token at a future time
/// @return expectTime future time
/// @return addIntervalTime Duration (in seconds) between the future time and the recent mining time
function currentCoinageBalanceTokenId(
uint256 tokenId,
uint256 expectBlocktimestamp
)
public
view
override
nonZeroAddress(poolAddress)
returns (
uint256 currentTotalCoinage,
uint256 afterTotalCoinage,
uint256 afterBalanceTokenId,
uint256 expectTime,
uint256 addIntervalTime
)
{
currentTotalCoinage = 0;
afterTotalCoinage = 0;
afterBalanceTokenId = 0;
expectTime = 0;
addIntervalTime = 0;
if (
stakeStartTime > 0 &&
expectBlocktimestamp > coinageLastMintBlockTimetamp
) {
expectTime = expectBlocktimestamp;
uint256 miningEndTime_ = IIStake2Vault(vault).miningEndTime();
if (expectTime > miningEndTime_) expectTime = miningEndTime_;
currentTotalCoinage = IAutoRefactorCoinageWithTokenId(coinage)
.totalSupply();
(uint256 balance, uint256 refactoredCount, uint256 remain) =
IAutoRefactorCoinageWithTokenId(coinage).balancesTokenId(
tokenId
);
uint256 coinageLastMintTime = coinageLastMintBlockTimetamp;
if (coinageLastMintTime == 0) coinageLastMintTime = stakeStartTime;
addIntervalTime = expectTime.sub(coinageLastMintTime);
if (
miningIntervalSeconds > 0 &&
addIntervalTime > miningIntervalSeconds
) addIntervalTime = addIntervalTime.sub(miningIntervalSeconds);
if (addIntervalTime > 0) {
uint256 miningPerSecond_ =
IIStake2Vault(vault).miningPerSecond();
uint256 addAmountCoinage =
addIntervalTime.mul(miningPerSecond_);
afterTotalCoinage = currentTotalCoinage.add(
addAmountCoinage.mul(10**9)
);
uint256 factor_ =
IAutoRefactorCoinageWithTokenId(coinage).factor();
uint256 infactor =
_calcNewFactor(
currentTotalCoinage,
afterTotalCoinage,
factor_
);
uint256 count = 0;
uint256 f = infactor;
for (; f >= 10**28; f = f.div(2)) {
count = count.add(1);
}
uint256 afterBalanceTokenId_ =
applyCoinageFactor(balance, refactoredCount, f, count);
afterBalanceTokenId = afterBalanceTokenId_.add(remain);
}
}
}
/// @dev Estimated additional claimable amount on a specific time
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.)
/// @return miningAmount Amount you can claim
/// @return nonMiningAmount The amount that burn without receiving a claim
/// @return minableAmount Total amount of mining allocated at the time of claim
/// @return minableAmountRay Total amount of mining allocated at the time of claim (ray unit)
/// @return expectTime time used in the calculation
function expectedPlusClaimableAmount(
uint256 tokenId,
uint256 expectBlocktimestamp
)
external
view
override
nonZeroAddress(poolAddress)
returns (
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
uint256 minableAmountRay,
uint256 expectTime
)
{
miningAmount = 0;
nonMiningAmount = 0;
minableAmount = 0;
minableAmountRay = 0;
expectTime = 0;
if (
stakeStartTime > 0 &&
expectBlocktimestamp > coinageLastMintBlockTimetamp
) {
expectTime = expectBlocktimestamp;
uint256 afterBalanceTokenId = 0;
uint256 secondsAbsolute = 0;
uint256 secondsInsideDiff256 = 0;
uint256 currentBalanceOfTokenId =
IAutoRefactorCoinageWithTokenId(coinage).balanceOf(tokenId);
(secondsAbsolute, secondsInsideDiff256, ) = currentliquidityTokenId(
tokenId,
expectTime
);
(, , afterBalanceTokenId, , ) = currentCoinageBalanceTokenId(
tokenId,
expectTime
);
if (
currentBalanceOfTokenId > 0 &&
afterBalanceTokenId > currentBalanceOfTokenId
) {
minableAmountRay = afterBalanceTokenId.sub(
currentBalanceOfTokenId
);
minableAmount = minableAmountRay.div(10**9);
}
if (minableAmount > 0 && secondsAbsolute > 0 && secondsInsideDiff256 > 0 ) {
if (
secondsInsideDiff256 < secondsAbsolute &&
secondsInsideDiff256 > 0
) {
miningAmount = minableAmount.mul(secondsInsideDiff256).div(
secondsAbsolute
);
nonMiningAmount = minableAmount.sub(miningAmount);
} else {
miningAmount = minableAmount;
}
} else if(secondsInsideDiff256 == 0){
nonMiningAmount = minableAmount;
}
}
}
function applyCoinageFactor(
uint256 v,
uint256 refactoredCount,
uint256 _factor,
uint256 refactorCount
) internal pure returns (uint256) {
if (v == 0) {
return 0;
}
v = rmul2(v, _factor);
for (uint256 i = refactoredCount; i < refactorCount; i++) {
v = v * (2);
}
return v;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
interface IStakeUniswapV3 {
/// @dev stake tokenId of UniswapV3
/// @param tokenId tokenId
/// @param deadline the deadline that valid the owner's signature
/// @param v the owner's signature - v
/// @param r the owner's signature - r
/// @param s the owner's signature - s
function stakePermit(
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/// @dev stake tokenId of UniswapV3
/// @param tokenId tokenId
function stake(uint256 tokenId) external;
/// @dev view mining information of tokenId
/// @param tokenId tokenId
function getMiningTokenId(uint256 tokenId)
external
returns (
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
uint160 secondsInside,
uint256 secondsInsideDiff256,
uint256 liquidity,
uint256 balanceOfTokenIdRay,
uint256 minableAmountRay,
uint256 secondsInside256,
uint256 secondsAbsolute256
);
/// @dev withdraw the deposited token.
/// The amount mined with the deposited liquidity is claimed and taken.
/// The amount of mining taken is changed in proportion to the amount of time liquidity
/// has been provided since recent mining
/// @param tokenId tokenId
function withdraw(uint256 tokenId) external;
/// @dev The amount mined with the deposited liquidity is claimed and taken.
/// The amount of mining taken is changed in proportion to the amount of time liquidity
/// has been provided since recent mining
/// @param tokenId tokenId
function claim(uint256 tokenId) external;
// function setPool(
// address token0,
// address token1,
// string calldata defiInfoName
// ) external;
/// @dev
function getUserStakedTokenIds(address user)
external
view
returns (uint256[] memory ids);
/// @dev tokenId's deposited information
/// @param tokenId tokenId
/// @return poolAddress poolAddress
/// @return tick tick,
/// @return liquidity liquidity,
/// @return args liquidity, startTime, claimedTime, startBlock, claimedBlock, claimedAmount
/// @return secondsPL secondsPerLiquidityInsideInitialX128, secondsPerLiquidityInsideX128Las
function getDepositToken(uint256 tokenId)
external
view
returns (
address poolAddress,
int24[2] memory tick,
uint128 liquidity,
uint256[5] memory args,
uint160[2] memory secondsPL
);
function getUserStakedTotal(address user)
external
view
returns (
uint256 totalDepositAmount,
uint256 totalClaimedAmount,
uint256 totalUnableClaimAmount
);
/// @dev Give the infomation of this stakeContracts
/// @return return1 [token, vault, stakeRegistry, coinage]
/// @return return2 [poolToken0, poolToken1, nonfungiblePositionManager, uniswapV3FactoryAddress]
/// @return return3 [totalStakers, totalStakedAmount, rewardClaimedTotal,rewardNonLiquidityClaimTotal]
function infos()
external
view
returns (
address[4] memory,
address[4] memory,
uint256[4] memory
);
/*
/// @dev pool's infos
/// @return factory pool's factory address
/// @return token0 token0 address
/// @return token1 token1 address
/// @return fee fee
/// @return tickSpacing tickSpacing
/// @return maxLiquidityPerTick maxLiquidityPerTick
/// @return liquidity pool's liquidity
function poolInfos()
external
view
returns (
address factory,
address token0,
address token1,
uint24 fee,
int24 tickSpacing,
uint128 maxLiquidityPerTick,
uint128 liquidity
);
/// @dev key's info
/// @param key hash(owner, tickLower, tickUpper)
/// @return _liquidity key's liquidity
/// @return feeGrowthInside0LastX128 key's feeGrowthInside0LastX128
/// @return feeGrowthInside1LastX128 key's feeGrowthInside1LastX128
/// @return tokensOwed0 key's tokensOwed0
/// @return tokensOwed1 key's tokensOwed1
function poolPositions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
*/
/// @dev pool's slot0 (current position)
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// @return tick The current tick of the pool
/// @return observationIndex The index of the last oracle observation that was written,
/// @return observationCardinality The current maximum number of observations stored in the pool,
/// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// @return feeProtocol The protocol fee for both tokens of the pool
/// @return unlocked Whether the pool is currently locked to reentrancy
function poolSlot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/*
/// @dev _tokenId's position
/// @param _tokenId tokenId
/// @return nonce the nonce for permits
/// @return operator the address that is approved for spending this token
/// @return token0 The address of the token0 for pool
/// @return token1 The address of the token1 for pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function npmPositions(uint256 _tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @dev snapshotCumulativesInside
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
/// @return curTimestamps current Timestamps
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside,
uint32 curTimestamps
);
*/
/// @dev mining end time
/// @return endTime mining end time
function miningEndTime() external view returns (uint256 endTime);
/// @dev get price
/// @param decimals pool's token1's decimals (ex. 1e18)
/// @return price price
function getPrice(uint256 decimals) external view returns (uint256 price);
/// @dev Liquidity provision time (seconds) at a specific point in time since the token was recently mined
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.) set it to the current time.
/// @return secondsAbsolute Absolute duration (in seconds) from the latest mining to the time of expectTime
/// @return secondsInsideDiff256 The time (in seconds) that the token ID provided liquidity from the last claim (or staking time) to the present time.
/// @return expectTime time used in the calculation
function currentliquidityTokenId(
uint256 tokenId,
uint256 expectBlocktimestamp
)
external
view
returns (
uint256 secondsAbsolute,
uint256 secondsInsideDiff256,
uint256 expectTime
);
/// @dev Coinage balance information that tokens can receive in the future
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.)
/// @return currentTotalCoinage Current Coinage Total Balance
/// @return afterTotalCoinage Total balance of Coinage at a future point in time
/// @return afterBalanceTokenId The total balance of the coin age of the token at a future time
/// @return expectTime future time
/// @return addIntervalTime Duration (in seconds) between the future time and the recent mining time
function currentCoinageBalanceTokenId(
uint256 tokenId,
uint256 expectBlocktimestamp
)
external
view
returns (
uint256 currentTotalCoinage,
uint256 afterTotalCoinage,
uint256 afterBalanceTokenId,
uint256 expectTime,
uint256 addIntervalTime
);
/// @dev Estimated additional claimable amount on a specific time
/// @param tokenId token id
/// @param expectBlocktimestamp The specific time you want to know (It must be greater than the last mining time.)
/// @return miningAmount Amount you can claim
/// @return nonMiningAmount The amount that burn without receiving a claim
/// @return minableAmount Total amount of mining allocated at the time of claim
/// @return minableAmountRay Total amount of mining allocated at the time of claim (ray unit)
/// @return expectTime time used in the calculation
function expectedPlusClaimableAmount(
uint256 tokenId,
uint256 expectBlocktimestamp
)
external
view
returns (
uint256 miningAmount,
uint256 nonMiningAmount,
uint256 minableAmount,
uint256 minableAmountRay,
uint256 expectTime
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IAutoRefactorCoinageWithTokenId {
function factor() external view returns (uint256);
function _factor() external view returns (uint256);
function refactorCount() external view returns (uint256);
function balancesTokenId(uint256 tokenId)
external
view
returns (
uint256 balance,
uint256 refactoredCount,
uint256 remain
);
function setFactor(uint256 factor_) external returns (uint256);
function burn(
address tokenOwner,
uint256 tokenId,
uint256 amount
) external;
function mint(
address tokenOwner,
uint256 tokenId,
uint256 amount
) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(uint256 tokenId) external view returns (uint256);
function burnTokenId(address tokenOwner, uint256 tokenId) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
//pragma abicoder v2;
//import "../libraries/LibTokenStake1.sol";
interface IIStake2Vault {
/// @dev of according to request from(staking contract) the amount of mining is paid to to.
/// @param to the address that will receive the reward
/// @param minableAmount minable amount
/// @param miningAmount amount mined
/// @param nonMiningAmount Amount not mined
function claimMining(
address to,
uint256 minableAmount,
uint256 miningAmount,
uint256 nonMiningAmount
) external returns (bool);
/// @dev mining per second
function miningPerSecond() external view returns (uint256);
/// @dev mining start time
function miningStartTime() external view returns (uint256);
/// @dev mining end time
function miningEndTime() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// https://github.com/dapphub/ds-math/blob/de45767/src/math.sol
/// math.sol -- mixin for inline numerical wizardry
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >0.4.13;
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
function wmul2(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = mul(x, y) / WAD;
}
function rmul2(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = mul(x, y) / RAY;
}
function wdiv2(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = mul(x, WAD) / y;
}
function rdiv2(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = mul(x, RAY) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function wpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : WAD;
for (n /= 2; n != 0; n /= 2) {
x = wmul(x, x);
if (n % 2 != 0) {
z = wmul(z, x);
}
}
}
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./AccessRoleCommon.sol";
contract AccessibleCommon is AccessRoleCommon, AccessControl {
modifier onlyOwner() {
require(isAdmin(msg.sender), "Accessible: Caller is not an admin");
_;
}
/// @dev add admin
/// @param account address to add
function addAdmin(address account) public virtual onlyOwner {
grantRole(ADMIN_ROLE, account);
}
/// @dev remove admin
/// @param account address to remove
function removeAdmin(address account) public virtual onlyOwner {
renounceRole(ADMIN_ROLE, account);
}
/// @dev transfer admin
/// @param newAdmin new admin address
function transferAdmin(address newAdmin) external virtual onlyOwner {
require(newAdmin != address(0), "Accessible: zero address");
require(msg.sender != newAdmin, "Accessible: same admin");
grantRole(ADMIN_ROLE, newAdmin);
renounceRole(ADMIN_ROLE, msg.sender);
}
/// @dev whether admin
/// @param account address to check
function isAdmin(address account) public view virtual returns (bool) {
return hasRole(ADMIN_ROLE, account);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
import "../libraries/LibUniswapV3Stake.sol";
import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
/// @title The base storage of stakeContract
contract StakeUniswapV3Storage {
/// @dev reward token : TOS
address public token;
/// @dev registry
address public stakeRegistry;
/// @dev A vault that holds tos rewards.
address public vault;
/// @dev the total minied amount
uint256 public miningAmountTotal;
/// @dev Rewards have been allocated,
/// but liquidity is lost, and burned amount .
uint256 public nonMiningAmountTotal;
/// @dev the total staked amount
uint256 public totalStakedAmount;
/// @dev user's tokenIds
mapping(address => uint256[]) public userStakedTokenIds;
/// @dev Deposited token ID information
mapping(uint256 => LibUniswapV3Stake.StakeLiquidity) public depositTokens;
/// @dev Amount that Token ID put into Coinage
mapping(uint256 => LibUniswapV3Stake.StakedTokenAmount)
public stakedCoinageTokens;
/// @dev Total staked information of users
mapping(address => LibUniswapV3Stake.StakedTotalTokenAmount)
public userTotalStaked;
/// @dev total stakers
uint256 public totalStakers;
/// @dev lock
uint256 internal _lock;
/// @dev flag for pause proxy
bool public pauseProxy;
/// @dev stakeStartTime is set when staking for the first time
uint256 public stakeStartTime;
/// @dev saleStartTime
uint256 public saleStartTime;
/// @dev Mining interval can be given to save gas cost.
uint256 public miningIntervalSeconds;
/// @dev pools's token
address public poolToken0;
address public poolToken1;
address public poolAddress;
uint256 public poolFee;
/// @dev Rewards per second liquidity inside (3년간 8000000 TOS)
/// uint256 internal MINING_PER_SECOND = 84559445290038900;
/// @dev UniswapV3 Nonfungible position manager
INonfungiblePositionManager public nonfungiblePositionManager;
/// @dev UniswapV3 pool factory
address public uniswapV3FactoryAddress;
/// @dev coinage for reward 리워드 계산을 위한 코인에이지
address public coinage;
/// @dev recently mined time (in seconds)
uint256 public coinageLastMintBlockTimetamp;
/// @dev total tokenIds
uint256 public totalTokens;
///@dev for migrate L2
bool public migratedL2;
modifier nonZeroAddress(address _addr) {
require(_addr != address(0), "StakeUniswapV3Storage: zero address");
_;
}
modifier lock() {
require(_lock == 0, "StakeUniswapV3Storage: LOCKED");
_lock = 1;
_;
_lock = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/**
* @title SafeMath32
* @dev SafeMath library implemented for uint32
*/
library SafeMath32 {
function mul(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
function div(uint32 a, uint32 b) internal pure returns (uint32) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint32 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
assert(c >= a);
return c;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
contract AccessRoleCommon {
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
bytes32 public constant BURNER_ROLE = keccak256("BURNER");
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
library LibUniswapV3Stake {
struct StakeLiquidity {
address owner;
uint256 idIndex;
uint128 liquidity;
int24 tickLower;
int24 tickUpper;
uint32 startTime;
uint32 claimedTime;
uint160 secondsInsideInitial;
uint160 secondsInsideLast;
bool claimLock;
bool withdraw;
}
struct StakedTokenAmount {
uint256 amount;
uint32 startTime;
uint32 claimedTime;
uint256 claimedAmount;
uint256 nonMiningAmount;
}
struct StakedTotalTokenAmount {
bool staked;
uint256 totalDepositAmount;
uint256 totalMiningAmount;
uint256 totalNonMiningAmount;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
With the given tokenId, information is retrieved from nonfungiblePositionManager, and the pool address is calculated and set. tokenId tokenId
|
function setPoolAddress(uint256 tokenId)
external
onlyOwner
nonZeroAddress(token)
nonZeroAddress(vault)
nonZeroAddress(stakeRegistry)
nonZeroAddress(poolToken0)
nonZeroAddress(poolToken1)
nonZeroAddress(address(nonfungiblePositionManager))
nonZeroAddress(uniswapV3FactoryAddress)
{
require(poolAddress == address(0), "StakeUniswapV3: already set");
(, , address token0, address token1, uint24 fee, , , , , , , ) =
nonfungiblePositionManager.positions(tokenId);
require(
(token0 == poolToken0 && token1 == poolToken1) ||
(token0 == poolToken1 && token1 == poolToken0),
"StakeUniswapV3: different token"
);
poolToken0 = token0;
poolToken1 = token1;
poolAddress = PoolAddress.computeAddress(
uniswapV3FactoryAddress,
);
poolFee = fee;
}
| 12,109,784 |
./full_match/80001/0x3A6d9BA21E5132af088AA22Bf9b137Bb9BfC7f2C/sources/contracts/simba.sol
|
Allows contributors to recover their ether in the case of a failed funding campaign.
|
function refund() external {
uint256 simVal = balances[msg.sender];
if (simVal == 0) revert();
balances[msg.sender] = 0;
}
| 842,696 |
./partial_match/1/0x31aDC9b997a5F9150FCE56eC7A8fA73726FbB5c3/sources/verified-sources/0x31aDC9b997a5F9150FCE56eC7A8fA73726FbB5c3/sources/streetracer.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("STREET RACER", "NOS") {
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 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 0;
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);
| 3,987,491 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "../library/openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../library/Pausable.sol";
import "../library/kip/IKIP7.sol";
import "../interface/IPoolToken.sol";
import "../interface/IBasePool.sol";
import "./StableSwap.sol";
/**
* @dev BasePool is the solidity implementation of Curve Finance
* Original code https://github.com/curvefi/curve-contract/blob/master/contracts/pools/3pool/StableSwap3Pool.vy
*/
abstract contract BasePool is IBasePool, StableSwap {
// @dev WARN: be careful to add new variable here
uint256[50] private __storageBuffer;
constructor(uint256 _N) StableSwap(_N) {}
/// @notice Contract initializer
/// @param _coins Addresses of KIP7 contracts of coins
/// @param _poolToken Address of the token representing LP share
/// @param _initialA Amplification coefficient multiplied by n * (n - 1)
/// @param _fee Fee to charge for exchanges
/// @param _adminFee Admin fee
function __BasePool_init(
address[] memory _coins,
uint256[] memory _PRECISION_MUL,
uint256[] memory _RATES,
address _poolToken,
uint256 _initialA,
uint256 _fee,
uint256 _adminFee
) internal initializer {
__StableSwap_init(_coins, _PRECISION_MUL, _RATES, _poolToken, _initialA, _fee, _adminFee);
}
function balances(uint256 i) public view override(II4ISwapPool, StableSwap) returns (uint256) {
return _storedBalances[i];
}
// 10**18 precision
function _xp() internal view returns (uint256[] memory) {
uint256[] memory result = new uint256[](N_COINS);
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (RATES[i] * _storedBalances[i]) / PRECISION;
}
return result;
}
// 10**18 precision
function _xpMem(uint256[] memory _balances) internal view returns (uint256[] memory) {
uint256[] memory result = new uint256[](N_COINS);
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (RATES[i] * _balances[i]) / PRECISION;
}
return result;
}
function getDMem(uint256[] memory _balances, uint256 amp) internal view returns (uint256) {
return getD(_xpMem(_balances), amp);
}
function getVirtualPrice() external view override returns (uint256) {
/*
Returns portfolio virtual price (for calculating profit)
scaled up by 1e18
*/
uint256 D = getD(_xp(), _A());
// D is in the units similar to DAI (e.g. converted to precision 1e18)
// When balanced, D = n * x_u - total virtual value of the portfolio
uint256 tokenSupply = IPoolToken(token).totalSupply();
return (D * PRECISION) / tokenSupply;
}
/// @notice Simplified method to calculate addition or reduction in token supply at
/// deposit or withdrawal without taking fees into account (but looking at
/// slippage).
/// Needed to prevent front-running, not for precise calculations!
/// @param amounts amount list of each assets
/// @param deposit the flag whether deposit or withdrawal
/// @return the amount of lp tokens
function calcTokenAmount(uint256[] memory amounts, bool deposit) external view override returns (uint256) {
/*
Simplified method to calculate addition or reduction in token supply at
deposit or withdrawal without taking fees into account (but looking at
slippage) .
Needed to prevent front-running, not for precise calculations!
*/
uint256[] memory _balances = _storedBalances;
uint256 amp = _A();
uint256 D0 = getDMem(_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
if (deposit) {
_balances[i] += amounts[i];
} else {
_balances[i] -= amounts[i];
}
}
uint256 D1 = getDMem(_balances, amp);
uint256 tokenAmount = IPoolToken(token).totalSupply();
uint256 diff = 0;
if (deposit) {
diff = D1 - D0;
} else {
diff = D0 - D1;
}
return (diff * tokenAmount) / D0;
}
function addLiquidity(uint256[] memory amounts, uint256 minMintAmount) external payable override nonReentrant whenNotPaused returns (uint256) {
require(msg.value == 0);
uint256 amp = _A();
uint256 tokenSupply = IPoolToken(token).totalSupply();
// Initial invariant
uint256 D0 = 0;
uint256[] memory oldBalances = _storedBalances;
if (tokenSupply > 0) {
D0 = getDMem(oldBalances, amp);
}
uint256[] memory newBalances = arrCopy(oldBalances);
for (uint256 i = 0; i < N_COINS; i++) {
uint256 inAmount = amounts[i];
if (tokenSupply == 0) {
require(inAmount > 0); // dev: initial deposit requires all coins
}
address in_coin = coins[i];
// Take coins from the sender
if (inAmount > 0) {
// "safeTransferFrom" which works for KIP7s which return bool or not
rawCall(in_coin, abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), amounts[i]));
}
newBalances[i] = oldBalances[i] + inAmount;
}
// Invariant after change
uint256 D1 = getDMem(newBalances, amp);
require(D1 > D0);
// We need to recalculate the invariant accounting for fees
// to calculate fair user's share
uint256 D2 = D1;
uint256[] memory fees = new uint256[](N_COINS);
if (tokenSupply > 0) {
// Only account for fees if we are not the first to deposit
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256 _adminFee = adminFee;
for (uint256 i = 0; i < N_COINS; i++) {
uint256 idealBalance = (D1 * oldBalances[i]) / D0;
uint256 difference = 0;
if (idealBalance > newBalances[i]) {
difference = idealBalance - newBalances[i];
} else {
difference = newBalances[i] - idealBalance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
_storedBalances[i] = newBalances[i] - ((fees[i] * _adminFee) / FEE_DENOMINATOR);
newBalances[i] -= fees[i];
}
D2 = getDMem(newBalances, amp);
} else {
_storedBalances = newBalances;
}
// Calculate, how much pool tokens to mint
uint256 mintAmount = 0;
if (tokenSupply == 0) {
mintAmount = D1; // Take the dust if there was any
} else {
mintAmount = (tokenSupply * (D2 - D0)) / D0;
}
require(mintAmount >= minMintAmount, "Slippage screwed you");
// Mint pool tokens
IPoolToken(token).mint(msg.sender, mintAmount);
emit AddLiquidity(msg.sender, amounts, fees, D1, tokenSupply + mintAmount);
return mintAmount;
}
function _getDy(
uint256 i,
uint256 j,
uint256 dx,
bool withoutFee
) internal view override returns (uint256) {
// dx and dy in c-units
uint256[] memory xp = _xp();
uint256 x = xp[i] + ((dx * RATES[i]) / PRECISION);
uint256 y = getY(i, j, x, xp);
uint256 dy = ((xp[j] - y - 1) * PRECISION) / RATES[j];
uint256 _fee = ((withoutFee ? 0 : fee) * dy) / FEE_DENOMINATOR;
return dy - _fee;
}
// reference: https://github.com/curvefi/curve-contract/blob/c6df0cf14b557b11661a474d8d278affd849d3fe/contracts/pools/y/StableSwapY.vy#L351
function _getDx(
uint256 i,
uint256 j,
uint256 dy
) internal view override returns (uint256) {
uint256[] memory xp = _xp();
uint256 y = xp[j] - (((dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - fee)) * RATES[j]) / PRECISION;
uint256 x = getY(j, i, y, xp);
uint256 dx = ((x - xp[i]) * PRECISION) / RATES[i];
return dx;
}
function _getDyUnderlying(
uint256 i,
uint256 j,
uint256 dx,
bool withoutFee
) internal view override returns (uint256) {
// dx and dy in underlying units
uint256[] memory xp = _xp();
uint256 x = xp[i] + dx * PRECISION_MUL[i];
uint256 y = getY(i, j, x, xp);
uint256 dy = (xp[j] - y - 1) / PRECISION_MUL[j];
uint256 _fee = ((withoutFee ? 0 : fee) * dy) / FEE_DENOMINATOR;
return dy - _fee;
}
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 minDy
) external payable override nonReentrant whenNotPaused returns (uint256) {
require(msg.value == 0);
uint256[] memory oldBalances = _storedBalances;
uint256[] memory xp = _xpMem(oldBalances);
address inputCoin = coins[i];
// "safeTransferFrom" which works for KIP7s which return bool or not
rawCall(inputCoin, abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), dx));
uint256 x = xp[i] + (dx * RATES[i]) / PRECISION;
uint256 y = getY(i, j, x, xp);
uint256 dy = xp[j] - y - 1; // -1 just in case there were some rounding errors
uint256 dyFee = (dy * fee) / FEE_DENOMINATOR;
// Convert all to real units
dy = ((dy - dyFee) * PRECISION) / RATES[j];
require(dy >= minDy, "Exchange resulted in fewer coins than expected");
uint256 dyAdminFee = (dyFee * adminFee) / FEE_DENOMINATOR;
dyAdminFee = (dyAdminFee * PRECISION) / RATES[j];
// Change balances exactly in same way as we change actual KIP7 coin amounts
_storedBalances[i] = oldBalances[i] + dx;
// When rounding errors happen, we undercharge admin fee in favor of LP
_storedBalances[j] = oldBalances[j] - dy - dyAdminFee;
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[j], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, dy));
emit TokenExchange(msg.sender, i, dx, j, dy, dyFee);
return dy;
}
/// @notice Withdraw coins from the pool
/// @dev Withdrawal amounts are based on current deposit ratios
/// @param _amount Quantity of LP tokens to burn in the withdrawal
/// @param minAmounts Minimum amounts of underlying coins to receive
/// @return List of amounts of coins that were withdrawn
function removeLiquidity(uint256 _amount, uint256[] memory minAmounts) external override nonReentrant returns (uint256[] memory) {
uint256 totalSupply = IPoolToken(token).totalSupply();
uint256[] memory amounts = new uint256[](N_COINS);
uint256[] memory fees = new uint256[](N_COINS); // Fees are unused but we've got them historically in event
for (uint256 i = 0; i < N_COINS; i++) {
uint256 value = (_storedBalances[i] * _amount) / totalSupply;
require(value >= minAmounts[i], "Withdrawal resulted in fewer coins than expected");
_storedBalances[i] -= value;
amounts[i] = value;
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, value));
}
IPoolToken(token).burn(msg.sender, _amount); // dev: insufficient funds
emit RemoveLiquidity(msg.sender, amounts, fees, totalSupply - _amount);
return amounts;
}
function removeLiquidityImbalance(uint256[] memory amounts, uint256 maxBurnAmount)
external
override
nonReentrant
whenNotPaused
returns (uint256)
{
uint256 tokenSupply = IPoolToken(token).totalSupply();
require(tokenSupply != 0); // dev: zero total supply
uint256 amp = _A();
uint256[] memory oldBalances = _storedBalances;
uint256[] memory newBalances = arrCopy(oldBalances);
uint256 D0 = getDMem(oldBalances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
newBalances[i] -= amounts[i];
}
uint256 D1 = getDMem(newBalances, amp);
uint256[] memory fees = new uint256[](N_COINS);
{
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256 _adminFee = adminFee;
for (uint256 i = 0; i < N_COINS; i++) {
uint256 idealBalance = (D1 * oldBalances[i]) / D0;
uint256 difference = 0;
if (idealBalance > newBalances[i]) {
difference = idealBalance - newBalances[i];
} else {
difference = newBalances[i] - idealBalance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
_storedBalances[i] = newBalances[i] - ((fees[i] * _adminFee) / FEE_DENOMINATOR);
newBalances[i] -= fees[i];
}
}
uint256 D2 = getDMem(newBalances, amp);
uint256 tokenAmount = ((D0 - D2) * tokenSupply) / D0;
require(tokenAmount != 0); // dev: zero tokens burned
tokenAmount += 1; // In case of rounding errors - make it unfavorable for the "attacker"
require(tokenAmount <= maxBurnAmount, "Slippage screwed you");
IPoolToken(token).burn(msg.sender, tokenAmount); // dev: insufficient funds
for (uint256 i = 0; i < N_COINS; i++) {
if (amounts[i] != 0) {
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, amounts[i]));
}
}
emit RemoveLiquidityImbalance(msg.sender, amounts, fees, D1, tokenSupply - tokenAmount);
return tokenAmount;
}
function _calcWithdrawOneCoin(
uint256 _tokenAmount,
uint256 i,
bool withoutFee
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
// First, need to calculate
// * Get current D
// * Solve Eqn against y_i for D - _tokenAmount
uint256 amp = _A();
uint256 totalSupply = IPoolToken(token).totalSupply();
uint256[] memory xp = _xp();
uint256 D0 = getD(xp, amp);
uint256 D1 = D0 - (_tokenAmount * D0) / totalSupply;
uint256[] memory xpReduced = arrCopy(xp);
uint256 newY = getYD(amp, i, xp, D1);
uint256 dy0 = (xp[i] - newY) / PRECISION_MUL[i]; // w/o fees, precision depends on coin
{
uint256 _fee = ((withoutFee ? 0 : fee) * N_COINS) / (4 * (N_COINS - 1));
for (uint256 j = 0; j < N_COINS; j++) {
uint256 dxExpected = 0;
if (j == i) {
dxExpected = (xp[j] * D1) / D0 - newY;
} else {
dxExpected = xp[j] - (xp[j] * D1) / D0;
// 10**18
}
xpReduced[j] -= (_fee * dxExpected) / FEE_DENOMINATOR;
}
}
uint256 dy = xpReduced[i] - getYD(amp, i, xpReduced, D1);
dy = (dy - 1) / PRECISION_MUL[i]; // Withdraw less to account for rounding errors
return (dy, dy0 - dy, totalSupply);
}
function calcWithdrawOneCoin(uint256 _tokenAmount, uint256 i) external view override returns (uint256) {
(uint256 result, , ) = _calcWithdrawOneCoin(_tokenAmount, i, false);
return result;
}
function calcWithdrawOneCoinWithoutFee(uint256 _tokenAmount, uint256 i) external view override returns (uint256) {
(uint256 result, , ) = _calcWithdrawOneCoin(_tokenAmount, i, true);
return result;
}
function removeLiquidityOneCoin(
uint256 _tokenAmount,
uint256 i,
uint256 minAmount
) external override nonReentrant whenNotPaused returns (uint256) {
/*
Remove _amount of liquidity all in a form of coin i
*/
(uint256 dy, uint256 dyFee, uint256 totalSupply) = _calcWithdrawOneCoin(_tokenAmount, i, false);
require(dy >= minAmount, "Not enough coins removed");
_storedBalances[i] -= (dy + (dyFee * adminFee) / FEE_DENOMINATOR);
IPoolToken(token).burn(msg.sender, _tokenAmount); // dev: insufficient funds
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, dy));
uint256[] memory amounts = new uint256[](N_COINS);
uint256[] memory fees = new uint256[](N_COINS);
amounts[i] = dy;
fees[i] = dyFee;
emit RemoveLiquidityOne(msg.sender, _tokenAmount, amounts, fees, totalSupply - _tokenAmount);
return dy;
}
function transferOwnership(address newOwner) public override(IStableSwap, StableSwap) onlyOwner {
super.transferOwnership(newOwner);
}
function adminBalances(uint256 i) public view override(IStableSwap, StableSwap) returns (uint256) {
return IKIP7(coins[i]).balanceOf(address(this)) - _storedBalances[i];
}
function withdrawAdminFees(address recipient) external override onlyOperator {
require(recipient != address(0), "StableSwap::withdrawAdminFee: 0 address");
for (uint256 i = 0; i < N_COINS; i++) {
address c = coins[i];
uint256 value = IKIP7(c).balanceOf(address(this)) - _storedBalances[i];
if (value > 0) {
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(c, abi.encodeWithSignature("transfer(address,uint256)", recipient, value));
}
}
}
function donateAdminFees() external override onlyOwner {
for (uint256 i = 0; i < N_COINS; i++) {
_storedBalances[i] = IKIP7(coins[i]).balanceOf(address(this));
}
}
}
|
"safeTransferFrom" which works for KIP7s which return bool or not Convert all to real units Change balances exactly in same way as we change actual KIP7 coin amounts When rounding errors happen, we undercharge admin fee in favor of LP "safeTransfer" which works for KIP7s which return bool or not
|
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 minDy
) external payable override nonReentrant whenNotPaused returns (uint256) {
require(msg.value == 0);
uint256[] memory oldBalances = _storedBalances;
uint256[] memory xp = _xpMem(oldBalances);
address inputCoin = coins[i];
rawCall(inputCoin, abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), dx));
uint256 x = xp[i] + (dx * RATES[i]) / PRECISION;
uint256 y = getY(i, j, x, xp);
uint256 dyFee = (dy * fee) / FEE_DENOMINATOR;
dy = ((dy - dyFee) * PRECISION) / RATES[j];
require(dy >= minDy, "Exchange resulted in fewer coins than expected");
uint256 dyAdminFee = (dyFee * adminFee) / FEE_DENOMINATOR;
dyAdminFee = (dyAdminFee * PRECISION) / RATES[j];
_storedBalances[i] = oldBalances[i] + dx;
_storedBalances[j] = oldBalances[j] - dy - dyAdminFee;
rawCall(coins[j], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, dy));
emit TokenExchange(msg.sender, i, dx, j, dy, dyFee);
return dy;
}
| 1,022,121 |
./full_match/5/0x18AF3db49e20eE86207C62645c882d4696d0b66C/sources/contracts/Pool.sol
|
When ratio of amounts In provided by the user is greater than the pool balances ratio Local copies to avoid stack too deep 'amountOut' is the result of 'onVirtualSwap' 'amountsInForVirtualSwap' is the input amount used when calling 'onVirtualSwap' 'amountOut' is the result of 'onVirtualSwap' 'amountsInForVirtualSwap' is the input amount used when calling 'onVirtualSwap'
|
function _unEqualJoin(
uint256[] memory balances,
uint256[] memory amountsIn,
uint256[] memory actualJoinAmountsIn,
uint256[] memory protocolSwapFeeAmount,
uint256 protocolSwapFeePercentage,
uint256 amountsInRatio,
uint256 poolBalancesRatio
) private returns (uint256[] memory, uint256[] memory) {
uint256 amountOut;
if (amountsInRatio > poolBalancesRatio) {
uint256 balancesIn = balances[0];
uint256 balancesOut = balances[1];
uint256 amountTokenIn = amountsIn[0];
uint256 amountTokenOut = amountsIn[1];
uint256 amountsInForVirtualSwap = _calculateVirtualSwapAmountIn(
balancesIn,
balancesOut,
amountTokenIn,
amountTokenOut,
_weight0,
_weight1
);
(
amountOut,
amountsInForVirtualSwap,
protocolSwapFeeAmount
) = _doVirtualSwap(
amountTokenIn,
amountTokenOut,
amountsInForVirtualSwap,
_token0,
protocolSwapFeePercentage,
balancesIn,
balancesOut
);
actualJoinAmountsIn[0] = amountTokenIn - amountsInForVirtualSwap;
actualJoinAmountsIn[1] = amountTokenOut + amountOut;
uint256 balancesIn = balances[1];
uint256 balancesOut = balances[0];
uint256 amountTokenIn = amountsIn[1];
uint256 amountTokenOut = amountsIn[0];
uint256 amountsInForVirtualSwap = _calculateVirtualSwapAmountIn(
balancesIn,
balancesOut,
amountTokenIn,
amountTokenOut,
_weight1,
_weight0
);
(
amountOut,
amountsInForVirtualSwap,
protocolSwapFeeAmount
) = _doVirtualSwap(
amountTokenIn,
amountTokenOut,
amountsInForVirtualSwap,
_token1,
protocolSwapFeePercentage,
balancesIn,
balancesOut
);
actualJoinAmountsIn[0] = amountTokenOut + amountOut;
actualJoinAmountsIn[1] = amountTokenIn - amountsInForVirtualSwap;
}
return (actualJoinAmountsIn, protocolSwapFeeAmount);
}
| 7,087,784 |
./full_match/80001/0x700dbe6E0720FEF36EfB3D9B98e240F28B3e7A53/sources/contracts/8_NftUrl.sol
|
verify creator (address,NFT address/ownership,wager<balance) require(address(msg.sender).balance>CreatorWager,"Not enough money to wager"); const userEthNFTs = await Moralis.Web3API.account.getNFTs(); require(userEthNFTs.contain(nftAddress),"You don't own this NFT on the Ethereum blockchain");
|
function addNft(string memory NftUrl, address nftAddress) public payable {
Battle memory newBattle = Battle(stateBattleNumber,nftAddress,NftUrl);
stateBattleNumber++;
battles.push(newBattle);
}
| 878,556 |
pragma solidity ^0.5.0;
import "./Graph.sol";
import "./SafeMath.sol";
import "./Agreement.sol";
contract MainGraph {
using SafeMath for uint256;
int256 public constant MAX_INT = int256(~(uint256(1) << 255));
uint256 constant MAX_UINT = ~uint256(0);
address public netereumAddress;
address[] confirmedCoordinators;
uint256 public numberOfCoordinators = 0;
// constructor(address _netereumAddress) public
// {
// netereumAddress = _netereumAddress;
// }
function setNetereum(address addr) public
{
netereumAddress = addr;
}
mapping(address => Graph.Node) public nodes;
mapping(uint256 => Graph.Edge) public edges;
uint256 public numberOfNodes;
uint256 public numberOfEdges;
function addNode(address coordinator) public
{
require(msg.sender == netereumAddress);
nodes[coordinator].coordinator = coordinator;
numberOfNodes ++;
nodes[coordinator].isInserted = true;
confirmedCoordinators.push(coordinator);
numberOfCoordinators++;
}
mapping(address => mapping(address => uint256)) public edgeIndex;/* a mapping that maps a combined key containing the source coordinator
and the destination coordinator to the index + 1 of that edge in the edges array*/
function addEdge(address sourceCoordinator, address destinationCoordinator,
uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag)
// if flag = 0, then the function has been called normally otherwise the edge may create a negative cycle thus an additional algorithm will be executed
internal
{
if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted)
{
uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator];
if (index == 0)//it means that this edge is a new edge
{
edges[numberOfEdges].source = sourceCoordinator;
edges[numberOfEdges].destination = destinationCoordinator;
edges[numberOfEdges].weights[0].exchangeRate = exchangeRate;
edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog;
edges[numberOfEdges].weights[0].reverse = reverse;
edges[numberOfEdges].weights[0].sourceAmount = sourceAmount;
edges[numberOfEdges].weights[0].agreementAddress = agreementAddress;
edges[numberOfEdges].numberOfWeights++;
numberOfEdges++;
edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges;
}
else
{
uint256 index2 = 0;
index --;
for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++)
if (edges[index].weights[index2].agreementAddress == agreementAddress)
break;
if (index2 == edges[index].numberOfWeights)// if the associated weight element was not found
{
edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate;
edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog;
edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount;
edges[index].weights[edges[index].numberOfWeights].reverse = reverse;
edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress;
edges[index].numberOfWeights++;
if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate)
{
edges[index].minIndex = edges[index].numberOfWeights - 1;
}
}
else
{
edges[index].weights[index2].sourceAmount += sourceAmount;
}
}
if(flag == 1)
{
if(exchangeRateLog > 0)
return;
else
{
//running the bellman ford with source = sourceCoordinator
while(true)
{
for (uint256 i = 0; i < numberOfCoordinators; i++)
{
if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator)
{
nodes[confirmedCoordinators[i]].distance = 0;
}
else
{
nodes[confirmedCoordinators[i]].distance = MAX_INT;
}
nodes[confirmedCoordinators[i]].parent = address(0);
//SHOULD BE MODIFIED
}
/*the Bellman-Ford algorithm for finding the shortest path and distance between
our source coordinator and destination coordinator*/
for (uint i = 1; i < numberOfNodes; i++)// we can use number of coordinators instead of number of nodes
{
for (uint j = 0; j < numberOfEdges; j++)
{
if (nodes[edges[j].source].distance != MAX_INT &&
nodes[edges[j].source].distance +
edges[j].weights[edges[j].minIndex].exchangeRateLog <
nodes[edges[j].destination].distance)
{
nodes[edges[j].destination].distance =
nodes[edges[j].source].distance +
edges[j].weights[edges[j].minIndex].exchangeRateLog;
nodes[edges[j].destination].parent = edges[j].source;
}
}
}
address tempDestination ;
bool containsNegativeCycle = false;
for (uint256 j = 0; j < numberOfEdges; j++)
{
if (nodes[edges[j].source].distance != MAX_INT &&
nodes[edges[j].source].distance +
edges[j].weights[edges[j].minIndex].exchangeRateLog <
nodes[edges[j].destination].distance)
{
indexxx++;
tempDestination = nodes[edges[j].destination].coordinator;
containsNegativeCycle = true;
break;
}
}
if(!containsNegativeCycle)
break;
else
{
uint256 transferAmount = 0;
uint256 destAmount = 0;
address [] memory cycle = new address[](2 * numberOfEdges);//array of the indexes of the edges
uint256 cycleLength = 0;
address tempDestination2 = tempDestination;
while (true)
{
cycle[cycleLength] = tempDestination;
cycle[cycleLength + 1] = nodes[tempDestination].parent;
cycleLength += 2;
// path.push(tempDestination);
// path.push(nodes[tempDestination].parent);
tempDestination = nodes[tempDestination].parent;
if(tempDestination == tempDestination2)
break;
}
for(uint256 i = cycleLength - 1;i >= 1 ; i-=2)
{
index = edgeIndex[cycle[i]][cycle[i-1]] - 1;
if(i == cycleLength - 1)
{
if(edges[index].weights[edges[index].minIndex].reverse == 0)
{
transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/
edges[index].weights[edges[index].minIndex].exchangeRate ;
}
else
{
uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate;
transferAmount = temp/ 1000000;
if(temp % 1000000 != 0)
transferAmount++;//for getting the upper bound of the result in the division
}
}
else if(i < cycleLength - 1)
{
if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount )
transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount;
if(edges[index].weights[edges[index].minIndex].reverse == 0)
{
transferAmount = (transferAmount *1000000) /
edges[index].weights[edges[index].minIndex].exchangeRate;
}
else
{
uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate;
transferAmount = temp / 1000000 ;
if(temp % 1000000 != 0)
transferAmount++;
}
}
// pathAmounts[cycleLength - 1 - i] = transferAmount;
if(i == 1)
break;
}
for(uint256 i = 0;i < cycleLength ; i+=2)
{
index = edgeIndex[cycle[i+1]][cycle[i]] - 1;
if(edges[index].weights[edges[index].minIndex].reverse == 0)
{
uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate;
transferAmount = temp/ 1000000;
if(temp % 1000000 != 0)
transferAmount++;
removeEdge(index,transferAmount,address(0),uint8(0));
}
else
{
transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate;
// if(edges[index].weights[edges[index].minIndex].exchangeRate % 1000000 != 0)
// transferAmount ++;
removeEdge(index,transferAmount,address(0),uint8(0));
}
// pathAmounts[pathLength / 2] = transferAmount;
}
}
//break;
}
}
}
}
}
uint256 public indexxx = 20;
function wrappedAddEdge(address sourceCoordinator, address destinationCoordinator,
uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress) public
{
require(msg.sender == netereumAddress);
require(nodes[sourceCoordinator].isInserted == true, "3");
require(nodes[destinationCoordinator].isInserted == true, "4");
addEdge(sourceCoordinator,destinationCoordinator,
exchangeRate, exchangeRateLog, reverse, sourceAmount, agreementAddress , 1);
}
//app.wrappedAddEdge('0x3c28ee5a77b6aa58c79E10C8416f32C8d916705a','0xfBa507d4eAc1A2D4144335C793Edae54d212fa22',1000000000,2000000,8,15687229690,'0x3c28ee5a77b6aa58c79E10C8416f32C8d916705a')
function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256)
{
uint256 mainIndex ;
uint256 weightIndex = 0;
uint256 remainingAmount = 0;
if(flag == 0)
{
weightIndex = edges[index].minIndex;
mainIndex = index;
}
else
{
mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ;
for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++)
{
if(edges[mainIndex].weights[i].agreementAddress == agreementAddress)
{
weightIndex = i;
break;
}
}
}
edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount;
uint8 forLength = 1;
if(flag == 2)
{
forLength = 2;
}
for(uint8 j = 0; j < forLength; j++)
{
if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0)
{
if(j == 0)
{
remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount;
}
edges[mainIndex].weights[weightIndex].exchangeRate =
edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate;
edges[mainIndex].weights[weightIndex].exchangeRateLog =
edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog;
edges[mainIndex].weights[weightIndex].reverse =
edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse;
edges[mainIndex].weights[weightIndex].sourceAmount =
edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount;
edges[mainIndex].weights[weightIndex].agreementAddress =
edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress;
edges[mainIndex].numberOfWeights --;
uint256 min = MAX_UINT;
for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++)
{
if (min > edges[mainIndex].weights[i].exchangeRate)
{
min = edges[mainIndex].weights[i].exchangeRate;
edges[mainIndex].minIndex = i;
}
}
if (edges[mainIndex].numberOfWeights == 0)
{
//swapping the current edge with the last edge and decrementing the number of edges
edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0;
edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1;
edges[mainIndex].source = edges[numberOfEdges - 1].source;
edges[mainIndex].destination = edges[numberOfEdges - 1].destination;
// code for swapping the weights of the desired edge and the last edge
for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++)
{
edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog;
edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate;
edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse;
edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount;
edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress;
}
edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights;
edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex;
numberOfEdges --;
}
}
if(flag == 2 && j == 0)
{
mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()];
if(mainIndex > 0)
{
mainIndex --;
for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++)
{
if(edges[mainIndex].weights[i].agreementAddress == agreementAddress)
{
weightIndex = i;
break;
}
}
}
else
break;
}
}
if(agreementAddress == address (0))
remainingAmount = 0;
return remainingAmount;
}
function wrappedRemoveEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) public returns(uint256)
{
require(msg.sender == netereumAddress);
return removeEdge(index,sourceAmount,agreementAddress,flag);
}
address[] public path;
uint256 public amounttt;
mapping(uint256 => uint256) public pathAmounts;
uint256 public pathLength;
function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost,
uint256 _sellerCost,bool virtual) public returns (bool,uint256)
{
require(msg.sender == netereumAddress);
// for(uint256 i = numberOfAgreements - 1;i >= 0; i--)//removing the agreements and edges that have expired
// {
// if(agreements[i].expireTime() < block.timestamp)
// {
// removeEdge(0,0,address(agreements[i]),2);
//// agreementStatus[address(agreements[i])] = 3;//expired
//// agreements[i] = agreements[numberOfAgreements - 1];//needs to be Checkeddddd
//// agreements.pop();
// }
// if(i == 0)
// break;
// }
if(pathLength > 0)
{
for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too,
but that required the conversion of pathLength to int256 which would be hazardous */
{
path.pop();
path.pop();
pathAmounts[i] = 0;
pathAmounts[i-1] = 0;
if(i == 1)// because of i being uint, when i == 1 the next iteration will start with i = MAX_uint
break;
}
}
pathLength = 0;
uint256 pathStart = 0;// the index that the path for the current iteration starts
uint256 sum = 0;
uint256 amount = 0;// the amount that the sender has to pay if the transaction is accepted by the system
while (sum < _sellerCost)
{
// initializing the distance of the nodes
for (uint i = 0; i < numberOfCoordinators; i++)
{
if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator)
{
nodes[confirmedCoordinators[i]].distance = 0;
}
else
{
nodes[confirmedCoordinators[i]].distance = MAX_INT;
}
nodes[confirmedCoordinators[i]].parent = address(0);
//SHOULD BE MODIFIED
}
/*the Bellman-Ford algorithm for finding the shortest path and distance between
our source coordinator and destination coordinator*/
for (uint i = 1; i < numberOfNodes; i++)// we can use number of coordinators instead of number of nodes
{
for (uint j = 0; j < numberOfEdges; j++)
{
if (nodes[edges[j].source].distance != MAX_INT &&
nodes[edges[j].source].distance +
edges[j].weights[edges[j].minIndex].exchangeRateLog <
nodes[edges[j].destination].distance)
{
nodes[edges[j].destination].distance =
nodes[edges[j].source].distance +
edges[j].weights[edges[j].minIndex].exchangeRateLog;
nodes[edges[j].destination].parent = edges[j].source;
}
}
}
// /* backtracking from the destination Coordinator to the source Coordinator to
// find the maximum amount that can be transferred through this path*/
uint256 transferAmount = 0;// the amount that the current path can transfer
uint256 minAmount = 0; // the minimum amount that can be sent to the receiver
address tempDestination = _sellerCoordinator;
require(nodes[tempDestination].parent != address(0), "13");
while (tempDestination != _buyerCoordinator)
{
path.push(tempDestination);
path.push(nodes[tempDestination].parent);
pathLength += 2;
uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1;
uint256 destAmount = 0;
if(edges[index].weights[edges[index].minIndex].reverse == 0)
{
destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/
edges[index].weights[edges[index].minIndex].exchangeRate ;
}
else
{
uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate;
destAmount = temp / 1000000;
if(temp % 1000000 != 0)
destAmount++;
}
if(pathLength == 2)
{
if(destAmount < _sellerCost - sum)
{
transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount;
}
else
{
if(edges[index].weights[edges[index].minIndex].reverse == 0)
{
uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate;
transferAmount = temp / 1000000 ;
if(temp % 1000000 != 0)
transferAmount++;
}
else
{
transferAmount = ((_sellerCost - sum) *1000000) /
edges[index].weights[edges[index].minIndex].exchangeRate;
}
}
}
else if(pathLength > 2)
{
if(transferAmount > destAmount )
transferAmount = destAmount;
if(edges[index].weights[edges[index].minIndex].reverse == 0)
{
uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate;
transferAmount = temp / 1000000 ;
if(temp % 1000000 != 0)
transferAmount++;
}
else
{
transferAmount = (transferAmount *1000000) /
edges[index].weights[edges[index].minIndex].exchangeRate;
}
}
tempDestination = nodes[tempDestination].parent;
}
amount += transferAmount;
minAmount = transferAmount;
// backtracking again to reduce the weights of the edges
for(uint256 i = pathLength - 1;i >= pathStart + 1 ; i-=2)
{
uint256 index = edgeIndex[path[i]][path[i-1]] - 1;
pathAmounts[i-1] = minAmount;
if(edges[index].weights[edges[index].minIndex].reverse == 0)
{
uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate;
addEdge(path[i-1],path[i],
edges[index].weights[edges[index].minIndex].exchangeRate,
-1 * edges[index].weights[edges[index].minIndex].exchangeRateLog,
1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0);
removeEdge(index,minAmount,address(0),uint8(0));
minAmount = temp;
}
else
{
uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate);
if(temp % 1000000 != 0)
{
temp = temp / 1000000;
temp ++;
}
else
temp = temp /1000000;
addEdge(path[i-1],path[i],
edges[index].weights[edges[index].minIndex].exchangeRate,
-1 * edges[index].weights[edges[index].minIndex].exchangeRateLog,
0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0);
removeEdge(index,minAmount,address(0),uint8(0));
minAmount = temp;
}
pathAmounts[i] = minAmount;
if(i == pathStart + 1)
break;
}
sum += minAmount;
pathStart = pathLength;
amounttt = amount;
}
if (amount > _buyerCost || virtual)//changing the graph to the previous state //BE CAREFUL HEREEEEEE
{
// neutralizing the effects that our computation had on the graph
for (uint256 i = pathLength - 1; i >= 1; i -= 2)
{
uint256 index = edgeIndex[path[i - 1]][path[i]] -1;
if(edges[index].weights[edges[index].minIndex].reverse == 0)
{
addEdge(path[i],path[i-1],
edges[index].weights[edges[index].minIndex].exchangeRate,
-1 * edges[index].weights[edges[index].minIndex].exchangeRateLog,
1,pathAmounts[i-1],
edges[index].weights[edges[index].minIndex].agreementAddress,0);
removeEdge(index,pathAmounts[i],address(0),0);
}
else
{
addEdge(path[i],path[i-1],
edges[index].weights[edges[index].minIndex].exchangeRate,
-1 * edges[index].weights[edges[index].minIndex].exchangeRateLog,
0,pathAmounts[i-1],
edges[index].weights[edges[index].minIndex].agreementAddress,0);
removeEdge(index,pathAmounts[i],address(0),0);
}
if(i == 1)
break;
}
amounttt = 1;
return (false,amount);
}
else
return (true,amount);
}
function getParent(address addr) public returns(address)
{
return nodes[addr].parent;
}
function getMinIndex(uint256 i) public returns(uint256)
{
return edges[i].minIndex;
}
function getNumberOfWeights(uint256 i) public returns(uint256)
{
return edges[i].numberOfWeights;
}
function getAmount(uint256 i,uint256 j) public returns(uint256)
{
return edges[i].weights[j].sourceAmount;
}
function getRate(uint256 i,uint256 j) public returns(uint256)
{
return edges[i].weights[j].exchangeRate;
}
function getLog(uint256 i,uint256 j) public returns(int256)
{
return edges[i].weights[j].exchangeRateLog;
}
}
|
app.wrappedAddEdge('0x3c28ee5a77b6aa58c79E10C8416f32C8d916705a','0xfBa507d4eAc1A2D4144335C793Edae54d212fa22',1000000000,2000000,8,15687229690,'0x3c28ee5a77b6aa58c79E10C8416f32C8d916705a')swapping the current edge with the last edge and decrementing the number of edges code for swapping the weights of the desired edge and the last edge
|
function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256)
{
uint256 mainIndex ;
uint256 weightIndex = 0;
uint256 remainingAmount = 0;
if(flag == 0)
{
weightIndex = edges[index].minIndex;
mainIndex = index;
}
else
{
mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ;
for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++)
{
if(edges[mainIndex].weights[i].agreementAddress == agreementAddress)
{
weightIndex = i;
break;
}
}
}
edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount;
uint8 forLength = 1;
if(flag == 2)
{
forLength = 2;
}
for(uint8 j = 0; j < forLength; j++)
{
if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0)
{
if(j == 0)
{
remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount;
}
edges[mainIndex].weights[weightIndex].exchangeRate =
edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate;
edges[mainIndex].weights[weightIndex].exchangeRateLog =
edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog;
edges[mainIndex].weights[weightIndex].reverse =
edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse;
edges[mainIndex].weights[weightIndex].sourceAmount =
edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount;
edges[mainIndex].weights[weightIndex].agreementAddress =
edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress;
edges[mainIndex].numberOfWeights --;
uint256 min = MAX_UINT;
for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++)
{
if (min > edges[mainIndex].weights[i].exchangeRate)
{
min = edges[mainIndex].weights[i].exchangeRate;
edges[mainIndex].minIndex = i;
}
}
if (edges[mainIndex].numberOfWeights == 0)
{
edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0;
edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1;
edges[mainIndex].source = edges[numberOfEdges - 1].source;
edges[mainIndex].destination = edges[numberOfEdges - 1].destination;
for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++)
{
edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog;
edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate;
edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse;
edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount;
edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress;
}
edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights;
edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex;
numberOfEdges --;
}
}
if(flag == 2 && j == 0)
{
mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()];
if(mainIndex > 0)
{
mainIndex --;
for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++)
{
if(edges[mainIndex].weights[i].agreementAddress == agreementAddress)
{
weightIndex = i;
break;
}
}
}
else
break;
}
}
if(agreementAddress == address (0))
remainingAmount = 0;
return remainingAmount;
}
| 12,652,449 |
pragma solidity ^0.4.2;
contract token {
function transfer(address, uint256){ }
function balanceOf(address) constant returns (uint256) { }
}
/// @title FairAuction contract
/// @author Christopher Grant - <[email protected]>
contract FairAuction {
/* State */
address public beneficiary;
uint public amountRaised; uint public startTime; uint public deadline; uint public memberCount; uint public crowdsaleCap;
uint256 public tokenSupply;
token public tokenReward;
mapping(address => uint256) public balanceOf;
mapping (uint => address) accountIndex;
bool public finalized;
/* Events */
event TokenAllocation(address recipient, uint amount);
event Finalized(address beneficiary, uint amountRaised);
event FundTransfer(address backer, uint amount);
event FundClaim(address claimant, uint amount);
/* Initialize relevant crowdsale contract details */
function FairAuction(
address fundedAddress,
uint epochStartTime,
uint durationInMinutes,
uint256 capOnCrowdsale,
token contractAddressOfRewardToken
) {
beneficiary = fundedAddress;
startTime = epochStartTime;
deadline = startTime + (durationInMinutes * 1 minutes);
tokenReward = token(contractAddressOfRewardToken);
crowdsaleCap = capOnCrowdsale * 1 ether;
finalized = false;
}
/* default function (called whenever funds are sent to the FairAuction) */
function () payable {
/* Ensure that auction is ongoing */
if (now < startTime) throw;
if (now >= deadline) throw;
uint amount = msg.value;
/* Ensure that we do not pass the cap */
if (amountRaised + amount > crowdsaleCap) throw;
uint256 existingBalance = balanceOf[msg.sender];
/* Tally new members (helps iteration later) */
if (existingBalance == 0) {
accountIndex[memberCount] = msg.sender;
memberCount += 1;
}
/* Track contribution amount */
balanceOf[msg.sender] = existingBalance + amount;
amountRaised += amount;
/* Fire FundTransfer event */
FundTransfer(msg.sender, amount);
}
/* finalize() can be called once the FairAuction has ended, which will allow withdrawals */
function finalize() {
/* Nothing to finalize */
if (amountRaised == 0) throw;
/* Auction still ongoing */
if (now < deadline) {
/* Don't terminate auction before cap is reached */
if (amountRaised < crowdsaleCap) throw;
}
/* Snapshot available supply of reward tokens */
tokenSupply = tokenReward.balanceOf(this);
/* Mark the FairAuction as finalized */
finalized = true;
/* Fire Finalized event */
Finalized(beneficiary, amountRaised);
}
/* individualClaim() can be called by any auction participant once the FairAuction is finalized, to claim the tokens they are owed from the auction */
function individualClaim() {
/* Only allow once auction has been finalized */
if (!finalized) throw;
/* Grant tokens due */
tokenReward.transfer(msg.sender, (balanceOf[msg.sender] * tokenSupply / amountRaised));
/* Fire TokenAllocation event */
TokenAllocation(msg.sender, (balanceOf[msg.sender] * tokenSupply / amountRaised));
/* Prevent repeat-withdrawals */
balanceOf[msg.sender] = 0;
}
/* beneficiarySend() can be called once the FairAuction is finalized, to send the crowdsale proceeds to their destination address */
function beneficiarySend() {
/* Only allow once auction has been finalized */
if (!finalized) throw;
/* Send proceeds to beneficiary */
if (beneficiary.send(amountRaised)) {
/* Fire FundClaim event */
FundClaim(beneficiary, amountRaised);
}
}
/* automaticWithdrawLoop() can be called once the FairAuction is finalized to automatically allocate a batch of auctioned tokens */
function automaticWithdrawLoop(uint startIndex, uint endIndex) {
/* Only allow once auction has been finalized */
if (!finalized) throw;
/* Distribute auctioned tokens fairly among a batch of participants. */
for (uint i=startIndex; i<=endIndex && i<memberCount; i++) {
/* Should not occur */
if (accountIndex[i] == 0)
continue;
/* Grant tokens due */
tokenReward.transfer(accountIndex[i], (balanceOf[accountIndex[i]] * tokenSupply / amountRaised));
/* Fire TokenAllocation event */
TokenAllocation(accountIndex[i], (balanceOf[accountIndex[i]] * tokenSupply / amountRaised));
/* Prevent repeat-withdrawals */
balanceOf[accountIndex[i]] = 0;
}
}
}
|
default function (called whenever funds are sent to the FairAuction) / Ensure that auction is ongoing / Ensure that we do not pass the cap / Tally new members (helps iteration later) /
|
function () payable {
if (now < startTime) throw;
if (now >= deadline) throw;
uint amount = msg.value;
if (amountRaised + amount > crowdsaleCap) throw;
uint256 existingBalance = balanceOf[msg.sender];
if (existingBalance == 0) {
accountIndex[memberCount] = msg.sender;
memberCount += 1;
}
amountRaised += amount;
}
| 988,946 |
./full_match/5/0xC89511CFB3e8cbAA9470a9fE50184EAF7204c175/sources/contracts/TFOP.sol
|
Change the withdraw address for the collection/
|
function setWithdrawAddress(address _walletAddress) external onlyOwner {
withdrawAddress = _walletAddress;
}
| 1,899,969 |
./partial_match/7700/0xb9a907A0c5160FaA86d0B942dc5fd4a3d3051d89/sources/contracts/CypherSkulls.sol
|
change the whitelist max per wallet
|
function setWlMaxPerWallet(uint256 _limit) public onlyOwner {
MaxperWalletWl = _limit;
}
| 3,507,996 |
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/utils/EnumerableMap.sol
pragma solidity ^0.8.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 Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0);
// Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value);
// All indexes are 1-based
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key");
// Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value;
// All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
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(uint160(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(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(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(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/utils/EnumerableSet.sol
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1;
// All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: http://github.com/OpenZeppelin/openzeppelin-contracts/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;
// solhint-disable-next-line no-inline-assembly
assembly {size := extcodesize(account)}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value : amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value : value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/introspection/ERC165.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: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/**
* @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(type(IERC165).interfaceId);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.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;
}
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: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/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: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/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: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/introspection/IERC165.sol
// File: http://github.com/OpenZeppelin/openzeppelin-contracts/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 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) {
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: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/**
* @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(type(IERC721).interfaceId);
_registerInterface(type(IERC721Metadata).interfaceId);
_registerInterface(type(IERC721Enumerable).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 _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString(), ".json"));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual 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 virtual override returns (uint256) {
(uint256 tokenId,) = _tokenOwners.at(index);
return tokenId;
}
/**
* @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 || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.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 = ERC721.ownerOf(tokenId);
// internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[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(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
// internal 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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
// internal owner
}
/**
* @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 {}
}
// File: http://github.com/OpenZeppelin/openzeppelin-contracts/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: https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: UNLICENSED
contract CodeofWonder is ERC721, Ownable {
using SafeMath for uint256;
using Strings for uint256;
uint public constant MAX_TOKENS = 1000;
mapping(uint256 => uint256) public creationDates;
mapping(uint256 => address) public creators;
string public METADATA_PROVENANCE_HASH = "";
string public GENERATOR_ADDRESS = "MYURL/script.php?number=";
constructor() ERC721("Code of Wonder", "COW") {
setBaseURI("garbage uri");
_safeMint(msg.sender, 0);
creationDates[0] = block.number;
creators[0] = msg.sender;
}
function tokensOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function mintToken(uint256 maxTOKENS) public onlyOwner {
require(totalSupply() < MAX_TOKENS, "Sale has already ended");
require(maxTOKENS > 0 && maxTOKENS <= 10, "You can claim minimum 1, maximum 10 tokens");
require(totalSupply().add(maxTOKENS) <= MAX_TOKENS, "Exceeds MAX_TOKENS");
for (uint i = 0; i < maxTOKENS; i++) {
uint mintIndex = totalSupply();
_safeMint(msg.sender, mintIndex);
creationDates[mintIndex] = block.number;
creators[mintIndex] = msg.sender;
}
}
function setProvenanceHash(string memory _hash) public onlyOwner {
METADATA_PROVENANCE_HASH = _hash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function tokenHash(uint256 tokenId) public view returns (bytes32){
require(_exists(tokenId), "DOES NOT EXIST");
return bytes32(keccak256(abi.encodePacked(address(this), creationDates[tokenId], creators[tokenId], tokenId)));
}
function generatorAddress(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "DOES NOT EXIST");
return string(abi.encodePacked(GENERATOR_ADDRESS, tokenId.toString()));
}
}
|
Returns the substraction of two unsigned integers, with an overflow flag. _Available since v3.4._/
|
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
| 16,162 |
pragma solidity ^0.5.12;
import "./MixTokenInterface.sol";
import "./MixTokenItemRegistry.sol";
/**
* @title MixTokenBurn
* @author Jonathan Brown <[email protected]>
* @dev Enable accounts to burn their tokens.
*/
contract MixTokenBurn {
/**
* @dev Amount of tokens burned, linked to next most burned.
*/
struct AccountBurnedLinked {
address next;
uint amount;
}
/**
* @dev Mapping of item to token to burn for that item.
*/
mapping (bytes32 => MixTokenOwnedInterface) itemTokenToBurn;
/**
* @dev Mapping of token to list of items that it should be burned for.
*/
mapping (address => bytes32[]) tokenToBurnItemsList;
/**
* @dev Mapping of account to list of tokens that it has burned.
*/
mapping (address => MixTokenInterface[]) accountTokensBurnedList;
/**
* @dev Mapping of token to mapping of account to AccountBurnedLinked.
*/
mapping (address => mapping (address => AccountBurnedLinked)) tokenAccountBurned;
/**
* @dev Mapping of account to list of itemIds that it has burned the token for.
*/
mapping (address => bytes32[]) accountItemsBurnedList;
/**
* @dev Mapping of itemId to mapping of account to quantity of tokens burned for the item.
*/
mapping (bytes32 => mapping (address => AccountBurnedLinked)) itemAccountBurned;
/**
* @dev Mapping of item to total burned for the item.
*/
mapping (bytes32 => uint) itemBurnedTotal;
/**
* @dev MixItemStoreRegistry contract.
*/
MixItemStoreRegistry public itemStoreRegistry;
/**
* @dev Address of token registry contract.
*/
MixTokenItemRegistry public tokenItemRegistry;
/**
* @dev A token has been burned.
* @param token Address of the token's contract.
* @param itemId Item the token was burned for, or 0 for none.
* @param account Address of the account burning its tokens.
* @param amount Amount of tokens burned.
*/
event BurnToken(MixTokenInterface indexed token, bytes32 indexed itemId, address indexed account, uint amount);
/**
* @dev Revert if amount is zero.
* @param amount Amount that must not be zero.
*/
modifier nonZero(uint amount) {
require (amount != 0, "Amount burned must not be zero.");
_;
}
/**
* @param _itemStoreRegistry Address of the MixItemStoreRegistry contract.
* @param _tokenItemRegistry Address of the MixTokenItemRegistry contract.
*/
constructor(MixItemStoreRegistry _itemStoreRegistry, MixTokenItemRegistry _tokenItemRegistry) public {
// Store the address of the MixItemStoreRegistry contract.
itemStoreRegistry = _itemStoreRegistry;
// Store the address of the MixTokenItemRegistry contract.
tokenItemRegistry = _tokenItemRegistry;
}
/**
* @dev Set the token that can be burned for an item.
* @param itemId itemId of item that is having set which token can be burned for it.
* @param token Address of token that can be burned for the item.
*/
function setTokenToBurnItem(bytes32 itemId, MixTokenOwnedInterface token) external {
MixItemStoreInterface itemStore = itemStoreRegistry.getItemStore(itemId);
// Ensure the item is owned by sender.
require (itemStore.getOwner(itemId) == msg.sender, "Item is not owned by sender.");
// Ensure the token is owned by sender.
require (token.owner() == msg.sender, "Token is not owned by sender.");
// Ensure the item's token has not been set before.
require (itemTokenToBurn[itemId] == MixTokenOwnedInterface(0), "Token to burn for item has already been set.");
// Set the token to burn for the item.
itemTokenToBurn[itemId] = token;
// Add item to list of items that burn token.
tokenToBurnItemsList[address(token)].push(itemId);
}
/**
* @dev Get previous and old previous accounts for inserting into linked list.
* @param accountBurned Linked list of how much each account has burned.
* @param amount Amount that the the new entry will have.
* @return prev Address of the entry preceeding the new entry.
* @return oldPrev Address of the entry preceeding the old entry.
*/
function _getPrev(mapping (address => AccountBurnedLinked) storage accountBurned, uint amount) internal view nonZero(amount) returns (address prev, address oldPrev) {
// Get sender AccountBurnedLinked.
AccountBurnedLinked storage senderBurned = accountBurned[msg.sender];
// Get total.
uint total = senderBurned.amount + amount;
// Search for first account that has burned less than sender.
address next = accountBurned[address(0)].next;
// accountBurned[0].amount == 0
while (total <= accountBurned[next].amount) {
prev = next;
next = accountBurned[next].next;
}
// Is sender already in the list?
if (senderBurned.amount > 0) {
// Search for account.
oldPrev = prev;
while (accountBurned[oldPrev].next != msg.sender) {
oldPrev = accountBurned[oldPrev].next;
}
}
}
/**
* @dev Get previous and old previous accounts for inserting burned tokens into tokenAccountBurned linked list.
* @param token Token that is being burned.
* @param amount Amount of the token that is being burned.
* @return prev Address of the entry preceeding the new entry.
* @return oldPrev Address of the entry preceeding the old entry.
*/
function getBurnTokenPrev(MixTokenInterface token, uint amount) external view returns (address prev, address oldPrev) {
(prev, oldPrev) = _getPrev(tokenAccountBurned[address(token)], amount);
}
/**
* @dev Get previous and old previous accounts for inserting burned tokens for an item into both tokenAccountBurned and itemAccountBurned linked lists.
* @param itemId Item having its token burned.
* @param amount Amount of the token that is being burned.
* @return tokenPrev Address of the entry preceeding the new entry in the tokenAccountBurned linked list.
* @return tokenOldPrev Address of the entry preceeding the old entry in the tokenAccountBurned linked list.
* @return itemPrev Address of the entry preceeding the new entry in the itemAccountBurned linked list.
* @return itemOldPrev Address of the entry preceeding the old entry in the itemAccountBurned linked list.
*/
function getBurnItemPrev(bytes32 itemId, uint amount) external view returns (address tokenPrev, address tokenOldPrev, address itemPrev, address itemOldPrev) {
// Get token contract for item.
address token = address(getTokenToBurnItem(itemId));
// Get previous and old previous for tokenAccountBurned linked list.
(tokenPrev, tokenOldPrev) = _getPrev(tokenAccountBurned[token], amount);
// Get previous and old previous for itemAccountBurned linked list.
(itemPrev, itemOldPrev) = _getPrev(itemAccountBurned[itemId], amount);
}
/**
* @dev Insert amount burned into linked list.
* @param accountBurned Linked list of how much each account has burned.
* @param amount Amount of tokens burned.
* @param prev Address of the entry preceeding the new entry.
* @param oldPrev Address of the entry preceeding the old entry.
*/
function _accountBurnedInsert(mapping (address => AccountBurnedLinked) storage accountBurned, uint amount, address prev, address oldPrev) internal {
// Get sender AccountBurnedLinked.
AccountBurnedLinked storage senderBurned = accountBurned[msg.sender];
// Get total.
uint total = senderBurned.amount + amount;
// Check supplied new previous.
if (prev != address(0)) {
require (total <= accountBurned[prev].amount, "Total burned must be less than or equal to previous account.");
}
// Find correct previous. Search for first account that has burned less than sender.
address next = accountBurned[prev].next;
// accountBurned[0].amount == 0
while (total <= accountBurned[next].amount) {
prev = next;
next = accountBurned[prev].next;
}
bool replace = false;
// Is sender already in the list?
if (senderBurned.amount > 0) {
// Find correct old previous.
while (accountBurned[oldPrev].next != msg.sender) {
oldPrev = accountBurned[oldPrev].next;
require(oldPrev != address(0), "Old previous account incorrect.");
}
// Is it in the same position?
if (prev == oldPrev) {
replace = true;
}
else {
// Remove sender from current position.
accountBurned[oldPrev].next = senderBurned.next;
}
}
if (!replace) {
// Insert into linked list.
accountBurned[prev].next = msg.sender;
senderBurned.next = next;
}
// Update the amount.
senderBurned.amount = total;
}
/**
* @dev Record burning of tokens in linked list.
* @param token Address of token being burned.
* @param amount Amount of token being burned.
* @param prev Address of the entry preceeding the new entry.
* @param oldPrev Address of the entry preceeding the old entry.
*/
function _burnToken(MixTokenInterface token, uint amount, address prev, address oldPrev) internal {
// Get accountBurned mapping.
mapping (address => AccountBurnedLinked) storage accountBurned = tokenAccountBurned[address(token)];
// Update list of tokens burned by this account.
if (accountBurned[msg.sender].amount == 0) {
accountTokensBurnedList[msg.sender].push(token);
}
_accountBurnedInsert(accountBurned, amount, prev, oldPrev);
}
/**
* @dev Record burning of tokens for item in linked list.
* @param itemId Item having its token burned.
* @param amount Amount of token being burned.
* @param prev Address of the entry preceeding the new entry.
* @param oldPrev Address of the entry preceeding the old entry.
*/
function _burnItem(bytes32 itemId, uint amount, address prev, address oldPrev) internal {
// Get accountBurned mapping.
mapping (address => AccountBurnedLinked) storage accountBurned = itemAccountBurned[itemId];
// Update list of items burned by this account.
if (accountBurned[msg.sender].amount == 0) {
accountItemsBurnedList[msg.sender].push(itemId);
}
_accountBurnedInsert(accountBurned, amount, prev, oldPrev);
}
/**
* @dev Burn sender's tokens.
* @param token Address of the token's contract.
* @param amount Amount of tokens burned.
* @param prev Address of the entry preceeding the new entry.
* @param oldPrev Address of the entry preceeding the old entry.
*/
function burnToken(MixTokenInterface token, uint amount, address prev, address oldPrev) external nonZero(amount) {
// Transfer the tokens to this contract.
// Wrap with require () in case the token contract returns false on error instead of throwing.
require (token.transferFrom(msg.sender, address(this), amount), "Token transfer failed.");
// Record the tokens as burned.
_burnToken(token, amount, prev, oldPrev);
// Emit the event.
emit BurnToken(token, 0, msg.sender, amount);
}
/**
* @dev Burn sender's tokens for a specific item.
* @param itemId Item to burn this token for.
* @param amount Amount of tokens burned.
* @param tokenPrev Address of the entry preceeding the new entry in the tokenAccountBurned linked list.
* @param tokenOldPrev Address of the entry preceeding the old entry in the tokenAccountBurned linked list.
* @param itemPrev Address of the entry preceeding the new entry in the itemAccountBurned linked list.
* @param itemOldPrev Address of the entry preceeding the old entry in the itemAccountBurned linked list.
*/
function burnItem(bytes32 itemId, uint amount, address tokenPrev, address tokenOldPrev, address itemPrev, address itemOldPrev) external nonZero(amount) {
// Get token contract for item.
MixTokenInterface token = MixTokenInterface(address(getTokenToBurnItem(itemId)));
// Transfer the tokens to this contract.
// Wrap with require () in case the token contract returns false on error instead of throwing.
require (token.transferFrom(msg.sender, address(this), amount), "Token transfer failed.");
// Record the tokens as burned.
_burnToken(token, amount, tokenPrev, tokenOldPrev);
_burnItem(itemId, amount, itemPrev, itemOldPrev);
// Update total burned for this item.
itemBurnedTotal[itemId] += amount;
// Emit the event.
emit BurnToken(token, itemId, msg.sender, amount);
}
/**
* @dev Get the token that can be burned for an item.
* @param itemId itemId of the item.
* @return Token that can be burned for the item.
*/
function getTokenToBurnItem(bytes32 itemId) public view returns (MixTokenOwnedInterface token) {
token = itemTokenToBurn[itemId];
require (token != MixTokenOwnedInterface(0), "Item does not have a token to burn.");
}
/**
* @dev Get number of items that a token can be burned for.
* @param token Token to get the number of items that can be burned for.
* @return Number of items that the token can be burned for.
*/
function getItemsBurningTokenCount(MixTokenInterface token) external view returns (uint) {
return tokenToBurnItemsList[address(token)].length;
}
/**
* @dev Get list of items that a token can be burned for.
* @param token Token to check which items it can be burned tokens for.
* @param offset Offset to start results from.
* @param limit Maximum number of results to return. 0 for unlimited.
* @return itemIds List of itemIds for items token can be burned for.
* @return amounts Amount of tokens that was burned for each item.
*/
function getItemsBurningToken(MixTokenInterface token, uint offset, uint limit) external view returns (bytes32[] memory itemIds, uint[] memory amounts) {
// Get itemsBurningToken mapping.
bytes32[] storage itemsBurningToken = tokenToBurnItemsList[address(token)];
uint _limit = 0;
// Check if offset is beyond the end of the array.
if (offset < itemsBurningToken.length) {
// Check how many itemIds we can retrieve.
if (limit == 0 || offset + limit > itemsBurningToken.length) {
_limit = itemsBurningToken.length - offset;
}
else {
_limit = limit;
}
}
// Allocate memory arrays.
itemIds = new bytes32[](_limit);
amounts = new uint[](_limit);
// Populate memory array.
for (uint i = 0; i < _limit; i++) {
itemIds[i] = itemsBurningToken[offset + i];
amounts[i] = itemBurnedTotal[itemIds[i]];
}
}
/**
* @dev Get the amount of tokens an account has burned.
* @param account Address of the account.
* @param token Address of the token contract.
* @return Amount of these tokens that this account has burned.
*/
function getAccountTokenBurned(address account, MixTokenInterface token) external view returns (uint) {
return tokenAccountBurned[address(token)][account].amount;
}
/**
* @dev Get the amount of tokens an account has burned for an item.
* @param account Address of the account.
* @param itemId Item to get the amount of tokens account has burned for it.
* @return Amount of these tokens that this account has burned for the item.
*/
function getAccountItemBurned(address account, bytes32 itemId) external view returns (uint) {
return itemAccountBurned[itemId][account].amount;
}
/**
* @dev Get number of different tokens an account has burned.
* @param account Account to get the number of different tokens burned.
* @return Number of different tokens account has burned.
*/
function getAccountTokensBurnedCount(address account) external view returns (uint) {
return accountTokensBurnedList[account].length;
}
/**
* @dev Get list of tokens that an account has burned.
* @param account Account to get which tokens it has burned.
* @param offset Offset to start results from.
* @param limit Maximum number of results to return. 0 for unlimited.
* @return tokens List of tokens the account has burned.
* @return amounts Amount of each token that was burned by account.
*/
function getAccountTokensBurned(address account, uint offset, uint limit) external view returns (address[] memory tokens, uint[] memory amounts) {
// Get tokensBurned mapping.
MixTokenInterface[] storage tokensBurned = accountTokensBurnedList[account];
uint _limit = 0;
// Check if offset is beyond the end of the array.
if (offset < tokensBurned.length) {
// Check how many itemIds we can retrieve.
if (limit == 0 || offset + limit > tokensBurned.length) {
_limit = tokensBurned.length - offset;
}
else {
_limit = limit;
}
}
// Allocate memory arrays.
tokens = new address[](_limit);
amounts = new uint[](_limit);
// Populate memory arrays.
for (uint i = 0; i < _limit; i++) {
tokens[i] = address(tokensBurned[offset + i]);
amounts[i] = tokenAccountBurned[tokens[i]][account].amount;
}
}
/**
* @dev Get accounts that have burned.
* @param accountBurned Linked list of how much each account has burned.
* @param offset Offset to start results from.
* @param limit Maximum number of results to return.
* @return accounts List of accounts that burned the token.
* @return amounts Amount of token each account burned.
*/
function _getAccountsBurned(mapping (address => AccountBurnedLinked) storage accountBurned, uint offset, uint limit) internal view returns (address[] memory accounts, uint[] memory amounts) {
// Find the account at offset.
address account = accountBurned[address(0)].next;
uint i = 0;
while (account != (address(0)) && i++ < offset) {
account = accountBurned[account].next;
}
// Check how many accounts we can retrieve.
address _account = account;
uint _limit = 0;
while (_account != address(0) && _limit < limit) {
_account = accountBurned[_account].next;
_limit++;
}
// Allocate return variables.
accounts = new address[](_limit);
amounts = new uint[](_limit);
// Populate return variables.
i = 0;
while (i < _limit) {
accounts[i] = account;
amounts[i++] = accountBurned[account].amount;
account = accountBurned[account].next;
}
}
/**
* @dev Get accounts that have burned a token.
* @param token Token to get accounts that have burned it.
* @param offset Offset to start results from.
* @param limit Maximum number of results to return.
* @return accounts List of accounts that burned the token.
* @return amounts Amount of token each account burned.
*/
function getTokenAccountsBurned(MixTokenInterface token, uint offset, uint limit) external view returns (address[] memory accounts, uint[] memory amounts) {
// Get accountBurned mapping.
mapping (address => AccountBurnedLinked) storage accountBurned = tokenAccountBurned[address(token)];
// Get accounts and corresponding amounts.
(accounts, amounts) = _getAccountsBurned(accountBurned, offset, limit);
}
/**
* @dev Get number of items an account has burned tokens for.
* @param account Account to check.
* @return Number of items account has burned tokens for.
*/
function getAccountItemsBurnedCount(address account) external view returns (uint) {
return accountItemsBurnedList[account].length;
}
/**
* @dev Get list of items that an account has burned tokens for.
* @param account Account to check which items it has burned tokens for.
* @param offset Offset to start results from.
* @param limit Maximum number of results to return. 0 for unlimited.
* @return itemIds List of itemIds for items account has burned tokens for.
* @return amounts Amount of each token that was burned for each item by account.
*/
function getAccountItemsBurned(address account, uint offset, uint limit) external view returns (bytes32[] memory itemIds, uint[] memory amounts) {
// Get itemsBurned mapping.
bytes32[] storage itemsBurned = accountItemsBurnedList[account];
uint _limit = 0;
// Check if offset is beyond the end of the array.
if (offset < itemsBurned.length) {
// Check how many itemIds we can retrieve.
if (limit == 0 || offset + limit > itemsBurned.length) {
_limit = itemsBurned.length - offset;
}
else {
_limit = limit;
}
}
// Allocate memory arrays.
itemIds = new bytes32[](_limit);
amounts = new uint[](_limit);
// Populate memory array.
for (uint i = 0; i < _limit; i++) {
itemIds[i] = itemsBurned[offset + i];
amounts[i] = itemAccountBurned[itemIds[i]][account].amount;
}
}
/**
* @dev Get accounts that have burned tokens for an item.
* @param itemId Item to get accounts for.
* @param offset Offset to start results from.
* @param limit Maximum number of results to return.
* @return accounts List of accounts that burned tokens for the item.
* @return amounts Amount of token each account burned for the item.
*/
function getItemAccountsBurned(bytes32 itemId, uint offset, uint limit) external view returns (address[] memory accounts, uint[] memory amounts) {
// Get accountBurned mapping.
mapping (address => AccountBurnedLinked) storage accountBurned = itemAccountBurned[itemId];
// Get accounts and corresponding amounts.
(accounts, amounts) = _getAccountsBurned(accountBurned, offset, limit);
}
/**
* @dev Get total amount of tokens that were burned for an item.
* @param itemId Item to get amount of tokens burned for.
* @return Total amount of tokens that have been burned for the item.
*/
function getItemBurnedTotal(bytes32 itemId) external view returns (uint) {
return itemBurnedTotal[itemId];
}
}
|
Get the token that can be burned for an item. itemId itemId of the item. return Token that can be burned for the item./
|
function getTokenToBurnItem(bytes32 itemId) public view returns (MixTokenOwnedInterface token) {
token = itemTokenToBurn[itemId];
require (token != MixTokenOwnedInterface(0), "Item does not have a token to burn.");
}
| 5,447,935 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "./UniverseMarketplaceCore.sol";
import "./transfer-manager/UniverseTransferManager.sol";
import "./interfaces/IRoyaltiesProvider.sol";
contract UniverseMarketplaceTest is UniverseMarketplaceCore, UniverseTransferManager {
function __UniverseMarketplace_init(
uint daoFee,
address daoAddress,
IRoyaltiesProvider royaltiesProvider,
uint256 maxBundleSize,
uint256 maxBatchTransferSize
) external initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__TransferExecutor_init_unchained(maxBundleSize, maxBatchTransferSize);
__UniverseTransferManager_init_unchained(daoFee, daoAddress, royaltiesProvider);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "./lib/LibFill.sol";
import "./lib/LibOrder.sol";
import "./order-validator/OrderValidator.sol";
import "./asset-matcher/AssetMatcher.sol";
import "./transfer-executor/TransferExecutor.sol";
import "./interfaces/ITransferManager.sol";
import "./lib/LibTransfer.sol";
abstract contract UniverseMarketplaceCore is Initializable, OwnableUpgradeable, AssetMatcher, TransferExecutor, OrderValidator, ITransferManager {
using SafeMathUpgradeable for uint;
using LibTransfer for address;
uint256 private constant UINT256_MAX = 2 ** 256 - 1;
bool public protocolActivated;
//state of the orders
mapping(bytes32 => uint) public fills;
//events
event Cancel(bytes32 indexed hash, address indexed maker, LibAsset.AssetType makeAssetType, LibAsset.AssetType takeAssetType);
event Match(bytes32 indexed leftHash, bytes32 indexed rightHash, address indexed leftMaker, address rightMaker, uint newLeftFill, uint newRightFill, LibAsset.AssetType leftAsset, LibAsset.AssetType rightAsset);
modifier onlyActive {
require(protocolActivated, "Marketplace is not activated!");
_;
}
function toggleActiveStatus(bool status) external onlyOwner {
protocolActivated = status;
}
function cancel(LibOrder.Order memory order) external onlyActive {
require(_msgSender() == order.maker, "not a maker");
require(order.salt != 0, "0 salt can't be used");
bytes32 orderKeyHash = LibOrder.hashKey(order);
fills[orderKeyHash] = UINT256_MAX;
emit Cancel(orderKeyHash, order.maker, order.makeAsset.assetType, order.takeAsset.assetType);
}
function matchOrders(
LibOrder.Order memory orderLeft,
bytes memory signatureLeft,
LibOrder.Order memory orderRight,
bytes memory signatureRight
) external payable onlyActive {
validateFull(orderLeft, signatureLeft);
validateFull(orderRight, signatureRight);
if (orderLeft.taker != address(0)) {
require(orderRight.maker == orderLeft.taker, "leftOrder.taker verification failed");
}
if (orderRight.taker != address(0)) {
require(orderRight.taker == orderLeft.maker, "rightOrder.taker verification failed");
}
matchAndTransfer(orderLeft, orderRight);
}
function matchAndTransfer(LibOrder.Order memory orderLeft, LibOrder.Order memory orderRight) internal {
(LibAsset.AssetType memory makeMatch, LibAsset.AssetType memory takeMatch) = matchAssets(orderLeft, orderRight);
bytes32 leftOrderKeyHash = LibOrder.hashKey(orderLeft);
bytes32 rightOrderKeyHash = LibOrder.hashKey(orderRight);
uint leftOrderFill = getOrderFill(orderLeft, leftOrderKeyHash);
uint rightOrderFill = getOrderFill(orderRight, rightOrderKeyHash);
LibFill.FillResult memory newFill = LibFill.fillOrder(orderLeft, orderRight, leftOrderFill, rightOrderFill);
require(newFill.takeValue > 0, "nothing to fill");
if (orderLeft.salt != 0) {
fills[leftOrderKeyHash] = leftOrderFill.add(newFill.takeValue);
}
if (orderRight.salt != 0) {
fills[rightOrderKeyHash] = rightOrderFill.add(newFill.makeValue);
}
(uint totalMakeValue, uint totalTakeValue) = doTransfers(makeMatch, takeMatch, newFill, orderLeft, orderRight);
if (makeMatch.assetClass == LibAsset.ETH_ASSET_CLASS) {
require(takeMatch.assetClass != LibAsset.ETH_ASSET_CLASS);
require(msg.value >= totalMakeValue, "not enough eth");
if (msg.value > totalMakeValue) {
address(msg.sender).transferEth(msg.value.sub(totalMakeValue));
}
} else if (takeMatch.assetClass == LibAsset.ETH_ASSET_CLASS) {
require(msg.value >= totalTakeValue, "not enough eth");
if (msg.value > totalTakeValue) {
address(msg.sender).transferEth(msg.value.sub(totalTakeValue));
}
}
emit Match(leftOrderKeyHash, rightOrderKeyHash, orderLeft.maker, orderRight.maker, newFill.takeValue, newFill.makeValue, makeMatch, takeMatch);
}
function getOrderFill(LibOrder.Order memory order, bytes32 hash) internal view returns (uint fill) {
if (order.salt == 0) {
fill = 0;
} else {
fill = fills[hash];
}
}
function matchAssets(LibOrder.Order memory orderLeft, LibOrder.Order memory orderRight) internal view returns (LibAsset.AssetType memory makeMatch, LibAsset.AssetType memory takeMatch) {
makeMatch = matchAssets(orderLeft.makeAsset.assetType, orderRight.takeAsset.assetType);
require(makeMatch.assetClass != 0, "assets don't match");
takeMatch = matchAssets(orderLeft.takeAsset.assetType, orderRight.makeAsset.assetType);
require(takeMatch.assetClass != 0, "assets don't match");
}
function validateFull(LibOrder.Order memory order, bytes memory signature) internal view {
LibOrder.validate(order);
validate(order, signature);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "../lib/LibAsset.sol";
import "../interfaces/IRoyaltiesProvider.sol";
import "../lib/LibFill.sol";
import "../lib/LibFeeSide.sol";
import "../interfaces/ITransferManager.sol";
import "../interfaces/INftTransferProxy.sol";
import "../transfer-executor/TransferExecutor.sol";
import "../lib/LibOrderData.sol";
import "../lib/BpLibrary.sol";
import "../lib/LibERC721LazyMint.sol";
import "../lib/LibERC1155LazyMint.sol";
abstract contract UniverseTransferManager is OwnableUpgradeable, ITransferManager {
using BpLibrary for uint;
using SafeMathUpgradeable for uint;
uint public daoFee;
IRoyaltiesProvider public royaltiesRegistry;
address public defaultFeeReceiver;
mapping(address => address) public feeReceivers;
struct FeeCalculateInfo {
LibAsset.AssetType matchCalculate;
uint amount;
address from;
bytes4 transferDirection;
LibPart.Part[] revenueSplits;
LibAsset.AssetType matchNft;
uint matchNftValue;
}
function __UniverseTransferManager_init_unchained(
uint _daoFee,
address _daoAddress,
IRoyaltiesProvider _royaltiesRegistry
) internal initializer {
daoFee = _daoFee;
defaultFeeReceiver = _daoAddress;
royaltiesRegistry = _royaltiesRegistry;
}
function setRoyaltiesRegistry(IRoyaltiesProvider _royaltiesRegistry) external onlyOwner {
royaltiesRegistry = _royaltiesRegistry;
}
function setDaoFee(uint _daoFee) external onlyOwner {
daoFee = _daoFee;
}
function setDefaultFeeReceiver(address payable newDefaultFeeReceiver) external onlyOwner {
defaultFeeReceiver = newDefaultFeeReceiver;
}
function setFeeReceiver(address token, address wallet) external onlyOwner {
feeReceivers[token] = wallet;
}
function getFeeReceiver(address token) internal view returns (address) {
address wallet = feeReceivers[token];
if (wallet != address(0)) {
return wallet;
}
return defaultFeeReceiver;
}
function doTransfers(
LibAsset.AssetType memory makeMatch,
LibAsset.AssetType memory takeMatch,
LibFill.FillResult memory fill,
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder
) override internal returns (uint totalMakeValue, uint totalTakeValue) {
LibFeeSide.FeeSide feeSide = LibFeeSide.getFeeSide(makeMatch.assetClass, takeMatch.assetClass);
totalMakeValue = fill.makeValue;
totalTakeValue = fill.takeValue;
LibOrderData.Data memory leftOrderData = LibOrderData.parse(leftOrder);
LibOrderData.Data memory rightOrderData = LibOrderData.parse(rightOrder);
if (feeSide == LibFeeSide.FeeSide.MAKE) {
FeeCalculateInfo memory feeCalculateInfo = FeeCalculateInfo(makeMatch, totalMakeValue, leftOrder.maker, TO_TAKER, rightOrderData.revenueSplits, takeMatch, totalTakeValue);
uint totalFees = transferAllFees(feeCalculateInfo);
transfer(LibAsset.Asset(makeMatch, totalMakeValue.sub(totalFees)), leftOrder.maker, rightOrder.maker, PAYOUT, TO_TAKER);
transfer(LibAsset.Asset(takeMatch, totalTakeValue), rightOrder.maker, leftOrder.maker, PAYOUT, TO_MAKER);
} else if (feeSide == LibFeeSide.FeeSide.TAKE) {
FeeCalculateInfo memory feeCalculateInfo = FeeCalculateInfo(takeMatch, totalTakeValue, rightOrder.maker, TO_MAKER, leftOrderData.revenueSplits, makeMatch, totalMakeValue);
uint totalFees = transferAllFees(feeCalculateInfo);
transfer(LibAsset.Asset(takeMatch, totalTakeValue.sub(totalFees)), rightOrder.maker, leftOrder.maker, PAYOUT, TO_MAKER);
transfer(LibAsset.Asset(makeMatch, totalMakeValue), leftOrder.maker, rightOrder.maker, PAYOUT, TO_TAKER);
} else {
transfer(LibAsset.Asset(takeMatch, fill.takeValue), rightOrder.maker, leftOrder.maker, PAYOUT, TO_MAKER);
transfer(LibAsset.Asset(makeMatch, fill.makeValue), leftOrder.maker, rightOrder.maker, PAYOUT, TO_TAKER);
}
}
function transferAllFees(FeeCalculateInfo memory feeCalculateInfo) internal returns (uint allFeesValue) {
uint royaltiesValue = transferRoyaltyFees(feeCalculateInfo.matchCalculate, feeCalculateInfo.matchNft, feeCalculateInfo.matchNftValue, feeCalculateInfo.amount, feeCalculateInfo.from, feeCalculateInfo.transferDirection);
uint daoFeeValue = transferDaoFee(feeCalculateInfo.matchCalculate, feeCalculateInfo.amount.sub(royaltiesValue), feeCalculateInfo.from, feeCalculateInfo.transferDirection);
uint revenueSplitsValue = transferRevenueSplits(feeCalculateInfo.matchCalculate, feeCalculateInfo.amount.sub(royaltiesValue).sub(daoFeeValue), feeCalculateInfo.from, feeCalculateInfo.revenueSplits, feeCalculateInfo.transferDirection);
return royaltiesValue.add(daoFeeValue).add(revenueSplitsValue);
}
function transferDaoFee(
LibAsset.AssetType memory matchCalculate,
uint amount,
address from,
bytes4 transferDirection
) internal returns (uint) {
uint daoFeeValue = amount.bp(daoFee);
transfer(LibAsset.Asset(matchCalculate, daoFeeValue), from, defaultFeeReceiver, transferDirection, DAO);
return daoFeeValue;
}
function transferRevenueSplits(
LibAsset.AssetType memory matchCalculate,
uint amount,
address from,
LibPart.Part[] memory revenueSplits,
bytes4 transferDirection
) internal returns (uint) {
uint sumBps = 0;
uint restValue = amount;
for (uint256 i = 0; i < revenueSplits.length && i < 5; i++) {
uint currentAmount = amount.bp(revenueSplits[i].value);
sumBps = sumBps.add(revenueSplits[i].value);
if (currentAmount > 0) {
restValue = restValue.sub(currentAmount);
transfer(LibAsset.Asset(matchCalculate, currentAmount), from, revenueSplits[i].account, transferDirection, REVENUE_SPLIT);
}
}
return amount.sub(restValue);
}
function transferFees(
LibAsset.AssetType memory matchCalculate,
LibPart.Part[] memory fees,
uint amount,
address from,
bytes4 transferDirection
) internal returns (uint) {
uint totalFees = 0;
uint restValue = amount;
for (uint256 i = 0; i < fees.length && i < 5; i++) {
totalFees = totalFees.add(fees[i].value);
(uint newRestValue, uint feeValue) = subFeeInBp(restValue, amount, fees[i].value);
restValue = newRestValue;
if (feeValue > 0) {
transfer(LibAsset.Asset(matchCalculate, feeValue), from, fees[i].account, transferDirection, ROYALTY);
}
}
require(totalFees <= 5000, "Royalties are too high (>50%)");
return amount.sub(restValue);
}
function transferRoyaltyFees(
LibAsset.AssetType memory matchCalculate,
LibAsset.AssetType memory matchNft,
uint matchNftValue,
uint amount,
address from,
bytes4 transferDirection
) internal returns (uint) {
uint256 totalAmount = 0;
if (matchNft.assetClass == LibAsset.ERC1155_ASSET_CLASS || matchNft.assetClass == LibAsset.ERC721_ASSET_CLASS) {
(address token, uint tokenId) = abi.decode(matchNft.data, (address, uint));
(LibPart.Part[] memory fees, LibPart.Part[] memory collectionRoyalties) = royaltiesRegistry.getRoyalties(token, tokenId);
uint256 nftFees = transferFees(matchCalculate, fees, amount, from, transferDirection);
uint256 collectionFees = transferFees(matchCalculate, collectionRoyalties, amount - nftFees, from, transferDirection);
totalAmount = collectionFees + nftFees;
} else if (matchNft.assetClass == LibERC1155LazyMint.ERC1155_LAZY_ASSET_CLASS) {
(address token, LibERC1155LazyMint.Mint1155Data memory data) = abi.decode(matchNft.data, (address, LibERC1155LazyMint.Mint1155Data));
LibPart.Part[] memory fees = data.royalties;
totalAmount = transferFees(matchCalculate, fees, amount, from, transferDirection);
} else if (matchNft.assetClass == LibERC721LazyMint.ERC721_LAZY_ASSET_CLASS) {
(address token, LibERC721LazyMint.Mint721Data memory data) = abi.decode(matchNft.data, (address, LibERC721LazyMint.Mint721Data));
LibPart.Part[] memory fees = data.royalties;
totalAmount = transferFees(matchCalculate, fees, amount, from, transferDirection);
} else if (matchNft.assetClass == LibAsset.ERC721_BUNDLE_ASSET_CLASS) {
(INftTransferProxy.ERC721BundleItem[] memory erc721BundleItems) = abi.decode(matchNft.data, (INftTransferProxy.ERC721BundleItem[]));
for (uint256 i = 0; i < erc721BundleItems.length; i++) {
for (uint256 j = 0; j < erc721BundleItems[i].tokenIds.length; j++){
(LibPart.Part[] memory fees, LibPart.Part[] memory collectionRoyalties) = royaltiesRegistry.getRoyalties(erc721BundleItems[i].tokenAddress, erc721BundleItems[i].tokenIds[j]);
totalAmount = totalAmount.add(_transferRoyaltyRegistryFees(matchCalculate, matchNftValue, fees, collectionRoyalties, amount, from, transferDirection));
}
}
}
return totalAmount;
}
function _transferRoyaltyRegistryFees(
LibAsset.AssetType memory matchCalculate,
uint matchNftValue,
LibPart.Part[] memory nftRoyalties,
LibPart.Part[] memory collectionRoyalties,
uint amount,
address from,
bytes4 transferDirection
) internal returns (uint256 totalRoyaltiesFee) {
uint256 nftFees = transferFees(matchCalculate, nftRoyalties, amount.div(matchNftValue), from, transferDirection);
uint256 collectionFees = transferFees(matchCalculate, collectionRoyalties, amount.div(matchNftValue).sub(nftFees), from, transferDirection);
return totalRoyaltiesFee = collectionFees.add(nftFees);
}
function encodeOrderData(LibOrderData.Data memory data) external pure returns (bytes memory encodedOrderData) {
encodedOrderData = abi.encode(data);
}
function subFeeInBp(uint value, uint total, uint feeInBp) internal pure returns (uint newValue, uint realFee) {
return subFee(value, total.bp(feeInBp));
}
function subFee(uint value, uint fee) internal pure returns (uint newValue, uint realFee) {
if (value > fee) {
newValue = value.sub(fee);
realFee = fee;
} else {
newValue = 0;
realFee = value;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../lib/LibPart.sol";
interface IRoyaltiesProvider {
function getRoyalties(address token, uint tokenId) external returns (LibPart.Part[] memory, LibPart.Part[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "./LibOrder.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
library LibFill {
using SafeMathUpgradeable for uint;
struct FillResult {
uint makeValue;
uint takeValue;
}
/**
* @dev Should return filled values
* @param leftOrder left order
* @param rightOrder right order
* @param leftOrderFill current fill of the left order (0 if order is unfilled)
* @param rightOrderFill current fill of the right order (0 if order is unfilled)
*/
function fillOrder(LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint leftOrderFill, uint rightOrderFill) internal pure returns (FillResult memory) {
(uint leftMakeValue, uint leftTakeValue) = LibOrder.calculateRemaining(leftOrder, leftOrderFill);
(uint rightMakeValue, uint rightTakeValue) = LibOrder.calculateRemaining(rightOrder, rightOrderFill);
//We have 3 cases here:
if (rightTakeValue > leftMakeValue) { //1nd: left order should be fully filled
return fillLeft(leftMakeValue, leftTakeValue, rightOrder.makeAsset.value, rightOrder.takeAsset.value);
}//2st: right order should be fully filled or 3d: both should be fully filled if required values are the same
return fillRight(leftOrder.makeAsset.value, leftOrder.takeAsset.value, rightMakeValue, rightTakeValue);
}
function fillRight(uint leftMakeValue, uint leftTakeValue, uint rightMakeValue, uint rightTakeValue) internal pure returns (FillResult memory result) {
uint makerValue = LibMath.safeGetPartialAmountFloor(rightTakeValue, leftMakeValue, leftTakeValue);
require(makerValue <= rightMakeValue, "fillRight: unable to fill");
return FillResult(rightTakeValue, makerValue);
}
function fillLeft(uint leftMakeValue, uint leftTakeValue, uint rightMakeValue, uint rightTakeValue) internal pure returns (FillResult memory result) {
uint rightTake = LibMath.safeGetPartialAmountFloor(leftTakeValue, rightMakeValue, rightTakeValue);
require(rightTake <= leftMakeValue, "fillLeft: unable to fill");
return FillResult(leftMakeValue, leftTakeValue);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "./LibMath.sol";
import "./LibAsset.sol";
library LibOrder {
using SafeMathUpgradeable for uint;
bytes32 constant ORDER_TYPEHASH = keccak256(
"Order(address maker,Asset makeAsset,address taker,Asset takeAsset,uint256 salt,uint256 start,uint256 end,bytes4 dataType,bytes data)Asset(AssetType assetType,uint256 value)AssetType(bytes4 assetClass,bytes data)"
);
struct Order {
address maker;
LibAsset.Asset makeAsset;
address taker;
LibAsset.Asset takeAsset;
uint salt;
uint start;
uint end;
bytes4 dataType;
bytes data;
}
function calculateRemaining(Order memory order, uint fill) internal pure returns (uint makeValue, uint takeValue) {
takeValue = order.takeAsset.value.sub(fill);
makeValue = LibMath.safeGetPartialAmountFloor(order.makeAsset.value, order.takeAsset.value, takeValue);
}
function hashKey(Order memory order) internal pure returns (bytes32) {
return keccak256(abi.encode(
order.maker,
LibAsset.hash(order.makeAsset.assetType),
LibAsset.hash(order.takeAsset.assetType),
order.salt
));
}
function hash(Order memory order) internal pure returns (bytes32) {
return keccak256(abi.encode(
ORDER_TYPEHASH,
order.maker,
LibAsset.hash(order.makeAsset),
order.taker,
LibAsset.hash(order.takeAsset),
order.salt,
order.start,
order.end,
order.dataType,
keccak256(order.data)
));
}
function validate(LibOrder.Order memory order) internal view {
require(order.start == 0 || order.start < block.timestamp, "Order start validation failed");
require(order.end == 0 || order.end > block.timestamp, "Order end validation failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../interfaces/ERC1271.sol";
import "../lib/LibOrder.sol";
import "../cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/SignatureCheckerUpgradeable.sol";
abstract contract OrderValidator is Initializable, ContextUpgradeable, EIP712 {
using AddressUpgradeable for address;
function validate(LibOrder.Order memory order, bytes memory signature) internal view {
if (order.salt == 0) {
if (order.maker != address(0)) {
require(_msgSender() == order.maker, "maker is not tx sender");
} else {
order.maker = _msgSender();
}
} else {
if (_msgSender() != order.maker) {
bytes32 hash = LibOrder.hash(order);
require(SignatureCheckerUpgradeable.isValidSignatureNow(order.maker, _hashTypedDataV4(hash), signature), "order signature verification error");
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../interfaces/IAssetMatcher.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
abstract contract AssetMatcher is Initializable, OwnableUpgradeable {
bytes constant EMPTY = "";
mapping(bytes4 => address) matchers;
event MatcherChange(bytes4 indexed assetType, address matcher);
function setAssetMatcher(bytes4 assetType, address matcher) external onlyOwner {
matchers[assetType] = matcher;
emit MatcherChange(assetType, matcher);
}
function matchAssets(LibAsset.AssetType memory leftAssetType, LibAsset.AssetType memory rightAssetType) internal view returns (LibAsset.AssetType memory) {
LibAsset.AssetType memory result = matchAssetOneSide(leftAssetType, rightAssetType);
if (result.assetClass == 0) {
return matchAssetOneSide(rightAssetType, leftAssetType);
} else {
return result;
}
}
function matchAssetOneSide(LibAsset.AssetType memory leftAssetType, LibAsset.AssetType memory rightAssetType) private view returns (LibAsset.AssetType memory) {
bytes4 classLeft = leftAssetType.assetClass;
bytes4 classRight = rightAssetType.assetClass;
if (classLeft == LibAsset.ETH_ASSET_CLASS) {
if (classRight == LibAsset.ETH_ASSET_CLASS) {
return leftAssetType;
}
return LibAsset.AssetType(0, EMPTY);
}
if (classLeft == LibAsset.ERC20_ASSET_CLASS) {
if (classRight == LibAsset.ERC20_ASSET_CLASS) {
return simpleMatch(leftAssetType, rightAssetType);
}
return LibAsset.AssetType(0, EMPTY);
}
if (classLeft == LibAsset.ERC721_ASSET_CLASS) {
if (classRight == LibAsset.ERC721_ASSET_CLASS) {
return simpleMatch(leftAssetType, rightAssetType);
}
return LibAsset.AssetType(0, EMPTY);
}
if (classLeft == LibAsset.ERC1155_ASSET_CLASS) {
if (classRight == LibAsset.ERC1155_ASSET_CLASS) {
return simpleMatch(leftAssetType, rightAssetType);
}
return LibAsset.AssetType(0, EMPTY);
}
if (classLeft == LibAsset.ERC721_BUNDLE_ASSET_CLASS) {
if (classRight == LibAsset.ERC721_BUNDLE_ASSET_CLASS) {
return simpleMatch(leftAssetType, rightAssetType);
}
return LibAsset.AssetType(0, EMPTY);
}
address matcher = matchers[classLeft];
if (matcher != address(0)) {
return IAssetMatcher(matcher).matchAssets(leftAssetType, rightAssetType);
}
if (classLeft == classRight) {
return simpleMatch(leftAssetType, rightAssetType);
}
revert("not found IAssetMatcher");
}
function simpleMatch(LibAsset.AssetType memory leftAssetType, LibAsset.AssetType memory rightAssetType) private pure returns (LibAsset.AssetType memory) {
bytes32 leftHash = keccak256(leftAssetType.data);
bytes32 rightHash = keccak256(rightAssetType.data);
if (leftHash == rightHash) {
return leftAssetType;
}
return LibAsset.AssetType(0, EMPTY);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../lib/LibAsset.sol";
import "../lib/LibTransfer.sol";
import "../interfaces/ITransferProxy.sol";
import "../interfaces/ITransferExecutor.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
abstract contract TransferExecutor is Initializable, OwnableUpgradeable, ITransferExecutor {
using LibTransfer for address;
mapping (bytes4 => address) proxies;
uint256 public maxBundleSize;
uint256 public maxBatchTransferSize;
event ProxyChange(bytes4 indexed assetType, address proxy);
function __TransferExecutor_init_unchained(uint256 _maxBundleSize, uint256 _maxBatchTransferSize) internal {
maxBundleSize = _maxBundleSize;
maxBatchTransferSize = _maxBatchTransferSize;
}
function setTransferProxy(bytes4 assetType, address proxy) external onlyOwner {
proxies[assetType] = proxy;
emit ProxyChange(assetType, proxy);
}
function setMaxBundleSize(uint256 _maxBundleSize) external onlyOwner {
require(_maxBundleSize > 0, "Bundle size should be > 0");
maxBundleSize = _maxBundleSize;
}
function setMaxBatchTransferSize(uint256 _maxBatchTransferSize) external onlyOwner {
require(_maxBatchTransferSize > 0, "Batch size should be > 0");
maxBatchTransferSize = _maxBatchTransferSize;
}
function erc721BatchTransfer(ERC721Item[] calldata erc721Items, address to) override external {
require(erc721Items.length <= maxBatchTransferSize, "Cannot transfer more than configured");
for (uint256 i = 0; i < erc721Items.length; i++) {
IERC721Upgradeable(erc721Items[i].tokenAddress).safeTransferFrom(msg.sender, to, erc721Items[i].tokenId);
}
}
function transfer(
LibAsset.Asset memory asset,
address from,
address to,
bytes4 transferDirection,
bytes4 transferType
) internal override {
if (asset.assetType.assetClass == LibAsset.ETH_ASSET_CLASS) {
to.transferEth(asset.value);
} else if (asset.assetType.assetClass == LibAsset.ERC20_ASSET_CLASS) {
(address token) = abi.decode(asset.assetType.data, (address));
SafeERC20Upgradeable.safeTransferFrom(IERC20Upgradeable(token), from, to, asset.value);
} else if (asset.assetType.assetClass == LibAsset.ERC721_ASSET_CLASS) {
(address token, uint tokenId) = abi.decode(asset.assetType.data, (address, uint256));
require(asset.value == 1, "erc721 value error");
IERC721Upgradeable(token).safeTransferFrom( from, to, tokenId);
} else if (asset.assetType.assetClass == LibAsset.ERC1155_ASSET_CLASS) {
(address token, uint tokenId) = abi.decode(asset.assetType.data, (address, uint256));
IERC1155Upgradeable(token).safeTransferFrom(from, to, tokenId, asset.value, "");
} else if (asset.assetType.assetClass == LibAsset.ERC721_BUNDLE_ASSET_CLASS) {
(ERC721BundleItem[] memory erc721BundleItems) = abi.decode(asset.assetType.data, (ERC721BundleItem[]));
require(asset.value > 1 && asset.value <= maxBundleSize, "erc721 value error");
for (uint256 i = 0; i < erc721BundleItems.length; i++) {
for (uint256 j = 0; j < erc721BundleItems[i].tokenIds.length; j++){
IERC721Upgradeable(erc721BundleItems[i].tokenAddress).safeTransferFrom(from, to, erc721BundleItems[i].tokenIds[j]);
}
}
} else {
ITransferProxy(proxies[asset.assetType.assetClass]).transfer(asset, from, to);
}
emit Transfer(asset, from, to, transferDirection, transferType);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../lib/LibAsset.sol";
import "../lib/LibFill.sol";
import "../transfer-executor/TransferExecutor.sol";
abstract contract ITransferManager is ITransferExecutor {
bytes4 constant TO_MAKER = bytes4(keccak256("TO_MAKER"));
bytes4 constant TO_TAKER = bytes4(keccak256("TO_TAKER"));
bytes4 constant PROTOCOL = bytes4(keccak256("PROTOCOL"));
bytes4 constant ROYALTY = bytes4(keccak256("ROYALTY"));
bytes4 constant ORIGIN = bytes4(keccak256("ORIGIN"));
bytes4 constant PAYOUT = bytes4(keccak256("PAYOUT"));
bytes4 constant DAO = bytes4(keccak256("DAO"));
bytes4 constant REVENUE_SPLIT = bytes4(keccak256("REVENUE_SPLIT"));
function doTransfers(
LibAsset.AssetType memory makeMatch,
LibAsset.AssetType memory takeMatch,
LibFill.FillResult memory fill,
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder
) internal virtual returns (uint totalMakeValue, uint totalTakeValue);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
library LibTransfer {
function transferEth(address to, uint value) internal {
(bool success,) = to.call{ value: value }("");
require(success, "transfer failed");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
library LibMath {
using SafeMathUpgradeable for uint;
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return partialAmount value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
) internal pure returns (uint256 partialAmount) {
if (isRoundingErrorFloor(numerator, denominator, target)) {
revert("rounding error");
}
partialAmount = numerator.mul(target).div(denominator);
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return isError Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
) internal pure returns (bool isError) {
if (denominator == 0) {
revert("division by zero");
}
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * target) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = remainder.mul(1000) >= numerator.mul(target);
}
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
) internal pure returns (uint256 partialAmount) {
if (isRoundingErrorCeil(numerator, denominator, target)) {
revert("rounding error");
}
partialAmount = numerator.mul(target).add(denominator.sub(1)).div(denominator);
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return isError Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
) internal pure returns (bool isError) {
if (denominator == 0) {
revert("division by zero");
}
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.sub(remainder) % denominator;
isError = remainder.mul(1000) >= numerator.mul(target);
return isError;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
library LibAsset {
bytes4 constant public ETH_ASSET_CLASS = bytes4(keccak256("ETH"));
bytes4 constant public ERC20_ASSET_CLASS = bytes4(keccak256("ERC20"));
bytes4 constant public ERC721_ASSET_CLASS = bytes4(keccak256("ERC721"));
bytes4 constant public ERC1155_ASSET_CLASS = bytes4(keccak256("ERC1155"));
bytes4 constant public ERC721_BUNDLE_ASSET_CLASS = bytes4(keccak256("ERC721_BUNDLE"));
bytes4 constant public ERC721_LAZY_ASSET_CLASS = bytes4(keccak256("ERC721_LAZY"));
bytes32 constant ASSET_TYPE_TYPEHASH = keccak256(
"AssetType(bytes4 assetClass,bytes data)"
);
bytes32 constant ASSET_TYPEHASH = keccak256(
"Asset(AssetType assetType,uint256 value)AssetType(bytes4 assetClass,bytes data)"
);
struct AssetType {
bytes4 assetClass;
bytes data;
}
struct Asset {
AssetType assetType;
uint value;
}
function hash(AssetType memory assetType) internal pure returns (bytes32) {
return keccak256(abi.encode(
ASSET_TYPE_TYPEHASH,
assetType.assetClass,
keccak256(assetType.data)
));
}
function hash(Asset memory asset) internal pure returns (bytes32) {
return keccak256(abi.encode(
ASSET_TYPEHASH,
hash(asset.assetType),
asset.value
));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface ERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param _hash Hash of the data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
*
* MUST return the bytes4 magic value 0x1626ba7e when function passes.
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes32 _hash, bytes calldata _signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/draft-EIP712.sol)
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private constant _HASHED_NAME = keccak256("Exchange");
bytes32 private constant _HASHED_VERSION = keccak256("2");
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library 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);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal 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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../AddressUpgradeable.sol";
import "../../interfaces/IERC1271Upgradeable.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureCheckerUpgradeable {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSAUpgradeable.RecoverError error) = ECDSAUpgradeable.tryRecover(hash, signature);
if (error == ECDSAUpgradeable.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271Upgradeable.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271Upgradeable.isValidSignature.selector);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// 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.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since 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.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271Upgradeable {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../lib/LibAsset.sol";
interface IAssetMatcher {
function matchAssets(
LibAsset.AssetType memory leftAssetType,
LibAsset.AssetType memory rightAssetType
) external view returns (LibAsset.AssetType memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../lib/LibAsset.sol";
interface ITransferProxy {
function transfer(LibAsset.Asset calldata asset, address from, address to) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../lib/LibAsset.sol";
abstract contract ITransferExecutor {
struct ERC721BundleItem {
address tokenAddress;
uint256[] tokenIds;
}
struct ERC721Item {
address tokenAddress;
uint256 tokenId;
}
//events
event Transfer(LibAsset.Asset asset, address from, address to, bytes4 transferDirection, bytes4 transferType);
function erc721BatchTransfer(ERC721Item[] calldata erc721Items, address to) external virtual;
function transfer(
LibAsset.Asset memory asset,
address from,
address to,
bytes4 transferDirection,
bytes4 transferType
) internal virtual;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using 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");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "./LibAsset.sol";
library LibFeeSide {
enum FeeSide {NONE, MAKE, TAKE}
function getFeeSide(bytes4 make, bytes4 take) internal pure returns (FeeSide) {
if (make == LibAsset.ETH_ASSET_CLASS) {
return FeeSide.MAKE;
}
if (take == LibAsset.ETH_ASSET_CLASS) {
return FeeSide.TAKE;
}
if (make == LibAsset.ERC20_ASSET_CLASS) {
return FeeSide.MAKE;
}
if (take == LibAsset.ERC20_ASSET_CLASS) {
return FeeSide.TAKE;
}
if (make == LibAsset.ERC1155_ASSET_CLASS) {
return FeeSide.MAKE;
}
if (take == LibAsset.ERC1155_ASSET_CLASS) {
return FeeSide.TAKE;
}
return FeeSide.NONE;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
interface INftTransferProxy {
struct ERC721BundleItem {
address tokenAddress;
uint256[] tokenIds;
}
struct ERC721Item {
address tokenAddress;
uint256 tokenId;
}
function erc721safeTransferFrom(IERC721Upgradeable token, address from, address to, uint256 tokenId) external;
function erc1155safeTransferFrom(IERC1155Upgradeable token, address from, address to, uint256 id, uint256 value, bytes calldata data) external;
function erc721BundleSafeTransferFrom(ERC721BundleItem[] calldata erc721BundleItems, address from, address to) external;
function erc721BatchTransfer(ERC721Item[] calldata erc721Items, address to) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "./LibPart.sol";
import "./LibOrder.sol";
library LibOrderData {
bytes4 constant public ORDER_DATA = bytes4(keccak256("ORDER_DATA"));
struct Data {
LibPart.Part[] revenueSplits;
}
function decodeOrderData(bytes memory data) internal pure returns (Data memory orderData) {
orderData = abi.decode(data, (Data));
}
function parse(LibOrder.Order memory order) pure internal returns (LibOrderData.Data memory dataOrder) {
if (order.dataType == ORDER_DATA) {
dataOrder = decodeOrderData(order.data);
} else {
LibOrderData.Data memory _dataOrder;
dataOrder = _dataOrder;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
library BpLibrary {
using SafeMathUpgradeable for uint;
function bp(uint value, uint bpValue) internal pure returns (uint) {
return value.mul(bpValue).div(10000);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "./LibPart.sol";
library LibERC721LazyMint {
bytes4 constant public ERC721_LAZY_ASSET_CLASS = bytes4(keccak256("ERC721_LAZY"));
bytes4 constant _INTERFACE_ID_MINT_AND_TRANSFER = 0x8486f69f;
struct Mint721Data {
string tokenURI;
LibPart.Part[] royalties;
}
bytes32 public constant MINT_AND_TRANSFER_TYPEHASH = keccak256("Mint721(string tokenURI,Part[] royalties)Part(address account,uint96 value)");
function hash(Mint721Data memory data) internal pure returns (bytes32) {
bytes32[] memory royaltiesBytes = new bytes32[](data.royalties.length);
for (uint i = 0; i < data.royalties.length; i++) {
royaltiesBytes[i] = LibPart.hash(data.royalties[i]);
}
return keccak256(abi.encode(
MINT_AND_TRANSFER_TYPEHASH,
keccak256(bytes(data.tokenURI)),
keccak256(abi.encodePacked(royaltiesBytes))
));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "./LibPart.sol";
library LibERC1155LazyMint {
bytes4 constant public ERC1155_LAZY_ASSET_CLASS = bytes4(keccak256("ERC1155_LAZY"));
bytes4 constant _INTERFACE_ID_MINT_AND_TRANSFER = 0x6db15a0f;
struct Mint1155Data {
uint tokenId;
string tokenURI;
uint supply;
LibPart.Part[] creators;
LibPart.Part[] royalties;
bytes[] signatures;
}
bytes32 public constant MINT_AND_TRANSFER_TYPEHASH = keccak256("Mint1155(uint256 tokenId,uint256 supply,string tokenURI,Part[] creators,Part[] royalties)Part(address account,uint96 value)");
function hash(Mint1155Data memory data) internal pure returns (bytes32) {
bytes32[] memory royaltiesBytes = new bytes32[](data.royalties.length);
for (uint i = 0; i < data.royalties.length; i++) {
royaltiesBytes[i] = LibPart.hash(data.royalties[i]);
}
bytes32[] memory creatorsBytes = new bytes32[](data.creators.length);
for (uint i = 0; i < data.creators.length; i++) {
creatorsBytes[i] = LibPart.hash(data.creators[i]);
}
return keccak256(abi.encode(
MINT_AND_TRANSFER_TYPEHASH,
data.tokenId,
data.supply,
keccak256(bytes(data.tokenURI)),
keccak256(abi.encodePacked(creatorsBytes)),
keccak256(abi.encodePacked(royaltiesBytes))
));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
|
Required interface of an ERC1155 compliant contract, as defined in the _Available since v3.1._/
|
interface IERC1155Upgradeable is IERC165Upgradeable {
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
event URI(string value, uint256 indexed id);
function balanceOf(address account, uint256 id) external view returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
}
| 153,680 |
./partial_match/56/0xEca7fC4c554086198dEEbCaff6C90D368dC327e0/sources/CommunityFund.sol
|
addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline)
|
function _addLiquidity2(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired
) internal {
IERC20(_tokenA).safeIncreaseAllowance(address(pancakeRouter), _amountADesired);
IERC20(_tokenB).safeIncreaseAllowance(address(pancakeRouter), _amountBDesired);
pancakeRouter.addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired, 0, 0, address(this), now.add(1800));
}
| 11,077,593 |
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20.sol";
contract virgoContract {
using SafeMath for uint256;
mapping(address => uint256) public balanceUserETH;
mapping(address => uint256) public balanceUserBTC;
mapping(address => uint256) public balanceUserUNI;
mapping(address => uint256) public balanceUserLINK;
function deposit_ETH(uint256 amount) public payable returns (uint) {
require(msg.value == amount * uint256(10) ** 18);
// adjust the account's balance
balanceUserETH[msg.sender] = balanceUserETH[msg.sender].add(amount * uint256(10) ** 18);
return balanceUserETH[msg.sender];
}
// note balanceContract for other tokens incl. BTC, UNI and LINK is future enhancement
function balanceContractETH() public view returns (uint256) {
return address(this).balance;
}
// updating user balances across ETH, UNI, LINK and BTC
function updateUserBalance(address buyer, string memory symbol,
uint256 amount, string memory incDec) public returns (uint256) {
if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("BTC")))) {
if (keccak256(abi.encodePacked((incDec))) == keccak256(abi.encodePacked(("inc")))) {
return balanceUserBTC[buyer] = balanceUserBTC[buyer].add(amount);
}
else {
return balanceUserBTC[buyer] = balanceUserBTC[buyer].sub(amount);
}
}
else if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("UNI")))) {
if (keccak256(abi.encodePacked((incDec))) == keccak256(abi.encodePacked(("inc")))) {
return balanceUserUNI[buyer] = balanceUserUNI[buyer].add(amount);
}
else {
return balanceUserUNI[buyer] = balanceUserUNI[buyer].sub(amount);
}
}
else if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("LINK")))) {
if (keccak256(abi.encodePacked((incDec))) == keccak256(abi.encodePacked(("inc")))) {
return balanceUserLINK[buyer] = balanceUserLINK[buyer].add(amount);
}
else {
return balanceUserLINK[buyer] = balanceUserLINK[buyer].sub(amount);
}
}
else if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("ETH")))) {
if (keccak256(abi.encodePacked((incDec))) == keccak256(abi.encodePacked(("inc")))) {
return balanceUserETH[buyer] = balanceUserETH[buyer].add(amount);
}
else {
return balanceUserETH[buyer] = balanceUserETH[buyer].sub(amount);
}
}
else {} // error catching
}
// function used by buyToken & loanRequest to test sufficient token balance for purchase/collateral
function getUserBalance(address user, string memory symbol) public view returns (uint256) {
if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("BTC")))) {
return balanceUserBTC[user];
}
else if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("UNI")))) {
return balanceUserUNI[user];
}
else if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("LINK")))) {
return balanceUserLINK[user];
}
else if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("ETH")))) {
return balanceUserETH[user];
}
else {} // error catching
}
// fallback function
function () external payable {
}
}
// UNUSED CODE
// Token BTCtoken = 0x4663FAFe32Ac27aeB1e4bac9b73a1b12E587Dd3B;
// Token UNItoken = 0x145d5423e9f5194e11138DE68939e46B21374487;
// Token LINKtoken = 0xBBC14d5aA1005A3E9526bda86F458143A7a01309;
// balances, indexed by addresses
// function balanceContractBTC() public view returns (uint256) {
// return BTCtoken.balanceOf(address(this));
// }
// function balanceContractUNI() public view returns (uint256) {
// return UNItoken.balanceOf(address(this));
// }
// function balanceContractLINK() public view returns (uint256) {
// return LINKtoken.balanceOf(address(this));
// }
|
updating user balances across ETH, UNI, LINK and BTC
|
function updateUserBalance(address buyer, string memory symbol,
uint256 amount, string memory incDec) public returns (uint256) {
if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("BTC")))) {
if (keccak256(abi.encodePacked((incDec))) == keccak256(abi.encodePacked(("inc")))) {
return balanceUserBTC[buyer] = balanceUserBTC[buyer].add(amount);
}
else {
return balanceUserBTC[buyer] = balanceUserBTC[buyer].sub(amount);
}
}
else if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("UNI")))) {
if (keccak256(abi.encodePacked((incDec))) == keccak256(abi.encodePacked(("inc")))) {
return balanceUserUNI[buyer] = balanceUserUNI[buyer].add(amount);
}
else {
return balanceUserUNI[buyer] = balanceUserUNI[buyer].sub(amount);
}
}
else if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("LINK")))) {
if (keccak256(abi.encodePacked((incDec))) == keccak256(abi.encodePacked(("inc")))) {
return balanceUserLINK[buyer] = balanceUserLINK[buyer].add(amount);
}
else {
return balanceUserLINK[buyer] = balanceUserLINK[buyer].sub(amount);
}
}
else if (keccak256(abi.encodePacked((symbol))) == keccak256(abi.encodePacked(("ETH")))) {
if (keccak256(abi.encodePacked((incDec))) == keccak256(abi.encodePacked(("inc")))) {
return balanceUserETH[buyer] = balanceUserETH[buyer].add(amount);
}
else {
return balanceUserETH[buyer] = balanceUserETH[buyer].sub(amount);
}
}
}
| 12,581,966 |
./full_match/84531/0xB720dE9a16F4Df1AAC27Ea85E55758233d54320C/sources/contracts/lib/Bytecode.sol
|
/ allocate output byte array - this could also be done without assembly by using o_code = new bytes(size) new "memory end" including padding store length in memory actually retrieve the code, this needs assembly
|
function codeAt(address _addr, uint256 _start, uint256 _end) internal view returns (bytes memory oCode) {
uint256 csize = codeSize(_addr);
if (csize == 0) return bytes("");
if (_start > csize) return bytes("");
if (_end < _start) revert InvalidCodeAtRange(csize, _start, _end);
unchecked {
uint256 reqSize = _end - _start;
uint256 maxSize = csize - _start;
uint256 size = maxSize < reqSize ? maxSize : reqSize;
assembly {
oCode := mload(0x40)
mstore(0x40, add(oCode, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(oCode, size)
extcodecopy(_addr, add(oCode, 0x20), _start, size)
}
}
}
| 14,305,950 |
./full_match/42/0x4A23049F8361d0B14f052A4C3a7212aa902099Ff/sources/ERC1155AuctionHouse.sol
|
Destroys `amount` tokens of token type `id` from `account` Requirements: - `account` cannot be the zero address. - `account` must have at least `amount` tokens of token type `id`./
|
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
require(_balances[id][account] >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] -= amount;
emit TransferSingle(operator, account, address(0), id, amount);
}
| 16,203,131 |
pragma solidity ^0.6.11;
/*
A gauge to allow users to commit to Stacker.vc fund 1. This will reward STACK tokens for hard and soft commits, as well as link with a ibETH gateway, to allow users
to deposit ETH directly into the fund.
ibETH is sent to the STACK DAO governance contract, for future VC fund initialization.
*/
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/**
* @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);
}
}
}
}
/**
* @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");
}
}
}
/**
* @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;
}
}
contract GaugeD1 is ReentrancyGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address payable public governance = 0xB156d2D9CAdB12a252A9015078fc5cb7E92e656e; // STACK DAO Agent address
address public constant acceptToken = 0xeEa3311250FE4c3268F8E684f7C87A82fF183Ec1; // AlphaHomora ibETHv2
address public vaultGaugeBridge; // the bridge address to allow people one transaction to do: (token <-> alphaHomora <-> commit)
address public constant STACK = 0xe0955F26515d22E347B17669993FCeFcc73c3a0a; // STACK DAO Token
uint256 public emissionRate = 127797160347097087; // 50k STACK total, div by delta block
uint256 public depositedCommitSoft;
uint256 public depositedCommitHard;
uint256 public constant commitSoftWeight = 1;
uint256 public constant commitHardWeight = 4;
struct CommitState {
uint256 balanceCommitSoft;
uint256 balanceCommitHard;
uint256 tokensAccrued;
}
mapping(address => CommitState) public balances; // balance of acceptToken by user by commit
event Deposit(address indexed from, uint256 amountCommitSoft, uint256 amountCommitHard);
event Withdraw(address indexed to, uint256 amount);
event Upgrade(address indexed user, uint256 amount);
event STACKClaimed(address indexed to, uint256 amount);
bool public fundOpen = true;
uint256 public constant startBlock = 11955015;
uint256 public endBlock = startBlock + 391245;
uint256 public lastBlock; // last block the distribution has ran
uint256 public tokensAccrued; // tokens to distribute per weight scaled by 1e18
constructor(address _vaultGaugeBridge) public {
vaultGaugeBridge = _vaultGaugeBridge;
}
function setGovernance(address payable _new) external {
require(msg.sender == governance, "GAUGE: !governance");
governance = _new;
}
function setEmissionRate(uint256 _new) external {
require(msg.sender == governance, "GAUGE: !governance");
_kick(); // catch up the contract to the current block for old rate
emissionRate = _new;
}
function setEndBlock(uint256 _block) external {
require(msg.sender == governance, "GAUGE: !governance");
require(block.number <= endBlock, "GAUGE: distribution already done, must start another");
require(block.number <= _block, "GAUGE: can't set endBlock to past block");
endBlock = _block;
}
function setFundOpen(bool _open) external {
require(msg.sender == governance, "GAUGE: !governance");
fundOpen = _open;
}
function deposit(uint256 _amountCommitSoft, uint256 _amountCommitHard, address _creditTo) nonReentrant external {
require(block.number <= endBlock, "GAUGE: distribution 1 over");
require(fundOpen || _amountCommitHard == 0, "GAUGE: !fundOpen, only soft commit allowed"); // when the fund closes, soft commits are still accepted
require(msg.sender == _creditTo || msg.sender == vaultGaugeBridge, "GAUGE: !bridge for creditTo"); // only the bridge contract can use the "creditTo" to credit !msg.sender
_claimSTACK(_creditTo); // new deposit doesn't get tokens right away
// transfer tokens from sender to account
uint256 _acceptTokenAmount = _amountCommitSoft.add(_amountCommitHard);
require(_acceptTokenAmount > 0, "GAUGE: !tokens");
IERC20(acceptToken).safeTransferFrom(msg.sender, address(this), _acceptTokenAmount);
CommitState memory _state = balances[_creditTo];
// no need to update _state.tokensAccrued because that's already done in _claimSTACK
if (_amountCommitSoft > 0){
_state.balanceCommitSoft = _state.balanceCommitSoft.add(_amountCommitSoft);
depositedCommitSoft = depositedCommitSoft.add(_amountCommitSoft);
}
if (_amountCommitHard > 0){
_state.balanceCommitHard = _state.balanceCommitHard.add(_amountCommitHard);
depositedCommitHard = depositedCommitHard.add(_amountCommitHard);
IERC20(acceptToken).safeTransfer(governance, _amountCommitHard); // transfer out any hard commits right away
}
emit Deposit(_creditTo, _amountCommitSoft, _amountCommitHard);
balances[_creditTo] = _state;
}
function upgradeCommit(uint256 _amount) nonReentrant external {
// upgrading from soft -> hard commit
require(block.number <= endBlock, "GAUGE: distribution 1 over");
require(fundOpen, "GAUGE: !fundOpen"); // soft commits cannot be upgraded after the fund closes. they can be deposited though
_claimSTACK(msg.sender);
CommitState memory _state = balances[msg.sender];
require(_amount <= _state.balanceCommitSoft, "GAUGE: insufficient balance softCommit");
_state.balanceCommitSoft = _state.balanceCommitSoft.sub(_amount);
_state.balanceCommitHard = _state.balanceCommitHard.add(_amount);
depositedCommitSoft = depositedCommitSoft.sub(_amount);
depositedCommitHard = depositedCommitHard.add(_amount);
IERC20(acceptToken).safeTransfer(governance, _amount);
emit Upgrade(msg.sender, _amount);
balances[msg.sender] = _state;
}
// withdraw funds that haven't been committed to VC fund (fund in commitSoft before deadline)
function withdraw(uint256 _amount, address _withdrawFor) nonReentrant external {
require(block.number <= endBlock, ">endblock");
require(msg.sender == _withdrawFor || msg.sender == vaultGaugeBridge, "GAUGE: !bridge for withdrawFor"); // only the bridge contract can use the "withdrawFor" to withdraw for !msg.sender
_claimSTACK(_withdrawFor); // claim tokens from all blocks including this block on withdraw
CommitState memory _state = balances[_withdrawFor];
require(_amount <= _state.balanceCommitSoft, "GAUGE: insufficient balance softCommit");
// update globals & add amtToWithdraw to final tally.
_state.balanceCommitSoft = _state.balanceCommitSoft.sub(_amount);
depositedCommitSoft = depositedCommitSoft.sub(_amount);
emit Withdraw(_withdrawFor, _amount);
balances[_withdrawFor] = _state;
// IMPORTANT: send tokens to msg.sender, not _withdrawFor. This will send to msg.sender OR vaultGaugeBridge (see second require() ).
// the bridge contract will then forward these tokens to the sender (after withdrawing from yield farm)
IERC20(acceptToken).safeTransfer(msg.sender, _amount);
}
function claimSTACK() nonReentrant external returns (uint256) {
return _claimSTACK(msg.sender);
}
function _claimSTACK(address _user) internal returns (uint256){
_kick();
CommitState memory _state = balances[_user];
if (_state.tokensAccrued == tokensAccrued){ // user doesn't have any accrued tokens
return 0;
}
// user has accrued tokens from their commit
else {
uint256 _tokensAccruedDiff = tokensAccrued.sub(_state.tokensAccrued);
uint256 _tokensGive = _tokensAccruedDiff.mul(getUserWeight(_user)).div(1e18);
_state.tokensAccrued = tokensAccrued;
balances[_user] = _state;
// if the guage has enough tokens to grant the user, then send their tokens
// otherwise, don't fail, just log STACK claimed, and a reimbursement can be done via chain events
if (IERC20(STACK).balanceOf(address(this)) >= _tokensGive){
IERC20(STACK).safeTransfer(_user, _tokensGive);
}
emit STACKClaimed(_user, _tokensGive);
return _tokensGive;
}
}
function _kick() internal {
uint256 _totalWeight = getTotalWeight();
// if there are no tokens committed, then don't kick.
if (_totalWeight == 0){
return;
}
// already done for this block || already did all blocks || not started yet
if (lastBlock == block.number || lastBlock >= endBlock || block.number < startBlock){
return;
}
uint256 _deltaBlock;
// edge case where kick was not called for the entire period of blocks.
if (lastBlock <= startBlock && block.number >= endBlock){
_deltaBlock = endBlock.sub(startBlock);
}
// where block.number is past the endBlock
else if (block.number >= endBlock){
_deltaBlock = endBlock.sub(lastBlock);
}
// where last block is before start
else if (lastBlock <= startBlock){
_deltaBlock = block.number.sub(startBlock);
}
// normal case, where we are in the middle of the distribution
else {
_deltaBlock = block.number.sub(lastBlock);
}
// mint tokens & update tokensAccrued global
uint256 _tokensToAccrue = _deltaBlock.mul(emissionRate);
tokensAccrued = tokensAccrued.add(_tokensToAccrue.mul(1e18).div(_totalWeight));
// if not allowed to mint it's just like the emission rate = 0. So just update the lastBlock.
// always update last block
lastBlock = block.number;
}
// a one-time use function to sweep any commitSoft to the vc fund rewards pool, after the 3 month window
function sweepCommitSoft() nonReentrant public {
require(block.number > endBlock, "GAUGE: <=endBlock");
// transfer all remaining ERC20 tokens to the VC address. Fund entry has closed, VC fund will start.
IERC20(acceptToken).safeTransfer(governance, IERC20(acceptToken).balanceOf(address(this)));
}
function getTotalWeight() public view returns (uint256){
uint256 soft = depositedCommitSoft.mul(commitSoftWeight);
uint256 hard = depositedCommitHard.mul(commitHardWeight);
return soft.add(hard);
}
function getTotalBalance() public view returns(uint256){
return depositedCommitSoft.add(depositedCommitHard);
}
function getUserWeight(address _user) public view returns (uint256){
uint256 soft = balances[_user].balanceCommitSoft.mul(commitSoftWeight);
uint256 hard = balances[_user].balanceCommitHard.mul(commitHardWeight);
return soft.add(hard);
}
function getUserBalance(address _user) public view returns (uint256){
uint256 soft = balances[_user].balanceCommitSoft;
uint256 hard = balances[_user].balanceCommitHard;
return soft.add(hard);
}
function getCommitted() public view returns (uint256, uint256, uint256){
return (depositedCommitSoft, depositedCommitHard, getTotalBalance());
}
// decentralized rescue function for any stuck tokens, will return to governance
function rescue(address _token, uint256 _amount) nonReentrant external {
require(msg.sender == governance, "GAUGE: !governance");
if (_token != address(0)){
IERC20(_token).safeTransfer(governance, _amount);
}
else { // if _tokenContract is 0x0, then escape ETH
governance.transfer(_amount);
}
}
}
|
upgrading from soft -> hard commit
|
function upgradeCommit(uint256 _amount) nonReentrant external {
require(block.number <= endBlock, "GAUGE: distribution 1 over");
_claimSTACK(msg.sender);
CommitState memory _state = balances[msg.sender];
require(_amount <= _state.balanceCommitSoft, "GAUGE: insufficient balance softCommit");
_state.balanceCommitSoft = _state.balanceCommitSoft.sub(_amount);
_state.balanceCommitHard = _state.balanceCommitHard.add(_amount);
depositedCommitSoft = depositedCommitSoft.sub(_amount);
depositedCommitHard = depositedCommitHard.add(_amount);
IERC20(acceptToken).safeTransfer(governance, _amount);
emit Upgrade(msg.sender, _amount);
balances[msg.sender] = _state;
}
| 14,401,393 |
pragma solidity 0.6.12;
import "./base/Controller.sol";
import "./base/EternalStorage.sol";
import "./EntityFacetBase.sol";
import "./base/IEntityCoreFacet.sol";
import "./base/IDiamondFacet.sol";
import "./base/IERC20.sol";
import "./base/IMarket.sol";
import "./base/IPolicy.sol";
import "./base/SafeMath.sol";
import "./Policy.sol";
/**
* @dev Business-logic for Entity
*/
contract EntityCoreFacet is EternalStorage, Controller, EntityFacetBase, IEntityCoreFacet, IDiamondFacet {
using SafeMath for uint256;
modifier assertCanTradeTranchTokens () {
require(inRoleGroup(msg.sender, ROLEGROUP_TRADERS), 'must be trader');
_;
}
modifier assertCanPayTranchPremiums (address _policyAddress) {
require(inRoleGroup(msg.sender, ROLEGROUP_ENTITY_REPS), 'must be entity rep');
_;
}
/**
* Constructor
*/
constructor (address _settings) Controller(_settings) public {
}
// IDiamondFacet
function getSelectors () public pure override returns (bytes memory) {
return abi.encodePacked(
IEntityCoreFacet.createPolicy.selector,
IEntityCoreFacet.getBalance.selector,
IEntityCoreFacet.getNumPolicies.selector,
IEntityCoreFacet.getPolicy.selector,
IEntityCoreFacet.deposit.selector,
IEntityCoreFacet.withdraw.selector,
IEntityCoreFacet.payTranchPremium.selector,
IEntityCoreFacet.trade.selector,
IEntityCoreFacet.sellAtBestPrice.selector
);
}
// IEntityCoreFacet
function createPolicy(
uint256[] calldata _dates,
address _unit,
uint256 _premiumIntervalSeconds,
uint256[] calldata _commmissionsBP,
address[] calldata _stakeholders
)
external
override
{
address[] memory stakeholders = new address[](6);
stakeholders[0] = address(this);
stakeholders[1] = msg.sender;
stakeholders[2] = _stakeholders[0];
stakeholders[3] = _stakeholders[1];
stakeholders[4] = _stakeholders[2];
stakeholders[5] = _stakeholders[3];
require(
IAccessControl(stakeholders[2]).aclContext() == aclContext(),
'underwriter ACL context must match'
);
Policy f = new Policy(
address(settings()),
stakeholders,
_dates,
_unit,
_premiumIntervalSeconds,
_commmissionsBP
);
uint256 numPolicies = dataUint256["numPolicies"];
address pAddr = address(f);
dataAddress[__i(numPolicies, "policy")] = pAddr;
dataUint256["numPolicies"] = numPolicies + 1;
dataBool[__a(pAddr, "isPolicy")] = true; // for _isPolicyCreatedByMe() to work
emit NewPolicy(pAddr, address(this), msg.sender);
}
function getBalance(address _unit) public view override returns (uint256) {
return dataUint256[__a(_unit, "balance")];
}
function getNumPolicies() public view override returns (uint256) {
return dataUint256["numPolicies"];
}
function getPolicy(uint256 _index) public view override returns (address) {
return dataAddress[__i(_index, "policy")];
}
function deposit(address _unit, uint256 _amount)
external
override
{
IERC20 tok = IERC20(_unit);
tok.transferFrom(msg.sender, address(this), _amount);
dataUint256[__a(_unit, "balance")] = dataUint256[__a(_unit, "balance")].add(_amount);
emit EntityDeposit(msg.sender, _unit, _amount);
}
function withdraw(address _unit, uint256 _amount)
external
override
assertIsEntityAdmin(msg.sender)
{
_assertHasEnoughBalance(_unit, _amount);
dataUint256[__a(_unit, "balance")] = dataUint256[__a(_unit, "balance")].sub(_amount);
IERC20 tok = IERC20(_unit);
tok.transfer(msg.sender, _amount);
emit EntityWithdraw(msg.sender, _unit, _amount);
}
function payTranchPremium(address _policy, uint256 _tranchIndex, uint256 _amount)
external
override
assertCanPayTranchPremiums(_policy)
{
address policyUnitAddress;
IPolicy p = IPolicy(_policy);
// avoid stack too deep errors
{
uint256 i1;
uint256 i2;
uint256 i3;
address a1;
// policy's unit
(a1, i1, i2, i3, policyUnitAddress, , , , , ,) = p.getInfo();
}
// check balance
_assertHasEnoughBalance(policyUnitAddress, _amount);
// approve transfer
IERC20 tok = IERC20(policyUnitAddress);
tok.approve(_policy, _amount);
// do it
p.payTranchPremium(_tranchIndex, _amount);
}
function trade(address _payUnit, uint256 _payAmount, address _buyUnit, uint256 _buyAmount)
external
override
assertCanTradeTranchTokens
returns (uint256)
{
// check balance
_assertHasEnoughBalance(_payUnit, _payAmount);
// do it
return _tradeOnMarket(_payUnit, _payAmount, _buyUnit, _buyAmount);
}
function sellAtBestPrice(address _sellUnit, uint256 _sellAmount, address _buyUnit)
external
override
assertCanTradeTranchTokens
returns (uint256)
{
// check balance
_assertHasEnoughBalance(_sellUnit, _sellAmount);
// do it!
return _sellAtBestPriceOnMarket(_sellUnit, _sellAmount, _buyUnit);
}
}
|
check balance do it
|
function trade(address _payUnit, uint256 _payAmount, address _buyUnit, uint256 _buyAmount)
external
override
assertCanTradeTranchTokens
returns (uint256)
{
_assertHasEnoughBalance(_payUnit, _payAmount);
return _tradeOnMarket(_payUnit, _payAmount, _buyUnit, _buyAmount);
}
| 6,460,575 |
/**
*Submitted for verification at Etherscan.io on 2021-06-25
*/
// 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);
}
// File contracts/@openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File contracts/@openzeppelin/contracts/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/@openzeppelin/contracts/utils/Initializable.sol
// solhint-disable-next-line compiler-version
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File contracts/@openzeppelin/contracts/utils/ContextUpgradeable.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal 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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File contracts/@openzeppelin/contracts/utils/Pausable.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 ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
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());
}
}
// File contracts/@openzeppelin/contracts/security/ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File contracts/@openzeppelin/contracts/IERC20Metadata.sol
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
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);
}
// File contracts/@openzeppelin/contracts/utils/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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 contracts/@openzeppelin/contracts/ERC20.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, 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 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_) {
_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
* 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 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:
*
* - `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 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 { }
}
// File contracts/CosmosToken.sol
contract CosmosERC20 is ERC20 {
uint256 MAX_UINT = 2**256 - 1;
uint8 immutable private _decimals;
constructor(
address peggyAddress_,
string memory name_,
string memory symbol_,
uint8 decimals_
) ERC20(name_, symbol_) {
_decimals = decimals_;
_mint(peggyAddress_, MAX_UINT);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
}
// File contracts/@openzeppelin/contracts/OwnableUpgradeableWithExpiry.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 OwnableUpgradeableWithExpiry is Initializable, ContextUpgradeable {
address private _owner;
uint256 private _deployTimestamp;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
_deployTimestamp = block.timestamp;
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() external virtual onlyOwner {
_renounceOwnership();
}
/**
* @dev Get the timestamp of ownership expiry.
* @return The timestamp of ownership expiry.
*/
function getOwnershipExpiryTimestamp() public view returns (uint256) {
return _deployTimestamp + 52 weeks;
}
/**
* @dev Check if the contract ownership is expired.
* @return True if the contract ownership is expired.
*/
function isOwnershipExpired() public view returns (bool) {
return block.timestamp > getOwnershipExpiryTimestamp();
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called after ownership is expired.
*/
function renounceOwnershipAfterExpiry() external {
require(isOwnershipExpired(), "Ownership not yet expired");
_renounceOwnership();
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function _renounceOwnership() private {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
uint256[49] private __gap;
}
// File contracts/Peggy.sol
// This is used purely to avoid stack too deep errors
// represents everything about a given validator set
struct ValsetArgs {
// the validators in this set, represented by an Ethereum address
address[] validators;
// the powers of the given validators in the same order as above
uint256[] powers;
// the nonce of this validator set
uint256 valsetNonce;
// the reward amount denominated in the below reward token, can be
// set to zero
uint256 rewardAmount;
// the reward token, should be set to the zero address if not being used
address rewardToken;
}
// Don't change the order of state for working upgrades.
// AND BE AWARE OF INHERITANCE VARIABLES!
// Inherited contracts contain storage slots and must be accounted for in any upgrades
// always test an exact upgrade on testnet and localhost before mainnet upgrades.
contract Peggy is Initializable, OwnableUpgradeableWithExpiry, Pausable, ReentrancyGuard {
using SafeERC20 for IERC20;
// These are updated often
bytes32 public state_lastValsetCheckpoint;
mapping(address => uint256) public state_lastBatchNonces;
mapping(bytes32 => uint256) public state_invalidationMapping;
uint256 public state_lastValsetNonce = 0;
uint256 public state_lastEventNonce = 0;
// These are set once at initialization
bytes32 public state_peggyId;
uint256 public state_powerThreshold;
// TransactionBatchExecutedEvent and SendToCosmosEvent both include the field _eventNonce.
// This is incremented every time one of these events is emitted. It is checked by the
// Cosmos module to ensure that all events are received in order, and that none are lost.
//
// ValsetUpdatedEvent does not include the field _eventNonce because it is never submitted to the Cosmos
// module. It is purely for the use of relayers to allow them to successfully submit batches.
event TransactionBatchExecutedEvent(
uint256 indexed _batchNonce,
address indexed _token,
uint256 _eventNonce
);
event SendToCosmosEvent(
address indexed _tokenContract,
address indexed _sender,
bytes32 indexed _destination,
uint256 _amount,
uint256 _eventNonce
);
event ERC20DeployedEvent(
// TODO(xlab): _cosmosDenom can be represented as bytes32 to allow indexing
string _cosmosDenom,
address indexed _tokenContract,
string _name,
string _symbol,
uint8 _decimals,
uint256 _eventNonce
);
event ValsetUpdatedEvent(
uint256 indexed _newValsetNonce,
uint256 _eventNonce,
uint256 _rewardAmount,
address _rewardToken,
address[] _validators,
uint256[] _powers
);
function initialize(
// A unique identifier for this peggy instance to use in signatures
bytes32 _peggyId,
// How much voting power is needed to approve operations
uint256 _powerThreshold,
// The validator set, not in valset args format since many of it's
// arguments would never be used in this case
address[] calldata _validators,
uint256[] memory _powers
) external initializer {
__Context_init_unchained();
__Ownable_init_unchained();
// CHECKS
// Check that validators, powers, and signatures (v,r,s) set is well-formed
require(
_validators.length == _powers.length,
"Malformed current validator set"
);
// Check cumulative power to ensure the contract has sufficient power to actually
// pass a vote
uint256 cumulativePower = 0;
for (uint256 i = 0; i < _powers.length; i++) {
cumulativePower = cumulativePower + _powers[i];
if (cumulativePower > _powerThreshold) {
break;
}
}
require(
cumulativePower > _powerThreshold,
"Submitted validator set signatures do not have enough power."
);
ValsetArgs memory _valset;
_valset = ValsetArgs(_validators, _powers, 0, 0, address(0));
bytes32 newCheckpoint = makeCheckpoint(_valset, _peggyId);
// ACTIONS
state_peggyId = _peggyId;
state_powerThreshold = _powerThreshold;
state_lastValsetCheckpoint = newCheckpoint;
state_lastEventNonce = state_lastEventNonce + 1;
// LOGS
emit ValsetUpdatedEvent(
state_lastValsetNonce,
state_lastEventNonce,
0,
address(0),
_validators,
_powers
);
}
function lastBatchNonce(address _erc20Address) public view returns (uint256) {
return state_lastBatchNonces[_erc20Address];
}
// Utility function to verify geth style signatures
function verifySig(
address _signer,
bytes32 _theHash,
uint8 _v,
bytes32 _r,
bytes32 _s
) private pure returns (bool) {
bytes32 messageDigest =
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _theHash));
return _signer == ecrecover(messageDigest, _v, _r, _s);
}
// Make a new checkpoint from the supplied validator set
// A checkpoint is a hash of all relevant information about the valset. This is stored by the contract,
// instead of storing the information directly. This saves on storage and gas.
// The format of the checkpoint is:
// h(peggyId, "checkpoint", valsetNonce, validators[], powers[])
// Where h is the keccak256 hash function.
// The validator powers must be decreasing or equal. This is important for checking the signatures on the
// next valset, since it allows the caller to stop verifying signatures once a quorum of signatures have been verified.
function makeCheckpoint(ValsetArgs memory _valsetArgs, bytes32 _peggyId)
private
pure
returns (bytes32)
{
// bytes32 encoding of the string "checkpoint"
bytes32 methodName =
0x636865636b706f696e7400000000000000000000000000000000000000000000;
bytes32 checkpoint =
keccak256(
abi.encode(
_peggyId,
methodName,
_valsetArgs.valsetNonce,
_valsetArgs.validators,
_valsetArgs.powers,
_valsetArgs.rewardAmount,
_valsetArgs.rewardToken
)
);
return checkpoint;
}
function checkValidatorSignatures(
// The current validator set and their powers
address[] memory _currentValidators,
uint256[] memory _currentPowers,
// The current validator's signatures
uint8[] memory _v,
bytes32[] memory _r,
bytes32[] memory _s,
// This is what we are checking they have signed
bytes32 _theHash,
uint256 _powerThreshold
) private pure {
uint256 cumulativePower = 0;
for (uint256 i = 0; i < _currentValidators.length; i++) {
// If v is set to 0, this signifies that it was not possible to get a signature from this validator and we skip evaluation
// (In a valid signature, it is either 27 or 28)
if (_v[i] != 0) {
// Check that the current validator has signed off on the hash
require(
verifySig(_currentValidators[i], _theHash, _v[i], _r[i], _s[i]),
"Validator signature does not match."
);
// Sum up cumulative power
cumulativePower = cumulativePower + _currentPowers[i];
// Break early to avoid wasting gas
if (cumulativePower > _powerThreshold) {
break;
}
}
}
// Check that there was enough power
require(
cumulativePower > _powerThreshold,
"Submitted validator set signatures do not have enough power."
);
// Success
}
// This updates the valset by checking that the validators in the current valset have signed off on the
// new valset. The signatures supplied are the signatures of the current valset over the checkpoint hash
// generated from the new valset.
// Anyone can call this function, but they must supply valid signatures of state_powerThreshold of the current valset over
// the new valset.
function updateValset(
// The new version of the validator set
ValsetArgs memory _newValset,
// The current validators that approve the change
ValsetArgs memory _currentValset,
// These are arrays of the parts of the current validator's signatures
uint8[] memory _v,
bytes32[] memory _r,
bytes32[] memory _s
) external whenNotPaused {
// CHECKS
// Check that the valset nonce is greater than the old one
require(
_newValset.valsetNonce > _currentValset.valsetNonce,
"New valset nonce must be greater than the current nonce"
);
// Check that new validators and powers set is well-formed
require(
_newValset.validators.length == _newValset.powers.length,
"Malformed new validator set"
);
// Check that current validators, powers, and signatures (v,r,s) set is well-formed
require(
_currentValset.validators.length == _currentValset.powers.length &&
_currentValset.validators.length == _v.length &&
_currentValset.validators.length == _r.length &&
_currentValset.validators.length == _s.length,
"Malformed current validator set"
);
// Check that the supplied current validator set matches the saved checkpoint
require(
makeCheckpoint(_currentValset, state_peggyId) ==
state_lastValsetCheckpoint,
"Supplied current validators and powers do not match checkpoint."
);
// Check that enough current validators have signed off on the new validator set
bytes32 newCheckpoint = makeCheckpoint(_newValset, state_peggyId);
checkValidatorSignatures(
_currentValset.validators,
_currentValset.powers,
_v,
_r,
_s,
newCheckpoint,
state_powerThreshold
);
// ACTIONS
// Stored to be used next time to validate that the valset
// supplied by the caller is correct.
state_lastValsetCheckpoint = newCheckpoint;
// Store new nonce
state_lastValsetNonce = _newValset.valsetNonce;
// Send submission reward to msg.sender if reward token is a valid value
if (_newValset.rewardToken != address(0) && _newValset.rewardAmount != 0) {
IERC20(_newValset.rewardToken).safeTransfer(
msg.sender,
_newValset.rewardAmount
);
}
// LOGS
state_lastEventNonce = state_lastEventNonce + 1;
emit ValsetUpdatedEvent(
_newValset.valsetNonce,
state_lastEventNonce,
_newValset.rewardAmount,
_newValset.rewardToken,
_newValset.validators,
_newValset.powers
);
}
// submitBatch processes a batch of Cosmos -> Ethereum transactions by sending the tokens in the transactions
// to the destination addresses. It is approved by the current Cosmos validator set.
// Anyone can call this function, but they must supply valid signatures of state_powerThreshold of the current valset over
// the batch.
function submitBatch(
// The validators that approve the batch
ValsetArgs memory _currentValset,
// These are arrays of the parts of the validators signatures
uint8[] memory _v,
bytes32[] memory _r,
bytes32[] memory _s,
// The batch of transactions
uint256[] memory _amounts,
address[] memory _destinations,
uint256[] memory _fees,
uint256 _batchNonce,
address _tokenContract,
// a block height beyond which this batch is not valid
// used to provide a fee-free timeout
uint256 _batchTimeout
) external nonReentrant whenNotPaused {
// CHECKS scoped to reduce stack depth
{
// Check that the batch nonce is higher than the last nonce for this token
require(
state_lastBatchNonces[_tokenContract] < _batchNonce,
"New batch nonce must be greater than the current nonce"
);
// Check that the block height is less than the timeout height
require(
block.number < _batchTimeout,
"Batch timeout must be greater than the current block height"
);
// Check that current validators, powers, and signatures (v,r,s) set is well-formed
require(
_currentValset.validators.length == _currentValset.powers.length &&
_currentValset.validators.length == _v.length &&
_currentValset.validators.length == _r.length &&
_currentValset.validators.length == _s.length,
"Malformed current validator set"
);
// Check that the supplied current validator set matches the saved checkpoint
require(
makeCheckpoint(_currentValset, state_peggyId) ==
state_lastValsetCheckpoint,
"Supplied current validators and powers do not match checkpoint."
);
// Check that the transaction batch is well-formed
require(
_amounts.length == _destinations.length &&
_amounts.length == _fees.length,
"Malformed batch of transactions"
);
// Check that enough current validators have signed off on the transaction batch and valset
checkValidatorSignatures(
_currentValset.validators,
_currentValset.powers,
_v,
_r,
_s,
// Get hash of the transaction batch and checkpoint
keccak256(
abi.encode(
state_peggyId,
// bytes32 encoding of "transactionBatch"
0x7472616e73616374696f6e426174636800000000000000000000000000000000,
_amounts,
_destinations,
_fees,
_batchNonce,
_tokenContract,
_batchTimeout
)
),
state_powerThreshold
);
// ACTIONS
// Store batch nonce
state_lastBatchNonces[_tokenContract] = _batchNonce;
{
// Send transaction amounts to destinations
uint256 totalFee;
for (uint256 i = 0; i < _amounts.length; i++) {
IERC20(_tokenContract).safeTransfer(_destinations[i], _amounts[i]);
totalFee = totalFee + _fees[i];
}
if (totalFee > 0) {
// Send transaction fees to msg.sender
IERC20(_tokenContract).safeTransfer(msg.sender, totalFee);
}
}
}
// LOGS scoped to reduce stack depth
{
state_lastEventNonce = state_lastEventNonce + 1;
emit TransactionBatchExecutedEvent(
_batchNonce,
_tokenContract,
state_lastEventNonce
);
}
}
function sendToCosmos(
address _tokenContract,
bytes32 _destination,
uint256 _amount
) external whenNotPaused nonReentrant {
IERC20(_tokenContract).safeTransferFrom(msg.sender, address(this), _amount);
state_lastEventNonce = state_lastEventNonce + 1;
emit SendToCosmosEvent(
_tokenContract,
msg.sender,
_destination,
_amount,
state_lastEventNonce
);
}
function deployERC20(
string calldata _cosmosDenom,
string calldata _name,
string calldata _symbol,
uint8 _decimals
) external {
// Deploy an ERC20 with entire supply granted to Peggy.sol
CosmosERC20 erc20 =
new CosmosERC20(address(this), _name, _symbol, _decimals);
// Fire an event to let the Cosmos module know
state_lastEventNonce = state_lastEventNonce + 1;
emit ERC20DeployedEvent(
_cosmosDenom,
address(erc20),
_name,
_symbol,
_decimals,
state_lastEventNonce
);
}
function emergencyPause() external onlyOwner {
_pause();
}
function emergencyUnpause() external onlyOwner {
_unpause();
}
}
|
Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner./
|
function transferOwnership(address newOwner) external virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| 2,134,335 |
//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
contract FreakShowNFT is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable, Pausable {
using Counters for Counters.Counter;
using SafeMath for uint256;
Counters.Counter private tokenIdCounter;
constructor() public ERC721("FreakshowNFT", "FREAKSHOW") {}
bool public isSaleActive = false;
uint256 public constant maxSupply = 10310;
uint256 public max_per_purchase = 100;
string public baseURI;
address firstWallet = 0x7431ac593d117BC3A28fa4025a39BCcCCAcf89AA;
address secondWallet = 0x7b845ED4979b27C49045E1A7eF6e96DF43ef8EC2;
address thirdWallet = 0x042a7172069e878b527b5c7BCce4B01353217399;
address fourthWallet = 0x7c4D3401e167c0699feb6319b5118c60088e60E9;
// uint256 private price = 10000000000000000; // 0.01 Ether
uint256 private price = 90000000000000000; // 0.09 ETHER
// Variables defined to keep track of stages and thresholds
mapping(uint => uint) public stages;
uint256 public stage = 1;
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function setMaxPerPurchase(uint256 _max) public onlyOwner {
max_per_purchase = _max;
}
// steStage is used to set the stage of the contract
function setStage(uint256 _stage, uint256 _threshold) public onlyOwner {
stages[_stage] = _threshold;
}
function setBaseURI(string memory newBaseURI) public onlyOwner {
baseURI = newBaseURI;
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function internalMint(address to) internal {
require(totalSupply() < maxSupply, 'supply depleted');
_safeMint(to, tokenIdCounter.current());
tokenIdCounter.increment();
// Checking if totalSupply() has reached the next stage,
// if so, we set the stage to the next one and pause the contract
if (totalSupply() == stages[stage]) {
stopContract();
}
}
function safeMint(address to) public onlyOwner {
internalMint(to);
}
// Function that allows only owner to mint for free
// even on sale inactive
function mintNFTReserve(uint256 amount)
public onlyOwner
{
require(amount <= max_per_purchase, 'excedeed number of items per transaction');
for (uint256 i = 0; i < amount; i++) internalMint(msg.sender);
}
function mintNFT(uint256 amount)
public payable
{
require(isSaleActive, "Sale is not active" );
require(msg.value >= price * amount, "Ether value sent is not correct");
require(amount <= max_per_purchase, 'excedeed number of items per transaction');
for (uint256 i = 0; i < amount; i++) internalMint(msg.sender);
}
// Helper functions
function setPrice(uint256 _newPrice) public onlyOwner() {
price = _newPrice;
}
function getPrice() public view returns (uint256){
return price;
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(firstWallet).transfer((balance * 250) / 1000);
payable(secondWallet).transfer((balance * 100) / 1000);
payable(thirdWallet).transfer((balance * 625) / 1000);
payable(fourthWallet).transfer((balance * 25) / 1000);
}
function stopContract() public onlyOwner {
require(isSaleActive, "Sale is not active" );
stage = stage + 1;
isSaleActive = false;
}
function flipSaleStatus() public onlyOwner {
isSaleActive = !isSaleActive;
}
function tokensByOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
// The following functions are overrides required by Solidity.
function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) {
return super.tokenURI(tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
|
Function that allows only owner to mint for free even on sale inactive
|
function mintNFTReserve(uint256 amount)
public onlyOwner
{
require(amount <= max_per_purchase, 'excedeed number of items per transaction');
for (uint256 i = 0; i < amount; i++) internalMint(msg.sender);
}
| 10,409,999 |
/**
*Submitted for verification at Etherscan.io on 2021-07-08
*/
// Sources flattened with hardhat v2.4.0 https://hardhat.org
// File contracts/auxiliary/interfaces/v0.8.4/IERC20Aux.sol
pragma solidity 0.8.4;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Aux {
/**
* @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/auxiliary/interfaces/v0.8.4/IApi3Token.sol
pragma solidity 0.8.4;
interface IApi3Token is IERC20Aux {
event MinterStatusUpdated(
address indexed minterAddress,
bool minterStatus
);
event BurnerStatusUpdated(
address indexed burnerAddress,
bool burnerStatus
);
function updateMinterStatus(
address minterAddress,
bool minterStatus
)
external;
function updateBurnerStatus(bool burnerStatus)
external;
function mint(
address account,
uint256 amount
)
external;
function burn(uint256 amount)
external;
function getMinterStatus(address minterAddress)
external
view
returns (bool minterStatus);
function getBurnerStatus(address burnerAddress)
external
view
returns (bool burnerStatus);
}
// File contracts/interfaces/IStateUtils.sol
pragma solidity 0.8.4;
interface IStateUtils {
event SetDaoApps(
address agentAppPrimary,
address agentAppSecondary,
address votingAppPrimary,
address votingAppSecondary
);
event SetClaimsManagerStatus(
address indexed claimsManager,
bool indexed status
);
event SetStakeTarget(uint256 stakeTarget);
event SetMaxApr(uint256 maxApr);
event SetMinApr(uint256 minApr);
event SetUnstakeWaitPeriod(uint256 unstakeWaitPeriod);
event SetAprUpdateStep(uint256 aprUpdateStep);
event SetProposalVotingPowerThreshold(uint256 proposalVotingPowerThreshold);
event UpdatedLastProposalTimestamp(
address indexed user,
uint256 lastProposalTimestamp,
address votingApp
);
function setDaoApps(
address _agentAppPrimary,
address _agentAppSecondary,
address _votingAppPrimary,
address _votingAppSecondary
)
external;
function setClaimsManagerStatus(
address claimsManager,
bool status
)
external;
function setStakeTarget(uint256 _stakeTarget)
external;
function setMaxApr(uint256 _maxApr)
external;
function setMinApr(uint256 _minApr)
external;
function setUnstakeWaitPeriod(uint256 _unstakeWaitPeriod)
external;
function setAprUpdateStep(uint256 _aprUpdateStep)
external;
function setProposalVotingPowerThreshold(uint256 _proposalVotingPowerThreshold)
external;
function updateLastProposalTimestamp(address userAddress)
external;
function isGenesisEpoch()
external
view
returns (bool);
}
// File contracts/StateUtils.sol
pragma solidity 0.8.4;
/// @title Contract that keeps state variables
contract StateUtils is IStateUtils {
struct Checkpoint {
uint32 fromBlock;
uint224 value;
}
struct AddressCheckpoint {
uint32 fromBlock;
address _address;
}
struct Reward {
uint32 atBlock;
uint224 amount;
uint256 totalSharesThen;
uint256 totalStakeThen;
}
struct User {
Checkpoint[] shares;
Checkpoint[] delegatedTo;
AddressCheckpoint[] delegates;
uint256 unstaked;
uint256 vesting;
uint256 unstakeAmount;
uint256 unstakeShares;
uint256 unstakeScheduledFor;
uint256 lastDelegationUpdateTimestamp;
uint256 lastProposalTimestamp;
}
struct LockedCalculation {
uint256 initialIndEpoch;
uint256 nextIndEpoch;
uint256 locked;
}
/// @notice Length of the epoch in which the staking reward is paid out
/// once. It is hardcoded as 7 days.
/// @dev In addition to regulating reward payments, this variable is used
/// for two additional things:
/// (1) After a user makes a proposal, they cannot make a second one
/// before `EPOCH_LENGTH` has passed
/// (2) After a user updates their delegation status, they have to wait
/// `EPOCH_LENGTH` before updating it again
uint256 public constant EPOCH_LENGTH = 1 weeks;
/// @notice Number of epochs before the staking rewards get unlocked.
/// Hardcoded as 52 epochs, which approximately corresponds to a year with
/// an `EPOCH_LENGTH` of 1 week.
uint256 public constant REWARD_VESTING_PERIOD = 52;
// All percentage values are represented as 1e18 = 100%
uint256 internal constant ONE_PERCENT = 1e18 / 100;
uint256 internal constant HUNDRED_PERCENT = 1e18;
// To assert that typecasts do not overflow
uint256 internal constant MAX_UINT32 = 2**32 - 1;
uint256 internal constant MAX_UINT224 = 2**224 - 1;
/// @notice Epochs are indexed as `block.timestamp / EPOCH_LENGTH`.
/// `genesisEpoch` is the index of the epoch in which the pool is deployed.
/// @dev No reward gets paid and proposals are not allowed in the genesis
/// epoch
uint256 public immutable genesisEpoch;
/// @notice API3 token contract
IApi3Token public immutable api3Token;
/// @notice TimelockManager contract
address public immutable timelockManager;
/// @notice Address of the primary Agent app of the API3 DAO
/// @dev Primary Agent can be operated through the primary Api3Voting app.
/// The primary Api3Voting app requires a higher quorum by default, and the
/// primary Agent is more privileged.
address public agentAppPrimary;
/// @notice Address of the secondary Agent app of the API3 DAO
/// @dev Secondary Agent can be operated through the secondary Api3Voting
/// app. The secondary Api3Voting app requires a lower quorum by default,
/// and the primary Agent is less privileged.
address public agentAppSecondary;
/// @notice Address of the primary Api3Voting app of the API3 DAO
/// @dev Used to operate the primary Agent
address public votingAppPrimary;
/// @notice Address of the secondary Api3Voting app of the API3 DAO
/// @dev Used to operate the secondary Agent
address public votingAppSecondary;
/// @notice Mapping that keeps the claims manager statuses of addresses
/// @dev A claims manager is a contract that is authorized to pay out
/// claims from the staking pool, effectively slashing the stakers. The
/// statuses are kept as a mapping to support multiple claims managers.
mapping(address => bool) public claimsManagerStatus;
/// @notice Records of rewards paid in each epoch
/// @dev `.atBlock` of a past epoch's reward record being `0` means no
/// reward was paid for that epoch
mapping(uint256 => Reward) public epochIndexToReward;
/// @notice Epoch index of the most recent reward
uint256 public epochIndexOfLastReward;
/// @notice Total number of tokens staked at the pool
uint256 public totalStake;
/// @notice Stake target the pool will aim to meet in percentages of the
/// total token supply. The staking rewards increase if the total staked
/// amount is below this, and vice versa.
/// @dev Default value is 50% of the total API3 token supply. This
/// parameter is governable by the DAO.
uint256 public stakeTarget = ONE_PERCENT * 50;
/// @notice Minimum APR (annual percentage rate) the pool will pay as
/// staking rewards in percentages
/// @dev Default value is 2.5%. This parameter is governable by the DAO.
uint256 public minApr = ONE_PERCENT * 25 / 10;
/// @notice Maximum APR (annual percentage rate) the pool will pay as
/// staking rewards in percentages
/// @dev Default value is 75%. This parameter is governable by the DAO.
uint256 public maxApr = ONE_PERCENT * 75;
/// @notice Steps in which APR will be updated in percentages
/// @dev Default value is 1%. This parameter is governable by the DAO.
uint256 public aprUpdateStep = ONE_PERCENT;
/// @notice Users need to schedule an unstake and wait for
/// `unstakeWaitPeriod` before being able to unstake. This is to prevent
/// the stakers from frontrunning insurance claims by unstaking to evade
/// them, or repeatedly unstake/stake to work around the proposal spam
/// protection. The tokens awaiting to be unstaked during this period do
/// not grant voting power or rewards.
/// @dev This parameter is governable by the DAO, and the DAO is expected
/// to set this to a value that is large enough to allow insurance claims
/// to be resolved.
uint256 public unstakeWaitPeriod = EPOCH_LENGTH;
/// @notice Minimum voting power the users must have to be able to make
/// proposals (in percentages)
/// @dev Delegations count towards voting power.
/// Default value is 0.1%. This parameter is governable by the DAO.
uint256 public proposalVotingPowerThreshold = ONE_PERCENT / 10;
/// @notice APR that will be paid next epoch
/// @dev This value will reach an equilibrium based on the stake target.
/// Every epoch (week), APR/52 of the total staked tokens will be added to
/// the pool, effectively distributing them to the stakers.
uint256 public apr = (maxApr + minApr) / 2;
/// @notice User records
mapping(address => User) public users;
// Keeps the total number of shares of the pool
Checkpoint[] public poolShares;
// Keeps user states used in `withdrawPrecalculated()` calls
mapping(address => LockedCalculation) public userToLockedCalculation;
// Kept to prevent third parties from frontrunning the initialization
// `setDaoApps()` call and grief the deployment
address private deployer;
/// @dev Reverts if the caller is not an API3 DAO Agent
modifier onlyAgentApp() {
require(
msg.sender == agentAppPrimary || msg.sender == agentAppSecondary,
"Pool: Caller not agent"
);
_;
}
/// @dev Reverts if the caller is not the primary API3 DAO Agent
modifier onlyAgentAppPrimary() {
require(
msg.sender == agentAppPrimary,
"Pool: Caller not primary agent"
);
_;
}
/// @dev Reverts if the caller is not an API3 DAO Api3Voting app
modifier onlyVotingApp() {
require(
msg.sender == votingAppPrimary || msg.sender == votingAppSecondary,
"Pool: Caller not voting app"
);
_;
}
/// @param api3TokenAddress API3 token contract address
/// @param timelockManagerAddress Timelock manager contract address
constructor(
address api3TokenAddress,
address timelockManagerAddress
)
{
require(
api3TokenAddress != address(0),
"Pool: Invalid Api3Token"
);
require(
timelockManagerAddress != address(0),
"Pool: Invalid TimelockManager"
);
deployer = msg.sender;
api3Token = IApi3Token(api3TokenAddress);
timelockManager = timelockManagerAddress;
// Initialize the share price at 1
updateCheckpointArray(poolShares, 1);
totalStake = 1;
// Set the current epoch as the genesis epoch and skip its reward
// payment
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
genesisEpoch = currentEpoch;
epochIndexOfLastReward = currentEpoch;
}
/// @notice Called after deployment to set the addresses of the DAO apps
/// @dev This can also be called later on by the primary Agent to update
/// all app addresses as a means of an upgrade
/// @param _agentAppPrimary Address of the primary Agent
/// @param _agentAppSecondary Address of the secondary Agent
/// @param _votingAppPrimary Address of the primary Api3Voting app
/// @param _votingAppSecondary Address of the secondary Api3Voting app
function setDaoApps(
address _agentAppPrimary,
address _agentAppSecondary,
address _votingAppPrimary,
address _votingAppSecondary
)
external
override
{
// solhint-disable-next-line reason-string
require(
msg.sender == agentAppPrimary
|| (agentAppPrimary == address(0) && msg.sender == deployer),
"Pool: Caller not primary agent or deployer initializing values"
);
require(
_agentAppPrimary != address(0)
&& _agentAppSecondary != address(0)
&& _votingAppPrimary != address(0)
&& _votingAppSecondary != address(0),
"Pool: Invalid DAO apps"
);
agentAppPrimary = _agentAppPrimary;
agentAppSecondary = _agentAppSecondary;
votingAppPrimary = _votingAppPrimary;
votingAppSecondary = _votingAppSecondary;
emit SetDaoApps(
agentAppPrimary,
agentAppSecondary,
votingAppPrimary,
votingAppSecondary
);
}
/// @notice Called by the primary DAO Agent to set the authorization status
/// of a claims manager contract
/// @dev The claims manager is a trusted contract that is allowed to
/// withdraw as many tokens as it wants from the pool to pay out insurance
/// claims.
/// Only the primary Agent can do this because it is a critical operation.
/// WARNING: A compromised contract being given claims manager status may
/// result in loss of staked funds. If a proposal has been made to call
/// this method to set a contract as a claims manager, you are recommended
/// to review the contract yourself and/or refer to the audit reports to
/// understand the implications.
/// @param claimsManager Claims manager contract address
/// @param status Authorization status
function setClaimsManagerStatus(
address claimsManager,
bool status
)
external
override
onlyAgentAppPrimary()
{
claimsManagerStatus[claimsManager] = status;
emit SetClaimsManagerStatus(
claimsManager,
status
);
}
/// @notice Called by the DAO Agent to set the stake target
/// @param _stakeTarget Stake target
function setStakeTarget(uint256 _stakeTarget)
external
override
onlyAgentApp()
{
require(
_stakeTarget <= HUNDRED_PERCENT,
"Pool: Invalid percentage value"
);
stakeTarget = _stakeTarget;
emit SetStakeTarget(_stakeTarget);
}
/// @notice Called by the DAO Agent to set the maximum APR
/// @param _maxApr Maximum APR
function setMaxApr(uint256 _maxApr)
external
override
onlyAgentApp()
{
require(
_maxApr >= minApr,
"Pool: Max APR smaller than min"
);
maxApr = _maxApr;
emit SetMaxApr(_maxApr);
}
/// @notice Called by the DAO Agent to set the minimum APR
/// @param _minApr Minimum APR
function setMinApr(uint256 _minApr)
external
override
onlyAgentApp()
{
require(
_minApr <= maxApr,
"Pool: Min APR larger than max"
);
minApr = _minApr;
emit SetMinApr(_minApr);
}
/// @notice Called by the primary DAO Agent to set the unstake waiting
/// period
/// @dev This may want to be increased to provide more time for insurance
/// claims to be resolved.
/// Even when the insurance functionality is not implemented, the minimum
/// valid value is `EPOCH_LENGTH` to prevent users from unstaking,
/// withdrawing and staking with another address to work around the
/// proposal spam protection.
/// Only the primary Agent can do this because it is a critical operation.
/// @param _unstakeWaitPeriod Unstake waiting period
function setUnstakeWaitPeriod(uint256 _unstakeWaitPeriod)
external
override
onlyAgentAppPrimary()
{
require(
_unstakeWaitPeriod >= EPOCH_LENGTH,
"Pool: Period shorter than epoch"
);
unstakeWaitPeriod = _unstakeWaitPeriod;
emit SetUnstakeWaitPeriod(_unstakeWaitPeriod);
}
/// @notice Called by the primary DAO Agent to set the APR update steps
/// @dev aprUpdateStep can be 0% or 100%+.
/// Only the primary Agent can do this because it is a critical operation.
/// @param _aprUpdateStep APR update steps
function setAprUpdateStep(uint256 _aprUpdateStep)
external
override
onlyAgentAppPrimary()
{
aprUpdateStep = _aprUpdateStep;
emit SetAprUpdateStep(_aprUpdateStep);
}
/// @notice Called by the primary DAO Agent to set the voting power
/// threshold for proposals
/// @dev Only the primary Agent can do this because it is a critical
/// operation.
/// @param _proposalVotingPowerThreshold Voting power threshold for
/// proposals
function setProposalVotingPowerThreshold(uint256 _proposalVotingPowerThreshold)
external
override
onlyAgentAppPrimary()
{
require(
_proposalVotingPowerThreshold >= ONE_PERCENT / 10
&& _proposalVotingPowerThreshold <= ONE_PERCENT * 10,
"Pool: Threshold outside limits");
proposalVotingPowerThreshold = _proposalVotingPowerThreshold;
emit SetProposalVotingPowerThreshold(_proposalVotingPowerThreshold);
}
/// @notice Called by a DAO Api3Voting app at proposal creation-time to
/// update the timestamp of the user's last proposal
/// @param userAddress User address
function updateLastProposalTimestamp(address userAddress)
external
override
onlyVotingApp()
{
users[userAddress].lastProposalTimestamp = block.timestamp;
emit UpdatedLastProposalTimestamp(
userAddress,
block.timestamp,
msg.sender
);
}
/// @notice Called to check if we are in the genesis epoch
/// @dev Voting apps use this to prevent proposals from being made in the
/// genesis epoch
/// @return If the current epoch is the genesis epoch
function isGenesisEpoch()
external
view
override
returns (bool)
{
return block.timestamp / EPOCH_LENGTH == genesisEpoch;
}
/// @notice Called internally to update a checkpoint array by pushing a new
/// checkpoint
/// @dev We assume `block.number` will always fit in a uint32 and `value`
/// will always fit in a uint224. `value` will either be a raw token amount
/// or a raw pool share amount so this assumption will be correct in
/// practice with a token with 18 decimals, 1e8 initial total supply and no
/// hyperinflation.
/// @param checkpointArray Checkpoint array
/// @param value Value to be used to create the new checkpoint
function updateCheckpointArray(
Checkpoint[] storage checkpointArray,
uint256 value
)
internal
{
assert(block.number <= MAX_UINT32);
assert(value <= MAX_UINT224);
checkpointArray.push(Checkpoint({
fromBlock: uint32(block.number),
value: uint224(value)
}));
}
/// @notice Called internally to update an address-checkpoint array by
/// pushing a new checkpoint
/// @dev We assume `block.number` will always fit in a uint32
/// @param addressCheckpointArray Address-checkpoint array
/// @param _address Address to be used to create the new checkpoint
function updateAddressCheckpointArray(
AddressCheckpoint[] storage addressCheckpointArray,
address _address
)
internal
{
assert(block.number <= MAX_UINT32);
addressCheckpointArray.push(AddressCheckpoint({
fromBlock: uint32(block.number),
_address: _address
}));
}
}
// File contracts/interfaces/IGetterUtils.sol
pragma solidity 0.8.4;
interface IGetterUtils is IStateUtils {
function userVotingPowerAt(
address userAddress,
uint256 _block
)
external
view
returns (uint256);
function userVotingPower(address userAddress)
external
view
returns (uint256);
function totalSharesAt(uint256 _block)
external
view
returns (uint256);
function totalShares()
external
view
returns (uint256);
function userSharesAt(
address userAddress,
uint256 _block
)
external
view
returns (uint256);
function userShares(address userAddress)
external
view
returns (uint256);
function userStake(address userAddress)
external
view
returns (uint256);
function delegatedToUserAt(
address userAddress,
uint256 _block
)
external
view
returns (uint256);
function delegatedToUser(address userAddress)
external
view
returns (uint256);
function userDelegateAt(
address userAddress,
uint256 _block
)
external
view
returns (address);
function userDelegate(address userAddress)
external
view
returns (address);
function userLocked(address userAddress)
external
view
returns (uint256);
function getUser(address userAddress)
external
view
returns (
uint256 unstaked,
uint256 vesting,
uint256 unstakeShares,
uint256 unstakeAmount,
uint256 unstakeScheduledFor,
uint256 lastDelegationUpdateTimestamp,
uint256 lastProposalTimestamp
);
}
// File contracts/GetterUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements getters
abstract contract GetterUtils is StateUtils, IGetterUtils {
/// @notice Called to get the voting power of a user at a specific block
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Voting power of the user at the block
function userVotingPowerAt(
address userAddress,
uint256 _block
)
public
view
override
returns (uint256)
{
// Users that have a delegate have no voting power
if (userDelegateAt(userAddress, _block) != address(0))
{
return 0;
}
return userSharesAt(userAddress, _block)
+ delegatedToUserAt(userAddress, _block);
}
/// @notice Called to get the current voting power of a user
/// @param userAddress User address
/// @return Current voting power of the user
function userVotingPower(address userAddress)
external
view
override
returns (uint256)
{
return userVotingPowerAt(userAddress, block.number);
}
/// @notice Called to get the total pool shares at a specific block
/// @dev Total pool shares also corresponds to total voting power
/// @param _block Block number for which the query is being made for
/// @return Total pool shares at the block
function totalSharesAt(uint256 _block)
public
view
override
returns (uint256)
{
return getValueAt(poolShares, _block);
}
/// @notice Called to get the current total pool shares
/// @dev Total pool shares also corresponds to total voting power
/// @return Current total pool shares
function totalShares()
public
view
override
returns (uint256)
{
return totalSharesAt(block.number);
}
/// @notice Called to get the pool shares of a user at a specific block
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Pool shares of the user at the block
function userSharesAt(
address userAddress,
uint256 _block
)
public
view
override
returns (uint256)
{
return getValueAt(users[userAddress].shares, _block);
}
/// @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(userAddress, block.number);
}
/// @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 userShares(userAddress) * totalStake / totalShares();
}
/// @notice Called to get the voting power delegated to a user at a
/// specific block
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Voting power delegated to the user at the block
function delegatedToUserAt(
address userAddress,
uint256 _block
)
public
view
override
returns (uint256)
{
return getValueAt(users[userAddress].delegatedTo, _block);
}
/// @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 delegatedToUser(address userAddress)
public
view
override
returns (uint256)
{
return delegatedToUserAt(userAddress, block.number);
}
/// @notice Called to get the delegate of the user at a specific block
/// @param userAddress User address
/// @param _block Block number
/// @return Delegate of the user at the specific block
function userDelegateAt(
address userAddress,
uint256 _block
)
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(userAddress, block.number);
}
/// @notice Called to get the current locked tokens of the user
/// @param userAddress User address
/// @return locked Current locked tokens of the user
function userLocked(address userAddress)
public
view
override
returns (uint256 locked)
{
Checkpoint[] storage _userShares = users[userAddress].shares;
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
uint256 oldestLockedEpoch = getOldestLockedEpoch();
uint256 indUserShares = _userShares.length;
for (
uint256 indEpoch = currentEpoch;
indEpoch >= oldestLockedEpoch;
indEpoch--
)
{
// The user has never staked at this point, we can exit early
if (indUserShares == 0)
{
break;
}
Reward storage lockedReward = epochIndexToReward[indEpoch];
if (lockedReward.atBlock != 0)
{
for (; indUserShares > 0; indUserShares--)
{
Checkpoint storage userShare = _userShares[indUserShares - 1];
if (userShare.fromBlock <= lockedReward.atBlock)
{
locked += lockedReward.amount * userShare.value / lockedReward.totalSharesThen;
break;
}
}
}
}
}
/// @notice Called to get the details of a user
/// @param userAddress User address
/// @return unstaked Amount of unstaked API3 tokens
/// @return vesting Amount of API3 tokens locked by vesting
/// @return unstakeAmount Amount scheduled to unstake
/// @return unstakeShares Shares revoked to unstake
/// @return unstakeScheduledFor Time unstaking is scheduled for
/// @return lastDelegationUpdateTimestamp Time of last delegation update
/// @return lastProposalTimestamp Time when the user made their most
/// recent proposal
function getUser(address userAddress)
external
view
override
returns (
uint256 unstaked,
uint256 vesting,
uint256 unstakeAmount,
uint256 unstakeShares,
uint256 unstakeScheduledFor,
uint256 lastDelegationUpdateTimestamp,
uint256 lastProposalTimestamp
)
{
User storage user = users[userAddress];
unstaked = user.unstaked;
vesting = user.vesting;
unstakeAmount = user.unstakeAmount;
unstakeShares = user.unstakeShares;
unstakeScheduledFor = user.unstakeScheduledFor;
lastDelegationUpdateTimestamp = user.lastDelegationUpdateTimestamp;
lastProposalTimestamp = user.lastProposalTimestamp;
}
/// @notice Called to get the value of a checkpoint array at a specific
/// block using binary search
/// @dev Adapted 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,
uint256 _block
)
internal
view
returns (uint256)
{
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length -1].fromBlock)
return checkpoints[checkpoints.length - 1].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Limit the search to the last 1024 elements if the value being
// searched falls within that window
uint min = 0;
if (
checkpoints.length > 1024
&& checkpoints[checkpoints.length - 1024].fromBlock < _block
)
{
min = checkpoints.length - 1024;
}
// Binary search of the value in the array
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 value of an address-checkpoint array at a
/// specific block using binary search
/// @dev Adapted from
/// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431
/// @param checkpoints Address-checkpoint array
/// @param _block Block number for which the query is being made
/// @return Value of the address-checkpoint array at the block
function getAddressAt(
AddressCheckpoint[] storage checkpoints,
uint256 _block
)
private
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);
// Limit the search to the last 1024 elements if the value being
// searched falls within that window
uint min = 0;
if (
checkpoints.length > 1024
&& checkpoints[checkpoints.length - 1024].fromBlock < _block
)
{
min = checkpoints.length - 1024;
}
// Binary search of the value in the array
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 internally to get the index of the oldest epoch whose
/// reward should be locked in the current epoch
/// @return oldestLockedEpoch Index of the oldest epoch with locked rewards
function getOldestLockedEpoch()
internal
view
returns (uint256 oldestLockedEpoch)
{
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
oldestLockedEpoch = currentEpoch - REWARD_VESTING_PERIOD + 1;
if (oldestLockedEpoch < genesisEpoch + 1)
{
oldestLockedEpoch = genesisEpoch + 1;
}
}
}
// File contracts/interfaces/IRewardUtils.sol
pragma solidity 0.8.4;
interface IRewardUtils is IGetterUtils {
event MintedReward(
uint256 indexed epochIndex,
uint256 amount,
uint256 newApr,
uint256 totalStake
);
function mintReward()
external;
}
// File contracts/RewardUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements reward payments
abstract contract RewardUtils is GetterUtils, IRewardUtils {
/// @notice Called to mint the staking reward
/// @dev Skips past epochs for which rewards have not been paid for.
/// Skips the reward payment if the pool is not authorized to mint tokens.
/// Neither of these conditions will occur in practice.
function mintReward()
public
override
{
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
// This will be skipped in most cases because someone else will have
// triggered the payment for this epoch
if (epochIndexOfLastReward < currentEpoch)
{
if (api3Token.getMinterStatus(address(this)))
{
uint256 rewardAmount = totalStake * apr * EPOCH_LENGTH / 365 days / HUNDRED_PERCENT;
assert(block.number <= MAX_UINT32);
assert(rewardAmount <= MAX_UINT224);
epochIndexToReward[currentEpoch] = Reward({
atBlock: uint32(block.number),
amount: uint224(rewardAmount),
totalSharesThen: totalShares(),
totalStakeThen: totalStake
});
api3Token.mint(address(this), rewardAmount);
totalStake += rewardAmount;
updateCurrentApr();
emit MintedReward(
currentEpoch,
rewardAmount,
apr,
totalStake
);
}
epochIndexOfLastReward = currentEpoch;
}
}
/// @notice Updates the current APR
/// @dev Called internally after paying out the reward
function updateCurrentApr()
internal
{
uint256 totalStakePercentage = totalStake
* HUNDRED_PERCENT
/ api3Token.totalSupply();
if (totalStakePercentage > stakeTarget)
{
apr = apr > aprUpdateStep ? apr - aprUpdateStep : 0;
}
else
{
apr += aprUpdateStep;
}
if (apr > maxApr) {
apr = maxApr;
}
else if (apr < minApr) {
apr = minApr;
}
}
}
// File contracts/interfaces/IDelegationUtils.sol
pragma solidity 0.8.4;
interface IDelegationUtils is IRewardUtils {
event Delegated(
address indexed user,
address indexed delegate,
uint256 shares,
uint256 totalDelegatedTo
);
event Undelegated(
address indexed user,
address indexed delegate,
uint256 shares,
uint256 totalDelegatedTo
);
event UpdatedDelegation(
address indexed user,
address indexed delegate,
bool delta,
uint256 shares,
uint256 totalDelegatedTo
);
function delegateVotingPower(address delegate)
external;
function undelegateVotingPower()
external;
}
// File contracts/DelegationUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements voting power delegation
abstract contract DelegationUtils is RewardUtils, IDelegationUtils {
/// @notice Called by the user to delegate voting power
/// @param delegate User address the voting power will be delegated to
function delegateVotingPower(address delegate)
external
override
{
mintReward();
require(
delegate != address(0) && delegate != msg.sender,
"Pool: Invalid delegate"
);
// Delegating users cannot use their voting power, so we are
// verifying that the delegate is not currently delegating. However,
// the delegate may delegate after they have been delegated to.
require(
userDelegate(delegate) == address(0),
"Pool: Delegate is delegating"
);
User storage user = users[msg.sender];
// Do not allow frequent delegation updates as that can be used to spam
// proposals
require(
user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp,
"Pool: Updated delegate recently"
);
user.lastDelegationUpdateTimestamp = block.timestamp;
uint256 userShares = userShares(msg.sender);
require(
userShares != 0,
"Pool: Have no shares to delegate"
);
address previousDelegate = userDelegate(msg.sender);
require(
previousDelegate != delegate,
"Pool: Already delegated"
);
if (previousDelegate != address(0)) {
// Need to revoke previous delegation
updateCheckpointArray(
users[previousDelegate].delegatedTo,
delegatedToUser(previousDelegate) - userShares
);
}
// Assign the new delegation
uint256 delegatedToUpdate = delegatedToUser(delegate) + userShares;
updateCheckpointArray(
users[delegate].delegatedTo,
delegatedToUpdate
);
// Record the new delegate for the user
updateAddressCheckpointArray(
user.delegates,
delegate
);
emit Delegated(
msg.sender,
delegate,
userShares,
delegatedToUpdate
);
}
/// @notice Called by the user to undelegate voting power
function undelegateVotingPower()
external
override
{
mintReward();
User storage user = users[msg.sender];
address previousDelegate = userDelegate(msg.sender);
require(
previousDelegate != address(0),
"Pool: Not delegated"
);
require(
user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp,
"Pool: Updated delegate recently"
);
user.lastDelegationUpdateTimestamp = block.timestamp;
uint256 userShares = userShares(msg.sender);
uint256 delegatedToUpdate = delegatedToUser(previousDelegate) - userShares;
updateCheckpointArray(
users[previousDelegate].delegatedTo,
delegatedToUpdate
);
updateAddressCheckpointArray(
user.delegates,
address(0)
);
emit Undelegated(
msg.sender,
previousDelegate,
userShares,
delegatedToUpdate
);
}
/// @notice Called internally when the user shares are updated to update
/// the delegated voting power
/// @dev User shares only get updated while staking or scheduling unstaking
/// @param shares Amount of shares that will be added/removed
/// @param delta Whether the shares will be added/removed (add for `true`,
/// and vice versa)
function updateDelegatedVotingPower(
uint256 shares,
bool delta
)
internal
{
address delegate = userDelegate(msg.sender);
if (delegate == address(0))
{
return;
}
uint256 currentDelegatedTo = delegatedToUser(delegate);
uint256 delegatedToUpdate = delta
? currentDelegatedTo + shares
: currentDelegatedTo - shares;
updateCheckpointArray(
users[delegate].delegatedTo,
delegatedToUpdate
);
emit UpdatedDelegation(
msg.sender,
delegate,
delta,
shares,
delegatedToUpdate
);
}
}
// File contracts/interfaces/ITransferUtils.sol
pragma solidity 0.8.4;
interface ITransferUtils is IDelegationUtils{
event Deposited(
address indexed user,
uint256 amount,
uint256 userUnstaked
);
event Withdrawn(
address indexed user,
uint256 amount,
uint256 userUnstaked
);
event CalculatingUserLocked(
address indexed user,
uint256 nextIndEpoch,
uint256 oldestLockedEpoch
);
event CalculatedUserLocked(
address indexed user,
uint256 amount
);
function depositRegular(uint256 amount)
external;
function withdrawRegular(uint256 amount)
external;
function precalculateUserLocked(
address userAddress,
uint256 noEpochsPerIteration
)
external
returns (bool finished);
function withdrawPrecalculated(uint256 amount)
external;
}
// File contracts/TransferUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements token transfer functionality
abstract contract TransferUtils is DelegationUtils, ITransferUtils {
/// @notice Called by the user to deposit tokens
/// @dev The user should approve the pool to spend at least `amount` tokens
/// before calling this.
/// The method is named `depositRegular()` to prevent potential confusion.
/// See `deposit()` for more context.
/// @param amount Amount to be deposited
function depositRegular(uint256 amount)
public
override
{
mintReward();
uint256 unstakedUpdate = users[msg.sender].unstaked + amount;
users[msg.sender].unstaked = unstakedUpdate;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transferFrom(msg.sender, address(this), amount));
emit Deposited(
msg.sender,
amount,
unstakedUpdate
);
}
/// @notice Called by the user to withdraw tokens to their wallet
/// @dev The user should call `userLocked()` beforehand to ensure that
/// they have at least `amount` unlocked tokens to withdraw.
/// The method is named `withdrawRegular()` to be consistent with the name
/// `depositRegular()`. See `depositRegular()` for more context.
/// @param amount Amount to be withdrawn
function withdrawRegular(uint256 amount)
public
override
{
mintReward();
withdraw(amount, userLocked(msg.sender));
}
/// @notice Called to calculate the locked tokens of a user by making
/// multiple transactions
/// @dev If the user updates their `user.shares` by staking/unstaking too
/// frequently (50+/week) in the last `REWARD_VESTING_PERIOD`, the
/// `userLocked()` call gas cost may exceed the block gas limit. In that
/// case, the user may call this method multiple times to have their locked
/// tokens calculated and use `withdrawPrecalculated()` to withdraw.
/// @param userAddress User address
/// @param noEpochsPerIteration Number of epochs per iteration
/// @return finished Calculation has finished in this call
function precalculateUserLocked(
address userAddress,
uint256 noEpochsPerIteration
)
external
override
returns (bool finished)
{
mintReward();
require(
noEpochsPerIteration > 0,
"Pool: Zero iteration window"
);
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
LockedCalculation storage lockedCalculation = userToLockedCalculation[userAddress];
// Reset the state if there was no calculation made in this epoch
if (lockedCalculation.initialIndEpoch != currentEpoch)
{
lockedCalculation.initialIndEpoch = currentEpoch;
lockedCalculation.nextIndEpoch = currentEpoch;
lockedCalculation.locked = 0;
}
uint256 indEpoch = lockedCalculation.nextIndEpoch;
uint256 locked = lockedCalculation.locked;
uint256 oldestLockedEpoch = getOldestLockedEpoch();
for (; indEpoch >= oldestLockedEpoch; indEpoch--)
{
if (lockedCalculation.nextIndEpoch >= indEpoch + noEpochsPerIteration)
{
lockedCalculation.nextIndEpoch = indEpoch;
lockedCalculation.locked = locked;
emit CalculatingUserLocked(
userAddress,
indEpoch,
oldestLockedEpoch
);
return false;
}
Reward storage lockedReward = epochIndexToReward[indEpoch];
if (lockedReward.atBlock != 0)
{
uint256 userSharesThen = userSharesAt(userAddress, lockedReward.atBlock);
locked += lockedReward.amount * userSharesThen / lockedReward.totalSharesThen;
}
}
lockedCalculation.nextIndEpoch = indEpoch;
lockedCalculation.locked = locked;
emit CalculatedUserLocked(userAddress, locked);
return true;
}
/// @notice Called by the user to withdraw after their locked token amount
/// is calculated with repeated calls to `precalculateUserLocked()`
/// @dev Only use `precalculateUserLocked()` and this method if
/// `withdrawRegular()` hits the block gas limit
/// @param amount Amount to be withdrawn
function withdrawPrecalculated(uint256 amount)
external
override
{
mintReward();
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
LockedCalculation storage lockedCalculation = userToLockedCalculation[msg.sender];
require(
lockedCalculation.initialIndEpoch == currentEpoch,
"Pool: Calculation not up to date"
);
require(
lockedCalculation.nextIndEpoch < getOldestLockedEpoch(),
"Pool: Calculation not complete"
);
withdraw(amount, lockedCalculation.locked);
}
/// @notice Called internally after the amount of locked tokens of the user
/// is determined
/// @param amount Amount to be withdrawn
/// @param userLocked Amount of locked tokens of the user
function withdraw(
uint256 amount,
uint256 userLocked
)
private
{
User storage user = users[msg.sender];
// Check if the user has `amount` unlocked tokens to withdraw
uint256 lockedAndVesting = userLocked + user.vesting;
uint256 userTotalFunds = user.unstaked + userStake(msg.sender);
require(
userTotalFunds >= lockedAndVesting + amount,
"Pool: Not enough unlocked funds"
);
require(
user.unstaked >= amount,
"Pool: Not enough unstaked funds"
);
// Carry on with the withdrawal
uint256 unstakedUpdate = user.unstaked - amount;
user.unstaked = unstakedUpdate;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transfer(msg.sender, amount));
emit Withdrawn(
msg.sender,
amount,
unstakedUpdate
);
}
}
// File contracts/interfaces/IStakeUtils.sol
pragma solidity 0.8.4;
interface IStakeUtils is ITransferUtils{
event Staked(
address indexed user,
uint256 amount,
uint256 mintedShares,
uint256 userUnstaked,
uint256 userShares,
uint256 totalShares,
uint256 totalStake
);
event ScheduledUnstake(
address indexed user,
uint256 amount,
uint256 shares,
uint256 scheduledFor,
uint256 userShares
);
event Unstaked(
address indexed user,
uint256 amount,
uint256 userUnstaked,
uint256 totalShares,
uint256 totalStake
);
function stake(uint256 amount)
external;
function depositAndStake(uint256 amount)
external;
function scheduleUnstake(uint256 amount)
external;
function unstake(address userAddress)
external
returns (uint256);
function unstakeAndWithdraw()
external;
}
// File contracts/StakeUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements staking functionality
abstract contract StakeUtils is TransferUtils, IStakeUtils {
/// @notice Called to stake tokens to receive pools in the share
/// @param amount Amount of tokens to stake
function stake(uint256 amount)
public
override
{
mintReward();
User storage user = users[msg.sender];
require(
user.unstaked >= amount,
"Pool: Amount exceeds unstaked"
);
uint256 userUnstakedUpdate = user.unstaked - amount;
user.unstaked = userUnstakedUpdate;
uint256 totalSharesNow = totalShares();
uint256 sharesToMint = amount * totalSharesNow / totalStake;
uint256 userSharesUpdate = userShares(msg.sender) + sharesToMint;
updateCheckpointArray(
user.shares,
userSharesUpdate
);
uint256 totalSharesUpdate = totalSharesNow + sharesToMint;
updateCheckpointArray(
poolShares,
totalSharesUpdate
);
totalStake += amount;
updateDelegatedVotingPower(sharesToMint, true);
emit Staked(
msg.sender,
amount,
sharesToMint,
userUnstakedUpdate,
userSharesUpdate,
totalSharesUpdate,
totalStake
);
}
/// @notice Convenience method to deposit and stake in a single transaction
/// @param amount Amount to be deposited and staked
function depositAndStake(uint256 amount)
external
override
{
depositRegular(amount);
stake(amount);
}
/// @notice Called by the user to schedule unstaking of their tokens
/// @dev While scheduling an unstake, `shares` get deducted from the user,
/// meaning that they will not receive rewards or voting power for them any
/// longer.
/// At unstaking-time, the user unstakes either the amount of tokens
/// scheduled to unstake, or the amount of tokens `shares` corresponds to
/// at unstaking-time, whichever is smaller. This corresponds to tokens
/// being scheduled to be unstaked not receiving any rewards, but being
/// subject to claim payouts.
/// In the instance that a claim has been paid out before an unstaking is
/// executed, the user may potentially receive rewards during
/// `unstakeWaitPeriod` (but not if there has not been a claim payout) but
/// the amount of tokens that they can unstake will not be able to exceed
/// the amount they scheduled the unstaking for.
/// @param amount Amount of tokens scheduled to unstake
function scheduleUnstake(uint256 amount)
external
override
{
mintReward();
uint256 userSharesNow = userShares(msg.sender);
uint256 totalSharesNow = totalShares();
uint256 userStaked = userSharesNow * totalStake / totalSharesNow;
require(
userStaked >= amount,
"Pool: Amount exceeds staked"
);
User storage user = users[msg.sender];
require(
user.unstakeScheduledFor == 0,
"Pool: Unexecuted unstake exists"
);
uint256 sharesToUnstake = amount * totalSharesNow / totalStake;
// This will only happen if the user wants to schedule an unstake for a
// few Wei
require(sharesToUnstake > 0, "Pool: Unstake amount too small");
uint256 unstakeScheduledFor = block.timestamp + unstakeWaitPeriod;
user.unstakeScheduledFor = unstakeScheduledFor;
user.unstakeAmount = amount;
user.unstakeShares = sharesToUnstake;
uint256 userSharesUpdate = userSharesNow - sharesToUnstake;
updateCheckpointArray(
user.shares,
userSharesUpdate
);
updateDelegatedVotingPower(sharesToUnstake, false);
emit ScheduledUnstake(
msg.sender,
amount,
sharesToUnstake,
unstakeScheduledFor,
userSharesUpdate
);
}
/// @notice Called to execute a pre-scheduled unstake
/// @dev Anyone can execute a matured unstake. This is to allow the user to
/// use bots, etc. to execute their unstaking as soon as possible.
/// @param userAddress User address
/// @return Amount of tokens that are unstaked
function unstake(address userAddress)
public
override
returns (uint256)
{
mintReward();
User storage user = users[userAddress];
require(
user.unstakeScheduledFor != 0,
"Pool: No unstake scheduled"
);
require(
user.unstakeScheduledFor < block.timestamp,
"Pool: Unstake not mature yet"
);
uint256 totalShares = totalShares();
uint256 unstakeAmount = user.unstakeAmount;
uint256 unstakeAmountByShares = user.unstakeShares * totalStake / totalShares;
// If there was a claim payout in between the scheduling and the actual
// unstake then the amount might be lower than expected at scheduling
// time
if (unstakeAmount > unstakeAmountByShares)
{
unstakeAmount = unstakeAmountByShares;
}
uint256 userUnstakedUpdate = user.unstaked + unstakeAmount;
user.unstaked = userUnstakedUpdate;
uint256 totalSharesUpdate = totalShares - user.unstakeShares;
updateCheckpointArray(
poolShares,
totalSharesUpdate
);
totalStake -= unstakeAmount;
user.unstakeAmount = 0;
user.unstakeShares = 0;
user.unstakeScheduledFor = 0;
emit Unstaked(
userAddress,
unstakeAmount,
userUnstakedUpdate,
totalSharesUpdate,
totalStake
);
return unstakeAmount;
}
/// @notice Convenience method to execute an unstake and withdraw to the
/// user's wallet in a single transaction
/// @dev The withdrawal will revert if the user has less than
/// `unstakeAmount` tokens that are withdrawable
function unstakeAndWithdraw()
external
override
{
withdrawRegular(unstake(msg.sender));
}
}
// File contracts/interfaces/IClaimUtils.sol
pragma solidity 0.8.4;
interface IClaimUtils is IStakeUtils {
event PaidOutClaim(
address indexed recipient,
uint256 amount,
uint256 totalStake
);
function payOutClaim(
address recipient,
uint256 amount
)
external;
}
// File contracts/ClaimUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements the insurance claim payout functionality
abstract contract ClaimUtils is StakeUtils, IClaimUtils {
/// @dev Reverts if the caller is not a claims manager
modifier onlyClaimsManager() {
require(
claimsManagerStatus[msg.sender],
"Pool: Caller not claims manager"
);
_;
}
/// @notice Called by a claims manager to pay out an insurance claim
/// @dev The claims manager is a trusted contract that is allowed to
/// withdraw as many tokens as it wants from the pool to pay out insurance
/// claims. Any kind of limiting logic (e.g., maximum amount of tokens that
/// can be withdrawn) is implemented at its end and is out of the scope of
/// this contract.
/// This will revert if the pool does not have enough staked funds.
/// @param recipient Recipient of the claim
/// @param amount Amount of tokens that will be paid out
function payOutClaim(
address recipient,
uint256 amount
)
external
override
onlyClaimsManager()
{
mintReward();
// totalStake should not go lower than 1
require(
totalStake > amount,
"Pool: Amount exceeds total stake"
);
totalStake -= amount;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transfer(recipient, amount));
emit PaidOutClaim(
recipient,
amount,
totalStake
);
}
}
// File contracts/interfaces/ITimelockUtils.sol
pragma solidity 0.8.4;
interface ITimelockUtils is IClaimUtils {
event DepositedByTimelockManager(
address indexed user,
uint256 amount,
uint256 userUnstaked
);
event DepositedVesting(
address indexed user,
uint256 amount,
uint256 start,
uint256 end,
uint256 userUnstaked,
uint256 userVesting
);
event VestedTimelock(
address indexed user,
uint256 amount,
uint256 userVesting
);
function deposit(
address source,
uint256 amount,
address userAddress
)
external;
function depositWithVesting(
address source,
uint256 amount,
address userAddress,
uint256 releaseStart,
uint256 releaseEnd
)
external;
function updateTimelockStatus(address userAddress)
external;
}
// File contracts/TimelockUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements vesting functionality
/// @dev The TimelockManager contract interfaces with this contract to transfer
/// API3 tokens that are locked under a vesting schedule.
/// This contract keeps its own type definitions, event declarations and state
/// variables for them to be easier to remove for a subDAO where they will
/// likely not be used.
abstract contract TimelockUtils is ClaimUtils, ITimelockUtils {
struct Timelock {
uint256 totalAmount;
uint256 remainingAmount;
uint256 releaseStart;
uint256 releaseEnd;
}
/// @notice Maps user addresses to timelocks
/// @dev This implies that a user cannot have multiple timelocks
/// transferred from the TimelockManager contract. This is acceptable
/// because TimelockManager is implemented in a way to not allow multiple
/// timelocks per user.
mapping(address => Timelock) public userToTimelock;
/// @notice Called by the TimelockManager contract to deposit tokens on
/// behalf of a user
/// @dev This method is only usable by `TimelockManager.sol`.
/// It is named as `deposit()` and not `depositAsTimelockManager()` for
/// example, because the TimelockManager is already deployed and expects
/// the `deposit(address,uint256,address)` interface.
/// @param source Token transfer source
/// @param amount Amount to be deposited
/// @param userAddress User that the tokens will be deposited for
function deposit(
address source,
uint256 amount,
address userAddress
)
external
override
{
require(
msg.sender == timelockManager,
"Pool: Caller not TimelockManager"
);
uint256 unstakedUpdate = users[userAddress].unstaked + amount;
users[userAddress].unstaked = unstakedUpdate;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transferFrom(source, address(this), amount));
emit DepositedByTimelockManager(
userAddress,
amount,
unstakedUpdate
);
}
/// @notice Called by the TimelockManager contract to deposit tokens on
/// behalf of a user on a linear vesting schedule
/// @dev Refer to `TimelockManager.sol` to see how this is used
/// @param source Token source
/// @param amount Token amount
/// @param userAddress Address of the user who will receive the tokens
/// @param releaseStart Vesting schedule starting time
/// @param releaseEnd Vesting schedule ending time
function depositWithVesting(
address source,
uint256 amount,
address userAddress,
uint256 releaseStart,
uint256 releaseEnd
)
external
override
{
require(
msg.sender == timelockManager,
"Pool: Caller not TimelockManager"
);
require(
userToTimelock[userAddress].remainingAmount == 0,
"Pool: User has active timelock"
);
require(
releaseEnd > releaseStart,
"Pool: Timelock start after end"
);
require(
amount != 0,
"Pool: Timelock amount zero"
);
uint256 unstakedUpdate = users[userAddress].unstaked + amount;
users[userAddress].unstaked = unstakedUpdate;
uint256 vestingUpdate = users[userAddress].vesting + amount;
users[userAddress].vesting = vestingUpdate;
userToTimelock[userAddress] = Timelock({
totalAmount: amount,
remainingAmount: amount,
releaseStart: releaseStart,
releaseEnd: releaseEnd
});
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transferFrom(source, address(this), amount));
emit DepositedVesting(
userAddress,
amount,
releaseStart,
releaseEnd,
unstakedUpdate,
vestingUpdate
);
}
/// @notice Called to release tokens vested by the timelock
/// @param userAddress Address of the user whose timelock status will be
/// updated
function updateTimelockStatus(address userAddress)
external
override
{
Timelock storage timelock = userToTimelock[userAddress];
require(
block.timestamp > timelock.releaseStart,
"Pool: Release not started yet"
);
require(
timelock.remainingAmount > 0,
"Pool: Timelock already released"
);
uint256 totalUnlocked;
if (block.timestamp >= timelock.releaseEnd)
{
totalUnlocked = timelock.totalAmount;
}
else
{
uint256 passedTime = block.timestamp - timelock.releaseStart;
uint256 totalTime = timelock.releaseEnd - timelock.releaseStart;
totalUnlocked = timelock.totalAmount * passedTime / totalTime;
}
uint256 previouslyUnlocked = timelock.totalAmount - timelock.remainingAmount;
uint256 newlyUnlocked = totalUnlocked - previouslyUnlocked;
User storage user = users[userAddress];
uint256 vestingUpdate = user.vesting - newlyUnlocked;
user.vesting = vestingUpdate;
timelock.remainingAmount -= newlyUnlocked;
emit VestedTimelock(
userAddress,
newlyUnlocked,
vestingUpdate
);
}
}
// File contracts/interfaces/IApi3Pool.sol
pragma solidity 0.8.4;
interface IApi3Pool is ITimelockUtils {
}
// File contracts/Api3Pool.sol
pragma solidity 0.8.4;
/// @title API3 pool contract
/// @notice Users can stake API3 tokens at the pool contract to be granted
/// shares. These shares are exposed to the Aragon-based DAO, giving the user
/// voting power at the DAO. Staking pays out weekly rewards that get unlocked
/// after a year, and staked funds are used to collateralize an insurance
/// product that is outside the scope of this contract.
/// @dev Functionalities of the contract are distributed to files that form a
/// chain of inheritance:
/// (1) Api3Pool.sol
/// (2) TimelockUtils.sol
/// (3) ClaimUtils.sol
/// (4) StakeUtils.sol
/// (5) TransferUtils.sol
/// (6) DelegationUtils.sol
/// (7) RewardUtils.sol
/// (8) GetterUtils.sol
/// (9) StateUtils.sol
contract Api3Pool is TimelockUtils, IApi3Pool {
/// @param api3TokenAddress API3 token contract address
/// @param timelockManagerAddress Timelock manager contract address
constructor(
address api3TokenAddress,
address timelockManagerAddress
)
StateUtils(
api3TokenAddress,
timelockManagerAddress
)
{}
}
|
Convenience method to execute an unstake and withdraw to the user's wallet in a single transaction The withdrawal will revert if the user has less than `unstakeAmount` tokens that are withdrawable
|
function unstakeAndWithdraw()
external
override
{
withdrawRegular(unstake(msg.sender));
}
| 2,456,849 |
//Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// implements the ERC721 standard
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
// keeps track of the number of token issued
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// Accesing the Ownable method ensures that only the creator of the smart contract can interact with it
contract FundNFT is ERC721, Ownable {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private _tokenIds;
// Optional mapping for token URI's
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURIextended;
// the name and symbol for the NFT
constructor() ERC721("FUNDayli", "FUND") {}
function setBaseURI(string memory baseURI_) external onlyOwner() {
_baseURIextended = baseURI_;
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
/*function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query of nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// if there is no base URI, returns the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// if both are set, concatenate the baseURI and tokenURI (via abi.encodePacked)
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// if there is baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}*/
function mint(
address _to,
uint256 _tokenId,
string memory tokenURI_
) external onlyOwner() {
_mint(_to, _tokenId);
_setTokenURI(_tokenId, tokenURI_);
}
// Create a function to mint/create the NFT
// receiver takes a type of address. This is the wallet address of the user that should receive the NFT minted using the smart contract
// tokenURI takes a string that contains metadata about the NFT
function createNFT(address receiver, string memory tokenURI) public onlyOwner returns (uint256) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(receiver, newItemId);
_setTokenURI(newItemId, tokenURI);
// returns the id for the newly created token
return newItemId;
}
}
|
Create a function to mint/create the NFT receiver takes a type of address. This is the wallet address of the user that should receive the NFT minted using the smart contract tokenURI takes a string that contains metadata about the NFT returns the id for the newly created token
|
function createNFT(address receiver, string memory tokenURI) public onlyOwner returns (uint256) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(receiver, newItemId);
_setTokenURI(newItemId, tokenURI);
return newItemId;
}
| 1,827,786 |
pragma solidity ^0.5.16;
import "./VToken.sol";
import "./ErrorReporter.sol";
import "./PriceOracle.sol";
import "./ComptrollerInterface.sol";
import "./ComptrollerStorage.sol";
import "./Unitroller.sol";
import "./Governance/XVS.sol";
import "./VAI/VAI.sol";
/**
* @title Venus's Comptroller Contract
* @author Venus
*/
contract Comptroller is ComptrollerV4Storage, ComptrollerInterfaceG2, ComptrollerErrorReporter, ExponentialNoError {
/// @notice Emitted when an admin supports a market
event MarketListed(VToken vToken);
/// @notice Emitted when an account enters a market
event MarketEntered(VToken vToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(VToken vToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(VToken vToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when VAI Vault info is changed
event NewVAIVaultInfo(address vault_, uint releaseStartBlock_, uint releaseInterval_);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(VToken vToken, string action, bool pauseState);
/// @notice Emitted when Venus VAI rate is changed
event NewVenusVAIRate(uint oldVenusVAIRate, uint newVenusVAIRate);
/// @notice Emitted when Venus VAI Vault rate is changed
event NewVenusVAIVaultRate(uint oldVenusVAIVaultRate, uint newVenusVAIVaultRate);
/// @notice Emitted when a new Venus speed is calculated for a market
event VenusSpeedUpdated(VToken indexed vToken, uint newSpeed);
/// @notice Emitted when XVS is distributed to a supplier
event DistributedSupplierVenus(VToken indexed vToken, address indexed supplier, uint venusDelta, uint venusSupplyIndex);
/// @notice Emitted when XVS is distributed to a borrower
event DistributedBorrowerVenus(VToken indexed vToken, address indexed borrower, uint venusDelta, uint venusBorrowIndex);
/// @notice Emitted when XVS is distributed to a VAI minter
event DistributedVAIMinterVenus(address indexed vaiMinter, uint venusDelta, uint venusVAIMintIndex);
/// @notice Emitted when XVS is distributed to VAI Vault
event DistributedVAIVaultVenus(uint amount);
/// @notice Emitted when VAIController is changed
event NewVAIController(VAIControllerInterface oldVAIController, VAIControllerInterface newVAIController);
/// @notice Emitted when VAI mint rate is changed by admin
event NewVAIMintRate(uint oldVAIMintRate, uint newVAIMintRate);
/// @notice Emitted when protocol state is changed by admin
event ActionProtocolPaused(bool state);
/// @notice Emitted when borrow cap for a vToken is changed
event NewBorrowCap(VToken indexed vToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when treasury guardian is changed
event NewTreasuryGuardian(address oldTreasuryGuardian, address newTreasuryGuardian);
/// @notice Emitted when treasury address is changed
event NewTreasuryAddress(address oldTreasuryAddress, address newTreasuryAddress);
/// @notice Emitted when treasury percent is changed
event NewTreasuryPercent(uint oldTreasuryPercent, uint newTreasuryPercent);
/// @notice The initial Venus index for a market
uint224 public constant venusInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
modifier onlyProtocolAllowed {
require(!protocolPaused, "protocol is paused");
_;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can");
_;
}
modifier onlyListedMarket(VToken vToken) {
require(markets[address(vToken)].isListed, "venus market is not listed");
_;
}
modifier validPauseState(bool state) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can");
require(msg.sender == admin || state == true, "only admin can unpause");
_;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (VToken[] memory) {
return accountAssets[account];
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param vToken The vToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, VToken vToken) external view returns (bool) {
return markets[address(vToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param vTokens The list of addresses of the vToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata vTokens) external returns (uint[] memory) {
uint len = vTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
results[i] = uint(addToMarketInternal(VToken(vTokens[i]), msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param vToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(VToken vToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(vToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower]) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(vToken);
emit MarketEntered(vToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param vTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address vTokenAddress) external returns (uint) {
VToken vToken = VToken(vTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the vToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(vTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(vToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set vToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete vToken from the account’s list of assets */
// In order to delete vToken, copy last item in list to location of item to be removed, reduce length by 1
VToken[] storage userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint i;
for (; i < len; i++) {
if (userAssetList[i] == vToken) {
userAssetList[i] = userAssetList[len - 1];
userAssetList.length--;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(i < len);
emit MarketExited(vToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param vToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address vToken, address minter, uint mintAmount) external onlyProtocolAllowed returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[vToken], "mint is paused");
// Shh - currently unused
mintAmount;
if (!markets[vToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateVenusSupplyIndex(vToken);
distributeSupplierVenus(vToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param vToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address vToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
vToken;
minter;
actualMintAmount;
mintTokens;
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param vToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of vTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address vToken, address redeemer, uint redeemTokens) external onlyProtocolAllowed returns (uint) {
uint allowed = redeemAllowedInternal(vToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateVenusSupplyIndex(vToken);
distributeSupplierVenus(vToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address vToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[vToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[vToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, VToken(vToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall != 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param vToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address vToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
vToken;
redeemer;
// Require tokens is zero or amount is also zero
require(redeemTokens != 0 || redeemAmount == 0, "redeemTokens zero");
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param vToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[vToken], "borrow is paused");
if (!markets[vToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[vToken].accountMembership[borrower]) {
// only vTokens may call borrowAllowed if borrower not in market
require(msg.sender == vToken, "sender must be vToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(VToken(vToken), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
}
if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[vToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = VToken(vToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall != 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()});
updateVenusBorrowIndex(vToken, borrowIndex);
distributeBorrowerVenus(vToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param vToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address vToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
vToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param vToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would repay the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address vToken,
address payer,
address borrower,
uint repayAmount) external onlyProtocolAllowed returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[vToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()});
updateVenusBorrowIndex(vToken, borrowIndex);
distributeBorrowerVenus(vToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param vToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address vToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
vToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param vTokenBorrowed Asset which was borrowed by the borrower
* @param vTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address vTokenBorrowed,
address vTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external onlyProtocolAllowed returns (uint) {
// Shh - currently unused
liquidator;
if (!(markets[vTokenBorrowed].isListed || address(vTokenBorrowed) == address(vaiController)) || !markets[vTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(0), 0, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance;
if (address(vTokenBorrowed) != address(vaiController)) {
borrowBalance = VToken(vTokenBorrowed).borrowBalanceStored(borrower);
} else {
borrowBalance = mintedVAIs[borrower];
}
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param vTokenBorrowed Asset which was borrowed by the borrower
* @param vTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address vTokenBorrowed,
address vTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
vTokenBorrowed;
vTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param vTokenCollateral Asset which was used as collateral and will be seized
* @param vTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address vTokenCollateral,
address vTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external onlyProtocolAllowed returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
// We've added VAIController as a borrowed token list check for seize
if (!markets[vTokenCollateral].isListed || !(markets[vTokenBorrowed].isListed || address(vTokenBorrowed) == address(vaiController))) {
return uint(Error.MARKET_NOT_LISTED);
}
if (VToken(vTokenCollateral).comptroller() != VToken(vTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateVenusSupplyIndex(vTokenCollateral);
distributeSupplierVenus(vTokenCollateral, borrower);
distributeSupplierVenus(vTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param vTokenCollateral Asset which was used as collateral and will be seized
* @param vTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address vTokenCollateral,
address vTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
vTokenCollateral;
vTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param vToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of vTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address vToken, address src, address dst, uint transferTokens) external onlyProtocolAllowed returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(vToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateVenusSupplyIndex(vToken);
distributeSupplierVenus(vToken, src);
distributeSupplierVenus(vToken, dst);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param vToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of vTokens to transfer
*/
function transferVerify(address vToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
vToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `vTokenBalance` is the number of vTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint vTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param vTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address vTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(vTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param vTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral vToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
VToken vTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
VToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
VToken asset = assets[i];
// Read the balances and exchange rate from the vToken
(oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> bnb (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * vTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.vTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with vTokenModify
if (asset == vTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
vars.sumBorrowPlusEffects = add_(vars.sumBorrowPlusEffects, mintedVAIs[account]);
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in vToken.liquidateBorrowFresh)
* @param vTokenBorrowed The address of the borrowed vToken
* @param vTokenCollateral The address of the collateral vToken
* @param actualRepayAmount The amount of vTokenBorrowed underlying to convert into vTokenCollateral tokens
* @return (errorCode, number of vTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address vTokenBorrowed, address vTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(VToken(vTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(VToken(vTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = VToken(vTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in vToken.liquidateBorrowFresh)
* @param vTokenCollateral The address of the collateral vToken
* @param actualRepayAmount The amount of vTokenBorrowed underlying to convert into vTokenCollateral tokens
* @return (errorCode, number of vTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateVAICalculateSeizeTokens(address vTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = 1e18; // Note: this is VAI
uint priceCollateralMantissa = oracle.getUnderlyingPrice(VToken(vTokenCollateral));
if (priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = VToken(vTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, newCloseFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param vToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(VToken vToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(vToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(vToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(vToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param vToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(VToken vToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(vToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
vToken.isVToken(); // Sanity check to make sure its really a VToken
// Note that isVenus is not in active use anymore
markets[address(vToken)] = Market({isListed: true, isVenus: false, collateralFactorMantissa: 0});
_addMarketInternal(vToken);
emit MarketListed(vToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(VToken vToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != vToken, "market already added");
}
allMarkets.push(vToken);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, newPauseGuardian);
return uint(Error.NO_ERROR);
}
/**
* @notice Set the given borrow caps for the given vToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param vTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(VToken[] calldata vTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = vTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(vTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(vTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external onlyAdmin {
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Set whole protocol pause/unpause state
*/
function _setProtocolPaused(bool state) public validPauseState(state) returns(bool) {
protocolPaused = state;
emit ActionProtocolPaused(state);
return state;
}
/**
* @notice Sets a new VAI controller
* @dev Admin function to set a new VAI controller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setVAIController(VAIControllerInterface vaiController_) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_VAICONTROLLER_OWNER_CHECK);
}
VAIControllerInterface oldRate = vaiController;
vaiController = vaiController_;
emit NewVAIController(oldRate, vaiController_);
}
function _setVAIMintRate(uint newVAIMintRate) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_VAI_MINT_RATE_CHECK);
}
uint oldVAIMintRate = vaiMintRate;
vaiMintRate = newVAIMintRate;
emit NewVAIMintRate(oldVAIMintRate, newVAIMintRate);
return uint(Error.NO_ERROR);
}
function _setTreasuryData(address newTreasuryGuardian, address newTreasuryAddress, uint newTreasuryPercent) external returns (uint) {
// Check caller is admin
if (!(msg.sender == admin || msg.sender == treasuryGuardian)) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_TREASURY_OWNER_CHECK);
}
require(newTreasuryPercent < 1e18, "treasury percent cap overflow");
address oldTreasuryGuardian = treasuryGuardian;
address oldTreasuryAddress = treasuryAddress;
uint oldTreasuryPercent = treasuryPercent;
treasuryGuardian = newTreasuryGuardian;
treasuryAddress = newTreasuryAddress;
treasuryPercent = newTreasuryPercent;
emit NewTreasuryGuardian(oldTreasuryGuardian, newTreasuryGuardian);
emit NewTreasuryAddress(oldTreasuryAddress, newTreasuryAddress);
emit NewTreasuryPercent(oldTreasuryPercent, newTreasuryPercent);
return uint(Error.NO_ERROR);
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can");
require(unitroller._acceptImplementation() == 0, "not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/*** Venus Distribution ***/
function setVenusSpeedInternal(VToken vToken, uint venusSpeed) internal {
uint currentVenusSpeed = venusSpeeds[address(vToken)];
if (currentVenusSpeed != 0) {
// note that XVS speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()});
updateVenusSupplyIndex(address(vToken));
updateVenusBorrowIndex(address(vToken), borrowIndex);
} else if (venusSpeed != 0) {
// Add the XVS market
Market storage market = markets[address(vToken)];
require(market.isListed == true, "venus market is not listed");
if (venusSupplyState[address(vToken)].index == 0 && venusSupplyState[address(vToken)].block == 0) {
venusSupplyState[address(vToken)] = VenusMarketState({
index: venusInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (venusBorrowState[address(vToken)].index == 0 && venusBorrowState[address(vToken)].block == 0) {
venusBorrowState[address(vToken)] = VenusMarketState({
index: venusInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
if (currentVenusSpeed != venusSpeed) {
venusSpeeds[address(vToken)] = venusSpeed;
emit VenusSpeedUpdated(vToken, venusSpeed);
}
}
/**
* @notice Accrue XVS to the market by updating the supply index
* @param vToken The market whose supply index to update
*/
function updateVenusSupplyIndex(address vToken) internal {
VenusMarketState storage supplyState = venusSupplyState[vToken];
uint supplySpeed = venusSpeeds[vToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = VToken(vToken).totalSupply();
uint venusAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(venusAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
venusSupplyState[vToken] = VenusMarketState({
index: safe224(index.mantissa, "new index overflows"),
block: safe32(blockNumber, "block number overflows")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number overflows");
}
}
/**
* @notice Accrue XVS to the market by updating the borrow index
* @param vToken The market whose borrow index to update
*/
function updateVenusBorrowIndex(address vToken, Exp memory marketBorrowIndex) internal {
VenusMarketState storage borrowState = venusBorrowState[vToken];
uint borrowSpeed = venusSpeeds[vToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(VToken(vToken).totalBorrows(), marketBorrowIndex);
uint venusAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(venusAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
venusBorrowState[vToken] = VenusMarketState({
index: safe224(index.mantissa, "new index overflows"),
block: safe32(blockNumber, "block number overflows")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number overflows");
}
}
/**
* @notice Calculate XVS accrued by a supplier and possibly transfer it to them
* @param vToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute XVS to
*/
function distributeSupplierVenus(address vToken, address supplier) internal {
if (address(vaiVaultAddress) != address(0)) {
releaseToVault();
}
VenusMarketState storage supplyState = venusSupplyState[vToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: venusSupplierIndex[vToken][supplier]});
venusSupplierIndex[vToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = venusInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = VToken(vToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(venusAccrued[supplier], supplierDelta);
venusAccrued[supplier] = supplierAccrued;
emit DistributedSupplierVenus(VToken(vToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate XVS accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param vToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute XVS to
*/
function distributeBorrowerVenus(address vToken, address borrower, Exp memory marketBorrowIndex) internal {
if (address(vaiVaultAddress) != address(0)) {
releaseToVault();
}
VenusMarketState storage borrowState = venusBorrowState[vToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: venusBorrowerIndex[vToken][borrower]});
venusBorrowerIndex[vToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(VToken(vToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(venusAccrued[borrower], borrowerDelta);
venusAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerVenus(VToken(vToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Calculate XVS accrued by a VAI minter and possibly transfer it to them
* @dev VAI minters will not begin to accrue until after the first interaction with the protocol.
* @param vaiMinter The address of the VAI minter to distribute XVS to
*/
function distributeVAIMinterVenus(address vaiMinter) public {
if (address(vaiVaultAddress) != address(0)) {
releaseToVault();
}
if (address(vaiController) != address(0)) {
uint vaiMinterAccrued;
uint vaiMinterDelta;
uint vaiMintIndexMantissa;
uint err;
(err, vaiMinterAccrued, vaiMinterDelta, vaiMintIndexMantissa) = vaiController.calcDistributeVAIMinterVenus(vaiMinter);
if (err == uint(Error.NO_ERROR)) {
venusAccrued[vaiMinter] = vaiMinterAccrued;
emit DistributedVAIMinterVenus(vaiMinter, vaiMinterDelta, vaiMintIndexMantissa);
}
}
}
/**
* @notice Claim all the xvs accrued by holder in all markets and VAI
* @param holder The address to claim XVS for
*/
function claimVenus(address holder) public {
return claimVenus(holder, allMarkets);
}
/**
* @notice Claim all the xvs accrued by holder in the specified markets
* @param holder The address to claim XVS for
* @param vTokens The list of markets to claim XVS in
*/
function claimVenus(address holder, VToken[] memory vTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimVenus(holders, vTokens, true, true);
}
/**
* @notice Claim all xvs accrued by the holders
* @param holders The addresses to claim XVS for
* @param vTokens The list of markets to claim XVS in
* @param borrowers Whether or not to claim XVS earned by borrowing
* @param suppliers Whether or not to claim XVS earned by supplying
*/
function claimVenus(address[] memory holders, VToken[] memory vTokens, bool borrowers, bool suppliers) public {
uint j;
if(address(vaiController) != address(0)) {
vaiController.updateVenusVAIMintIndex();
}
for (j = 0; j < holders.length; j++) {
distributeVAIMinterVenus(holders[j]);
venusAccrued[holders[j]] = grantXVSInternal(holders[j], venusAccrued[holders[j]]);
}
for (uint i = 0; i < vTokens.length; i++) {
VToken vToken = vTokens[i];
require(markets[address(vToken)].isListed, "not listed market");
if (borrowers) {
Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()});
updateVenusBorrowIndex(address(vToken), borrowIndex);
for (j = 0; j < holders.length; j++) {
distributeBorrowerVenus(address(vToken), holders[j], borrowIndex);
venusAccrued[holders[j]] = grantXVSInternal(holders[j], venusAccrued[holders[j]]);
}
}
if (suppliers) {
updateVenusSupplyIndex(address(vToken));
for (j = 0; j < holders.length; j++) {
distributeSupplierVenus(address(vToken), holders[j]);
venusAccrued[holders[j]] = grantXVSInternal(holders[j], venusAccrued[holders[j]]);
}
}
}
}
/**
* @notice Transfer XVS to the user
* @dev Note: If there is not enough XVS, we do not perform the transfer all.
* @param user The address of the user to transfer XVS to
* @param amount The amount of XVS to (possibly) transfer
* @return The amount of XVS which was NOT transferred to the user
*/
function grantXVSInternal(address user, uint amount) internal returns (uint) {
XVS xvs = XVS(getXVSAddress());
uint venusRemaining = xvs.balanceOf(address(this));
if (amount > 0 && amount <= venusRemaining) {
xvs.transfer(user, amount);
return 0;
}
return amount;
}
/*** Venus Distribution Admin ***/
/**
* @notice Set the amount of XVS distributed per block to VAI Mint
* @param venusVAIRate_ The amount of XVS wei per block to distribute to VAI Mint
*/
function _setVenusVAIRate(uint venusVAIRate_) public onlyAdmin {
uint oldVAIRate = venusVAIRate;
venusVAIRate = venusVAIRate_;
emit NewVenusVAIRate(oldVAIRate, venusVAIRate_);
}
/**
* @notice Set the amount of XVS distributed per block to VAI Vault
* @param venusVAIVaultRate_ The amount of XVS wei per block to distribute to VAI Vault
*/
function _setVenusVAIVaultRate(uint venusVAIVaultRate_) public onlyAdmin {
uint oldVenusVAIVaultRate = venusVAIVaultRate;
venusVAIVaultRate = venusVAIVaultRate_;
emit NewVenusVAIVaultRate(oldVenusVAIVaultRate, venusVAIVaultRate_);
}
/**
* @notice Set the VAI Vault infos
* @param vault_ The address of the VAI Vault
* @param releaseStartBlock_ The start block of release to VAI Vault
* @param minReleaseAmount_ The minimum release amount to VAI Vault
*/
function _setVAIVaultInfo(address vault_, uint256 releaseStartBlock_, uint256 minReleaseAmount_) public onlyAdmin {
vaiVaultAddress = vault_;
releaseStartBlock = releaseStartBlock_;
minReleaseAmount = minReleaseAmount_;
emit NewVAIVaultInfo(vault_, releaseStartBlock_, minReleaseAmount_);
}
/**
* @notice Set XVS speed for a single market
* @param vToken The market whose XVS speed to update
* @param venusSpeed New XVS speed for market
*/
function _setVenusSpeed(VToken vToken, uint venusSpeed) public {
require(adminOrInitializing(), "only admin can set venus speed");
setVenusSpeedInternal(vToken, venusSpeed);
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (VToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the XVS token
* @return The address of XVS
*/
function getXVSAddress() public view returns (address) {
return 0xcF6BB5389c92Bdda8a3747Ddb454cB7a64626C63;
}
/*** VAI functions ***/
/**
* @notice Set the minted VAI amount of the `owner`
* @param owner The address of the account to set
* @param amount The amount of VAI to set to the account
* @return The number of minted VAI by `owner`
*/
function setMintedVAIOf(address owner, uint amount) external onlyProtocolAllowed returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintVAIGuardianPaused && !repayVAIGuardianPaused, "VAI is paused");
// Check caller is vaiController
if (msg.sender != address(vaiController)) {
return fail(Error.REJECTION, FailureInfo.SET_MINTED_VAI_REJECTION);
}
mintedVAIs[owner] = amount;
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer XVS to VAI Vault
*/
function releaseToVault() public {
if(releaseStartBlock == 0 || getBlockNumber() < releaseStartBlock) {
return;
}
XVS xvs = XVS(getXVSAddress());
uint256 xvsBalance = xvs.balanceOf(address(this));
if(xvsBalance == 0) {
return;
}
uint256 actualAmount;
uint256 deltaBlocks = sub_(getBlockNumber(), releaseStartBlock);
// releaseAmount = venusVAIVaultRate * deltaBlocks
uint256 _releaseAmount = mul_(venusVAIVaultRate, deltaBlocks);
if (_releaseAmount < minReleaseAmount) {
return;
}
if (xvsBalance >= _releaseAmount) {
actualAmount = _releaseAmount;
} else {
actualAmount = xvsBalance;
}
releaseStartBlock = getBlockNumber();
xvs.transfer(vaiVaultAddress, actualAmount);
emit DistributedVAIVaultVenus(actualAmount);
IVAIVault(vaiVaultAddress).updatePendingRewards();
}
}
|
Add assets to be included in account liquidity calculation vTokens The list of addresses of the vToken markets to be enabled return Success indicator for whether each corresponding market was entered/
|
function enterMarkets(address[] calldata vTokens) external returns (uint[] memory) {
uint len = vTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
results[i] = uint(addToMarketInternal(VToken(vTokens[i]), msg.sender));
}
return results;
}
| 1,063,590 |
pragma solidity ^0.4.8;
// Utility contract for ownership functionality.
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
/**
* @author Ben Hodgson
*
* Sport Betting Contract
*
*/
contract Betting is owned {
using SafeMath for uint;
bytes32 public test;
bytes32 public verify;
// store the authorized leagues
mapping (bytes32 => uint) public leagueIndex;
League[] public leagues;
// constants that control contract functionality
uint public stakeAmount = 10;
struct League {
address host;
string name;
// store the matches
mapping (bytes32 => uint) matchIndex;
Match[] matches;
// store the authorized arbiters
mapping(address => uint) arbiterIndex;
Arbiter[] arbiters;
}
struct Bet {
bytes32 matchHash;
address owner;
string betOnTeam;
uint amount;
bool withdrawn;
}
struct Team {
string name;
uint score;
}
struct Match {
bytes32 hash;
string homeTeam;
string awayTeam;
string league;
uint startTime;
uint commits;
uint reveals;
bool finalized;
mapping (address => uint) betterIndex;
Bet[] bets;
mapping (address => bytes32) resultHash;
mapping (address => bytes32) revealHash;
mapping (bytes32 => uint) resultCountIndex;
Count[] resultCount;
uint betPool;
}
struct Result {
bytes32 hash;
bytes32 matchHash;
Team homeTeam;
Team awayTeam;
}
struct Count {
uint value;
Result matchResult;
}
struct Arbiter {
address id;
uint commits;
uint reveals;
}
constructor() public {
addLeague(owner, "Genesis");
}
/**
* Add League
*
* Make `makerAddress` a league named `leagueName`
*
* @param makerAddress ethereum address to be added as the league host
* @param leagueName public name for that league
*/
function addLeague(
address makerAddress,
string leagueName
) onlyOwner public {
bytes32 leagueHash = keccak256(abi.encodePacked(leagueName));
// Check existence of league.
uint index = leagueIndex[leagueHash];
if (index == 0) {
// Add league to ID list.
leagueIndex[leagueHash] = leagues.length;
// index gets leagues.length, then leagues.length++
index = leagues.length++;
}
// Create and update storage
League storage m = leagues[index];
m.host = makerAddress;
m.name = leagueName;
}
/**
* Remove a league
*
* @notice Remove match maker designation from `makerAddress` address.
*
* @param leagueName the name of the league to be removed
*/
function removeleague(string leagueName) onlyOwner public {
bytes32 leagueHash = validateLeague(leagueName);
// Rewrite the match maker storage to move the 'gap' to the end.
for (uint i = leagueIndex[leagueHash];
i < leagues.length - 1; i++) {
leagues[i] = leagues[i+1];
leagueIndex[keccak256(abi.encodePacked(leagues[i].name))] = i;
}
// Delete the last match maker
delete leagueIndex[leagueHash];
delete leagues[leagues.length-1];
leagues.length--;
}
/**
* Add an Arbiter to a specified League
*
* Make `arbiterAddress` an arbiter for league `leagueName`
*
* @param arbiterAddress ethereum address to be added as a league arbiter
* @param leagueName public name for that league
*/
function addLeagueArbiter(
address arbiterAddress,
string leagueName
) onlyOwner public {
bytes32 leagueHash = validateLeague(leagueName);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
// Check existence of league arbiter
uint index = thisLeague.arbiterIndex[arbiterAddress];
if (index == 0) {
// Add league arbiter to ID list.
thisLeague.arbiterIndex[arbiterAddress] = thisLeague.arbiters.length;
// index gets length, then length++
index = thisLeague.arbiters.length++;
}
// Create and update storage
Arbiter storage a = thisLeague.arbiters[index];
a.id = arbiterAddress;
a.commits = 0;
a.reveals = 0;
}
/**
* Remove an arbiter from a league
*
* @notice Remove arbiter designation from `arbiterAddress` address.
*
* @param arbiterAddress ethereum address to be removed as league arbiter
* @param leagueName the name of the league
*/
function removeLeagueArbiter(
address arbiterAddress,
string leagueName
) onlyOwner public {
bytes32 leagueHash = validateLeagueArbiter(arbiterAddress, leagueName);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
uint index = thisLeague.arbiterIndex[arbiterAddress];
// Rewrite storage to move the 'gap' to the end.
for (uint i = index;
i < thisLeague.arbiters.length - 1; i++) {
thisLeague.arbiters[i] = thisLeague.arbiters[i+1];
thisLeague.arbiterIndex[thisLeague.arbiters[i].id] = i;
}
// Delete the tail
delete thisLeague.arbiterIndex[arbiterAddress];
delete thisLeague.arbiters[thisLeague.arbiters.length-1];
thisLeague.arbiters.length--;
}
/**
* Allows only match makers to create a match
*
* @param homeTeam the home team competing in the match
* @param awayTeam the away team competing in the match
* @param league the match pertains to
* @param startTime the time the match begins
*/
function createMatch(
string homeTeam,
string awayTeam,
string league,
uint startTime
) public returns (bytes32 matchHash) {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
// require this is the league host
require(thisLeague.host == msg.sender, "Sender is not the league host");
// TODO require match hasn't already started
//require(startTime > now + 1 hours, "Match already started");
matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
uint index = thisLeague.matchIndex[matchHash];
if (index == 0) {
thisLeague.matchIndex[matchHash] = thisLeague.matches.length;
index = thisLeague.matches.length++;
}
// Create and update storage
Match storage newMatch = thisLeague.matches[index];
newMatch.hash = matchHash;
newMatch.homeTeam = homeTeam;
newMatch.awayTeam = awayTeam;
newMatch.league = league;
newMatch.startTime = startTime;
newMatch.finalized = false;
}
/**
* Allows only match makers to remove a match. Refunds all bets placed
* on the match.
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function removeMatch(
string homeTeam,
string awayTeam,
string league,
uint startTime
) public {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
// require this is the league host
require(thisLeague.host == msg.sender, "Sender is not the league host");
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
uint index = thisLeague.matchIndex[matchHash];
require(thisLeague.matches[index].hash == matchHash, "Invalid match");
// require the match hasn't started
require(now < thisLeague.matches[index].startTime, "Match has started");
// refund bets
for (uint b = 0; b < thisLeague.matches[index].bets.length; b++) {
if (!thisLeague.matches[index].bets[b].withdrawn) {
Bet storage thisBet = thisLeague.matches[index].bets[b];
thisBet.withdrawn = true;
thisBet.owner.transfer(thisBet.amount);
}
}
// Rewrite the matches storage to move the 'gap' to the end.
for (uint i = thisLeague.matchIndex[matchHash];
i < thisLeague.matches.length - 1; i++) {
thisLeague.matches[i] = thisLeague.matches[i + 1];
thisLeague.matchIndex[thisLeague.matches[i].hash] = i;
}
// Delete the last match
delete thisLeague.matchIndex[matchHash];
delete thisLeague.matches[thisLeague.matches.length - 1];
thisLeague.matches.length--;
}
/**
* Returns the match information that bears the hash generated with the user
* input parameters
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the name of the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function getMatch(
string homeTeam,
string awayTeam,
string league,
uint startTime
) view public returns(bytes32, string, string, string, uint, bool) {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
uint index = thisLeague.matchIndex[matchHash];
require(thisLeague.matches[index].hash == matchHash, "Invalid match");
Match storage retMatch = thisLeague.matches[index];
return (
retMatch.hash,
retMatch.homeTeam,
retMatch.awayTeam,
retMatch.league,
retMatch.startTime,
retMatch.finalized
);
}
/**
* Allow only arbiters for the specified 'league' to commit match results
*
* @param homeTeam the home team competing in the match
* @param awayTeam the away team competing in the match
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
* @param resultHash the hash of the result entered by the arbiter
*/
function commitMatchResult(
string homeTeam,
string awayTeam,
string league,
uint startTime,
bytes32 resultHash
) public payable {
bytes32 leagueHash = validateLeagueArbiter(msg.sender, league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// make sure match is valid
require(thisMatch.hash == matchHash, "Invalid match");
// require match is finished
require(now > startTime + 95, "Match is not finished");
// require match still needs more commits
require(
thisLeague.arbiters.length.mul(8).div(10) >= thisMatch.commits,
"Match not accepting more commits"
);
// only allow one result submission per address
require(thisMatch.resultHash[msg.sender] == 0, "Result already committed");
// must stake 'stakeAmount' to commit result
require(msg.value >= stakeAmount, "Must stake 10 Wei to commit result");
storeMatchCommit(msg.sender, league, matchHash, resultHash);
}
/**
* Allow only arbiters for the specified 'league' to reveal match results
*
* @param homeTeam the home team competing in the match
* @param awayTeam the away team competing in the match
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
* @param salt the hash added in the msg.sender's result commit
* @param homeScore the score for the home team
* @param awayScore the score for the away team
*/
function revealMatchResult(
string homeTeam,
string awayTeam,
string league,
uint startTime,
bytes32 salt,
uint homeScore,
uint awayScore
) public {
bytes32 leagueHash = validateLeagueArbiter(msg.sender, league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// make sure match is valid
require(thisMatch.hash == matchHash, "Invalid match");
// require match is finished
require(now > startTime + 95, "Match is not finished");
// require match doesn't need more commits
require(
thisLeague.arbiters.length.mul(8).div(10) < thisMatch.commits,
"Match is still accepting commits"
);
// require msg.sender committed a result
require(
thisMatch.resultHash[msg.sender] != 0,
"Result never committed or stake already withdrawn"
);
verifyMatchReveal(msg.sender, league, matchHash, salt, homeScore, awayScore);
}
/**
* Allows only match makers that submitted a correct result for a match
* withdraw a small reward taken from the bet pool for the match.
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function withdrawResult(
string homeTeam,
string awayTeam,
string league,
uint startTime
) public {
bytes32 leagueHash = validateLeagueArbiter(msg.sender, league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// require the match is finalized
require(thisMatch.finalized, "Match result is not finalized");
bytes32 finalResultHash = findFinalResultHash(homeTeam, awayTeam, league, startTime);
// require they revealed the correct result
require(
finalResultHash == thisMatch.revealHash[msg.sender],
"You did not submit the correct result"
);
// reset storage to only allow one result withdrawal
thisMatch.revealHash[msg.sender] = bytes32(0);
uint countIndex = thisMatch.resultCountIndex[finalResultHash];
Count storage resultCount = thisMatch.resultCount[countIndex];
uint winningPool;
if (resultCount.matchResult.homeTeam.score > resultCount.matchResult.awayTeam.score) {
winningPool = calculateWinningPool(league, matchHash,
resultCount.matchResult.homeTeam.name);
}
else if (resultCount.matchResult.homeTeam.score < resultCount.matchResult.awayTeam.score) {
winningPool = calculateWinningPool(league, matchHash,
resultCount.matchResult.awayTeam.name);
}
else {
//handle tie
winningPool = 0;
}
uint rewardPool = thisMatch.betPool.mul(99).div(100);
// reward if there are enough losers to guarantee winners don't lose money
if (rewardPool > winningPool) {
uint arbiterPool = thisMatch.betPool.sub(rewardPool);
uint reward = arbiterPool.div(resultCount.value);
msg.sender.transfer(reward);
}
}
/**
* Allows anyone to get the final result information for the specified
* match
*
* @param matchHash the identifying hash for the match
* @param league the league the match pertains to
*/
function getFinalResult(
bytes32 matchHash,
string league
) view public returns (bytes32, bytes32, string, uint, string, uint) {
League storage thisLeague = leagues[leagueIndex[validateLeague(league)]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// require the match is finalized
require(thisMatch.finalized, "Match result not finalized");
// loop through result counter and determine most numerous result
uint maxCounter = 0;
Result storage maxResult = thisMatch.resultCount[0].matchResult;
for (uint i = 0; i < thisMatch.resultCount.length; i++) {
if (thisMatch.resultCount[i].value > maxCounter) {
maxCounter = thisMatch.resultCount[i].value;
maxResult = thisMatch.resultCount[i].matchResult;
}
}
return (
maxResult.hash,
maxResult.matchHash,
maxResult.homeTeam.name,
maxResult.homeTeam.score,
maxResult.awayTeam.name,
maxResult.awayTeam.score
);
}
/**
* Allows anyone to place a bet on a match specified by the given
* function arguments.
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
* @param betOnTeam the team that is bet to win the match
*/
function placeBet(
string homeTeam,
string awayTeam,
string league,
uint startTime,
string betOnTeam
) payable public {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
// make sure this is a valid bet
uint index = validateBet(homeTeam, awayTeam, league,
startTime, betOnTeam);
Match storage matchBetOn = thisLeague.matches[index];
uint betIndex = matchBetOn.betterIndex[msg.sender];
if (betIndex == 0) {
// Add bet owner to ID list.
matchBetOn.betterIndex[msg.sender] = matchBetOn.bets.length;
betIndex = matchBetOn.bets.length++;
}
// Create and update storage
Bet storage b = matchBetOn.bets[betIndex];
b.matchHash = matchBetOn.hash;
b.owner = msg.sender;
b.withdrawn = false;
// place the bet on the correct team
if (keccak256(abi.encodePacked(betOnTeam)) ==
keccak256(abi.encodePacked(matchBetOn.homeTeam))) {
b.betOnTeam = homeTeam;
}
else {
b.betOnTeam = awayTeam;
}
b.amount = msg.value;
matchBetOn.betPool = matchBetOn.betPool.add(msg.value);
}
/**
* Allows anyone to remove a bet they placed on a match
*
* @notice msg.sender must have a bet placed on the match
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function removeBet(
string homeTeam,
string awayTeam,
string league,
uint startTime
) payable public {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
// make sure match is a valid match
uint index = thisLeague.matchIndex[matchHash];
require(index != 0 || thisLeague.matches[index].hash == matchHash, "Invalid match");
// require the user has placed a bet on the match
uint betIndex = thisLeague.matches[index].betterIndex[msg.sender];
require(
betIndex != 0 || thisLeague.matches[index].bets[betIndex].owner == msg.sender,
"You did not place a bet on this match"
);
// require the match hasn't started
require(now < thisLeague.matches[index].startTime, "Match already started");
// save the bet amount for refunding purposes
uint betAmount = thisLeague.matches[index].bets[betIndex].amount;
uint expectedBalance = address(this).balance.sub(betAmount);
// Rewrite the bets storage to move the 'gap' to the end.
Bet[] storage addressBets = thisLeague.matches[index].bets;
for (uint i = betIndex; i < addressBets.length - 1; i++) {
addressBets[i] = addressBets[i+1];
thisLeague.matches[index].betterIndex[addressBets[i].owner] = i;
}
// Delete the last bet
delete thisLeague.matches[index].betterIndex[msg.sender];
delete addressBets[addressBets.length-1];
addressBets.length--;
// refund and update match bet pool
thisLeague.matches[index].betPool = thisLeague.matches[index].betPool.sub(betAmount);
msg.sender.transfer(betAmount);
assert(address(this).balance == expectedBalance);
}
/**
* Allows anyone to retrieve the information about a bet they placed on
* a specified match. Information returned includes the match hash for the
* match the bet was placed on, the bet owner's address, the team bet on,
* the amount bet, and whether the bet has been withdrawn.
*
* @notice msg.sender must have a bet placed on the match
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function getBet(
string homeTeam,
string awayTeam,
string league,
uint startTime
) view public returns (bytes32, address, string, uint, bool) {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
// require the bet is on a valid match
uint index = thisLeague.matchIndex[matchHash];
require(index != 0 || thisLeague.matches[index].hash == matchHash);
// require the user has placed a bet on the match
uint betIndex = thisLeague.matches[index].betterIndex[msg.sender];
require(betIndex != 0 || thisLeague.matches[index].bets[betIndex].owner == msg.sender);
// require this is the bet owner
Bet storage userBet = thisLeague.matches[index].bets[betIndex];
require(msg.sender == userBet.owner);
return (
matchHash,
userBet.owner,
userBet.betOnTeam,
userBet.amount,
userBet.withdrawn
);
}
/**
* Allows anyone to withdraw a bet. If the bet was correct, a reward is
* calculated and transferred to the account of the msg.sender.
*
* @notice msg.sender must have a bet placed on the match
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function withdrawBet(
string homeTeam,
string awayTeam,
string league,
uint startTime
) public {
League storage thisLeague = leagues[leagueIndex[validateLeague(league)]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// require the match result is finalized
require(thisMatch.finalized, "Match result not finalized");
// require the bet hasn't been withdrawn and msg.sender owns a bet
uint betIndex = thisMatch.betterIndex[msg.sender];
Bet storage userBet = thisMatch.bets[betIndex];
require(
!userBet.withdrawn && userBet.owner == msg.sender,
"Bet already withdrawn or never placed on the match"
);
bytes32 finalResultHash = findFinalResultHash(homeTeam, awayTeam, league, startTime);
processBetWithdraw(msg.sender, league, matchHash, finalResultHash);
}
/***************************************************************************
* Private functions
**************************************************************************/
/**
* Verifies that 'leagueName' is a valid league
*/
function validateLeague(string leagueName) view private returns (bytes32) {
bytes32 leagueHash = keccak256(abi.encodePacked(leagueName));
// require it's a valid league
require(leagueIndex[leagueHash] != 0, "Invalid league");
return leagueHash;
}
/**
* Verifies that 'arbiterAddress' is a valid arbiter
*
* @notice Also verifies that 'leagueName' is a valid league
*/
function validateLeagueArbiter(
address arbiterAddress,
string leagueName
) view private returns (bytes32) {
bytes32 leagueHash = validateLeague(leagueName);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
uint index = thisLeague.arbiterIndex[arbiterAddress];
require(thisLeague.arbiters[index].id == arbiterAddress, "Invalid league arbiter");
return leagueHash;
}
/**
* Validates that a bet can be placed on a valid match
*
* @notice assumes the 'league' has already been confirmed as valid
*
* @return index the match index for the match the bet is placed on
*/
function validateBet(
string homeTeam,
string awayTeam,
string league,
uint startTime,
string betOnTeam
) view private returns (uint index) {
bytes32 leagueHash = keccak256(abi.encodePacked(league));
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
index = thisLeague.matchIndex[matchHash];
// require the match can still be bet on
require(thisLeague.matches[index].hash == matchHash
&& now < thisLeague.matches[index].startTime);
// require the bet is on a valid team
require(keccak256(abi.encodePacked(betOnTeam)) ==
keccak256(abi.encodePacked(thisLeague.matches[index].homeTeam))
|| keccak256(abi.encodePacked(betOnTeam)) ==
keccak256(abi.encodePacked(thisLeague.matches[index].awayTeam)));
}
/**
* Stores the result commit specified by the function parameters and
* attributes the submission to the sender address.
*
* @notice assumes the 'league' has already been confirmed as valid
* @notice assumes 'sender' has already been confirmed as a league arbiter
*
* @param sender the address that submitted this result
* @param league the league the match to be removed pertains to
* @param matchHash the unique hash that identifies the match
* @param resultHash the hash of the result committed by the arbiter
*/
function storeMatchCommit(
address sender,
string league,
bytes32 matchHash,
bytes32 resultHash
) private {
League storage thisLeague = leagues[leagueIndex[keccak256(abi.encodePacked(league))]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// map the sender's address to the hash of the result and the match hash
bytes32 resultKey = keccak256(abi.encodePacked(resultHash, matchHash));
thisMatch.resultHash[sender] = resultKey;
thisMatch.commits.add(1);
thisLeague.arbiters[thisLeague.arbiterIndex[sender]].commits.add(1);
}
/**
* Verifies that the result revealed matches the result previously committed
* by the address 'sender' for this match
*
* @notice assumes the 'league' has already been confirmed as valid
* @notice assumes 'sender' has already been confirmed as a league arbiter
*
* @param sender the address that submitted this result
* @param league the league the match to be removed pertains to
* @param matchHash the unique hash that identifies the match
* @param salt the hash added in the msg.sender's result commit
* @param homeScore the score for the home team
* @param awayScore the score for the away team
*/
function verifyMatchReveal(
address sender,
string league,
bytes32 matchHash,
bytes32 salt,
uint homeScore,
uint awayScore
) private {
League storage thisLeague = leagues[leagueIndex[keccak256(abi.encodePacked(league))]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
bytes32 commit = thisMatch.resultHash[sender];
bytes32 result = keccak256(abi.encodePacked(salt, homeScore, awayScore));
bytes32 verifyCommit = keccak256(abi.encodePacked(result, matchHash));
if (commit == verifyCommit) {
// overwrite mapping to allow only one reveal per address
thisMatch.resultHash[sender] = bytes32(0);
sender.transfer(stakeAmount);
// store the result and increase reveal number if match isn't finalized
if (!thisMatch.finalized) {
bytes32 storeResult = keccak256(abi.encodePacked(matchHash, homeScore, awayScore));
storeMatchReveal(sender, league, matchHash, storeResult, homeScore, awayScore);
}
}
}
/**
* Verifies that the result revealed matches the result previously committed
* by the address 'sender' for this match
*
* @notice assumes the 'league' has already been confirmed as valid
* @notice assumes 'sender' has already been confirmed as a league arbiter
*
* @param sender the address that submitted this result
* @param league the league the match to be removed pertains to
* @param matchHash the unique hash that identifies the match
* @param storeResult the hash to identify the result revealed
* @param homeScore the score for the home team
* @param awayScore the score for the away team
*/
function storeMatchReveal(
address sender,
string league,
bytes32 matchHash,
bytes32 storeResult,
uint homeScore,
uint awayScore
) private {
League storage thisLeague = leagues[leagueIndex[keccak256(abi.encodePacked(league))]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// map the sender's address to the result hash
thisMatch.revealHash[sender] = storeResult;
// map the result hash to an index in the result counter array
uint countIndex = thisMatch.resultCountIndex[storeResult];
if (countIndex == 0
&& thisMatch.resultCount[countIndex].matchResult.hash != storeResult) {
// Add result to ID list
thisMatch.resultCountIndex[storeResult] = thisMatch.resultCount.length;
countIndex = thisMatch.resultCount.length++;
// identify the result
thisMatch.resultCount[countIndex].matchResult = Result(
storeResult,
matchHash,
Team(thisMatch.homeTeam, homeScore),
Team(thisMatch.awayTeam, awayScore)
);
}
// add 1 to the number of people who submitted this result
Count storage thisCount = thisMatch.resultCount[countIndex];
thisCount.value = thisCount.value.add(uint(1));
// add to the number of reveals, check if match is finalized
thisMatch.reveals.add(1);
thisLeague.arbiters[thisLeague.arbiterIndex[sender]].reveals.add(1);
if(thisMatch.commits.mul(9).div(10) < thisMatch.reveals) {
thisMatch.finalized = true;
}
}
/**
* Distributes the bet reward if the user won the bet
*
* @notice assumes the 'league' has already been confirmed as valid
*
* @param sender the address that submitted a bet on this match
* @param league the league the match to be removed pertains to
* @param matchHash the unique hash that identifies the match
* @param finalResultHash the hash of the finalized match result
*/
function processBetWithdraw(
address sender,
string league,
bytes32 matchHash,
bytes32 finalResultHash
) private {
League storage thisLeague = leagues[leagueIndex[validateLeague(league)]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
uint resultIndex = thisMatch.resultCountIndex[finalResultHash];
Result storage finalResult = thisMatch.resultCount[resultIndex].matchResult;
uint betIndex = thisMatch.betterIndex[msg.sender];
Bet storage userBet = thisMatch.bets[betIndex];
// withdraw Bet
userBet.withdrawn = true;
uint reward;
if (finalResult.homeTeam.score == finalResult.awayTeam.score) {
// handle tie
reward = userBet.amount.mul(99).div(100);
sender.transfer(reward);
}
else {
// handle win
uint winningPool;
uint rewardPool = thisMatch.betPool.mul(99).div(100);
if (finalResult.homeTeam.score > finalResult.awayTeam.score) {
if (keccak256(abi.encodePacked(userBet.betOnTeam))
== keccak256(abi.encodePacked(finalResult.homeTeam.name))) {
winningPool = calculateWinningPool(league, matchHash,
finalResult.homeTeam.name);
reward = rewardPool.mul(userBet.amount).div(winningPool);
sender.transfer(reward);
}
}
else {
if (keccak256(abi.encodePacked(userBet.betOnTeam))
== keccak256(abi.encodePacked(finalResult.awayTeam.name))) {
winningPool = calculateWinningPool(league, matchHash,
finalResult.awayTeam.name);
reward = rewardPool.mul(userBet.amount).div(winningPool);
sender.transfer(reward);
}
}
}
}
/**
* Returns the hash of the final result for the specified match
*/
function findFinalResultHash(
string homeTeam,
string awayTeam,
string league,
uint startTime
) view private returns (bytes32) {
(bytes32 resultHash,
bytes32 matchHash,
string memory homeName,
uint homeScore,
string memory awayName,
uint awayScore) = getFinalResult(
getMatchHash(homeTeam, awayTeam, league, startTime),
league
);
return resultHash;
}
/**
* Calculates and returns the sum of the correct bet amounts
*
* @param matchHash the hash of the match the bets are for
* @param league the league the match pertains to
* @param winningTeam the team that won the match
*/
function calculateWinningPool(
string league,
bytes32 matchHash,
string winningTeam
) view private returns (uint winningPool) {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
winningPool = 0;
for (uint i = 0; i < thisMatch.bets.length; i++) {
Bet storage thisBet = thisMatch.bets[i];
if (keccak256(abi.encodePacked(thisBet.betOnTeam))
== keccak256(abi.encodePacked(winningTeam))) {
winningPool = winningPool.add(thisBet.amount);
}
}
}
/**
* Calculates the unique byte32 identifier hash for the specified match
*/
function getMatchHash(
string homeTeam,
string awayTeam,
string league,
uint startTime
) pure private returns (bytes32 matchHash){
matchHash = keccak256(abi.encodePacked(
homeTeam,
awayTeam,
league,
startTime
));
}
}
/**
* @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;
}
}
|
Allow only arbiters for the specified 'league' to commit match results homeTeam the home team competing in the match awayTeam the away team competing in the match league the league the match to be removed pertains to startTime the time the match to be removed begins resultHash the hash of the result entered by the arbiter/ make sure match is valid require match is finished require match still needs more commits only allow one result submission per address must stake 'stakeAmount' to commit result
|
function commitMatchResult(
string homeTeam,
string awayTeam,
string league,
uint startTime,
bytes32 resultHash
) public payable {
bytes32 leagueHash = validateLeagueArbiter(msg.sender, league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
require(thisMatch.hash == matchHash, "Invalid match");
require(now > startTime + 95, "Match is not finished");
require(
thisLeague.arbiters.length.mul(8).div(10) >= thisMatch.commits,
"Match not accepting more commits"
);
require(thisMatch.resultHash[msg.sender] == 0, "Result already committed");
require(msg.value >= stakeAmount, "Must stake 10 Wei to commit result");
storeMatchCommit(msg.sender, league, matchHash, resultHash);
}
| 12,535,196 |
pragma solidity >=0.7.0;
import "./SafeMathTyped.sol";
import "./AbqErc20.sol";
import "./SingleOwnerForward.sol";
enum GovernanceState
{
SubmissionsAccepted,
SubmissionsOpen,
SubmissionsSelection,
VotingStarted,
ProposalConclusion,
AwaitingSelectionCall
}
struct Proposal
{
// CG: Word 0 start.
address proposalAddress; // CG: Word 0; 160 bits total.
uint32 submissionBatchNumber; // CG: Word0; 160 + 32 = 192 bits total.
// CG: Word 0 end.
// CG: Word 1 start.
address proposer;
// CG: Word 1 end.
// CG: Word 2 start.
uint256 votesInSupport; // CG: Word 2; 256 bits total.
// CG: Word 2 full.
// CG: Word 3 start.
uint256 votesInOpposition; // CG: Word 3; 256 bits total.
// CG: Word 3 full.
// CG: Word 4 start.
uint256 proposalDeposit; // CG: Word 4; 256 bits total.
// CG: Word 4 full.
bytes proposalData;
mapping(address => VoteStatus) votesCasted;
}
enum VoteStatus
{
Abstain,
Support,
Oppose
}
struct Stake
{
uint256 amount;
address delegate;
}
/// @notice This is a governance contract for the Aardbanq DAO. All ABQ token holders can stake
/// their tokens and delegate their voting rights to an address, including to themselves.
/// Only one proposal can be voted on to be executed at a time.
/// Voters can stake or unstake their ABQ tokens at anytime using the `stake` and `unstake` method.
/// The protocol for selecting and voting on proposals works as follows:
/// * If there are no pending proposals, then anyone can submit a proposal candidate to be considered provided they pay an ABQ deposit of `proposalDeposit` (which also stores the 18 decimals).
/// * For `submissionWindow` seconds after the first proposal candidate was submitted can submit another proposal candidates by also paying an ABQ deposit of `proposalDeposit` (which also stores the 18 decimals).
/// * When the first proposal candidate is submitted, a proposal to "do nothing" is also automatically created.
/// * During the first `submissionSelectionWindow` seconds after the first proposal candidate was submitted the voters may place their votes with their preferred proposal candidate.
/// * After the first `submissionSelectionWindow` seconds after the first proposal candidate was submitted, the candidate that received the most votes can be made the proposal all voters should vote on, by calling the `selectMostSupportedProposal` function.
/// * In the event of a tie between the candidates for most votes the last candidate will receive presidence. However if the "do nothing" proposal is also tied for most votes, it will always take precedence.
/// * Once a proposal candidate has been established as the proposal, all voters may only vote on that proposal. Voting stays open for `votingWindow` seconds after this.
/// * When `votingWindow` seconds have passed since the proposal candidate has been promoted to the proposal or if the proposal has received more than 50% of all staked votes either for or against it, then the proposal may be executed calling the `resolveProposal` method.
/// * When a propsal is resolved it is considered successful only if more than 50% of all votes on it is in favor if it AND the proposal was resolved within `resolutionWindow` seconds after it was promoted from a proposal candidate to the proposal.
/// * Once the proposal has been resolved a new round of proposal candidates may be submitted again.
/// * All proposal candidates that were not promoted to the proposal and all failed proposals will have their deposits burnt. This is to avoid frivolous and malicious proposals that could cost the voters more gas than the person making the proposal.
/// * All successful proposals will have their deposits returned.
/// A proposal consist of an address and data, that the `daoOwnerContract` delegate calls to the address with the data.
contract StakedVotingGovernance
{
// CG: Word 0 start.
SingleOwnerDelegateCall public daoOwnerContract; // CG: Word 0; 160 bits total.
uint32 public currentSubmissionBatchNumber = 1; // CG: Word 0; 160 + 32 = 192 bits total.
uint64 public submissionStartedDate; // CG: Word 0; 192 + 64 = 256 bits total.
// CG: Word 0 full.
// CG: Word 1 start.
AbqErc20 public token; // CG: Word 1; 160 bits total.
uint64 public votingStartedDate; // CG: Word 1; 160 + 64 = 224 bits total.
uint32 public submissionWindow = 2 days; // CG: Word 1; 224 + 32 = 256 bits.
// CG: Word 1 full.
// CG: Word 2 start.
uint32 public submissionSelectionWindow = 4 days; // CG: Word 2; 32 bits total.
uint32 public votingWindow = 3 days; // CG: Word 2; 32 + 32 = 64 bits total.
uint32 public resolutionWindow = 10 days; // CG: Word 2; 64 + 32 = 96 bits total.
// CG: Word 2 end.
// CG: Word 3 start.
uint256 public burnAmount;
// CG: Word 3 full.
// CG: Word 4 start.
bytes32 public currentProposalHash;
// CG: Word 4 full.
// CG: Word 5 start.
uint256 public totalVotesStaked;
// CG: Word 5 full.
// CG: Word 6 start.
uint256 public proposalDeposit = 100 ether;
// CG: Word 6 full.
bytes32[] public runningProposals;
mapping(bytes32 => Proposal) public proposals;
mapping(address => uint256) public refundAmount;
mapping(address => uint256) public votingPower;
mapping(address => Stake) public stakes;
mapping(address => bytes32) public lastVotedOn;
constructor (SingleOwnerDelegateCall _daoOwnerContract, AbqErc20 _token)
{
daoOwnerContract = _daoOwnerContract;
token = _token;
}
modifier onlyDaoOwner()
{
require(msg.sender == address(daoOwnerContract), "ABQDAO/only-dao-owner");
_;
}
modifier onlyAcceptingProposalsState()
{
GovernanceState governanceState = proposalsState();
require(governanceState == GovernanceState.SubmissionsAccepted || governanceState == GovernanceState.SubmissionsOpen, "ABQDAO/submissions-not-allowed");
_;
}
modifier onlyVotingState()
{
GovernanceState governanceState = proposalsState();
require(governanceState == GovernanceState.VotingStarted, "ABQDAO/voting-not-allowed");
_;
}
modifier onlyAwaitingSelectionCallState()
{
GovernanceState governanceState = proposalsState();
require(governanceState == GovernanceState.AwaitingSelectionCall, "ABQDAO/selection-call-not-allowed");
_;
}
function changeTimeWindows(uint32 _submissionWindow, uint32 _submissionSelectionWindow, uint32 _votingWindow, uint32 _resolutionWindow)
onlyDaoOwner()
external
{
// CG: ensure all parameters are between [1 days, 31 days] (in seconds).
require(_submissionWindow >= 1 days && _submissionWindow <= 31 days, "ABQDAO/out-of-range");
require(_submissionSelectionWindow >= 1 days && _submissionSelectionWindow <= 31 days, "ABQDAO/out-of-range");
require(_votingWindow >= 1 days && _votingWindow <= 31 days, "ABQDAO/out-of-range");
require(_resolutionWindow >= 1 days && _resolutionWindow <= 31 days, "ABQDAO/out-of-range");
// CG: Ensure dependend windows occur after in the correct order.
// CG: Given the above constraints that these values aren't greater than 31 days (in seconds), we can safely add 1 day (in seconds) without an overflow happening.
require(_submissionSelectionWindow >= (_submissionSelectionWindow + 1 days), "ABQDAO/out-of-range");
require(_resolutionWindow >= (_votingWindow + 1 days), "ABQDAO/out-of-range");
// CG: Set the values.
submissionWindow = submissionWindow;
submissionSelectionWindow = _submissionSelectionWindow;
votingWindow = _votingWindow;
resolutionWindow = _resolutionWindow;
}
function proposalsState()
public
view
returns (GovernanceState _proposalsState)
{
// CG: If no submission has been filed yet, then submissions are eligible.
if (submissionStartedDate == 0)
{
return GovernanceState.SubmissionsAccepted;
}
// CG: Allow submissions for submissionWindow after first submission.
else if (block.timestamp <= SafeMathTyped.add256(submissionStartedDate, submissionWindow))
{
return GovernanceState.SubmissionsOpen;
}
// CG: Allow selection of to close submissionSelectionWindow after the first submission.
else if (block.timestamp <= SafeMathTyped.add256(submissionStartedDate, submissionSelectionWindow))
{
return GovernanceState.SubmissionsSelection;
}
// CG: If more than submissionSelectionWindow has passed since the submissionStartedDate the voting date should be checked.
else
{
// CG: If voting only happened for votingWindow or less so for, voting is still pending
if (votingStartedDate == 0)
{
return GovernanceState.AwaitingSelectionCall;
}
else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow))
{
return GovernanceState.VotingStarted;
}
// CG: If voting has started more than votingWindow ago, then voting is no longer possible
else
{
return GovernanceState.ProposalConclusion;
}
}
}
function proposalsCount()
public
view
returns (uint256 _proposalsCount)
{
return runningProposals.length;
}
function viewVote(bytes32 _proposalHash, address _voter)
external
view
returns (VoteStatus)
{
return proposals[_proposalHash].votesCasted[_voter];
}
event StakeReceipt(address indexed staker, address indexed delegate, address indexed oldDelegate, bool wasStaked, uint256 amount);
/// @notice Stake `_amount` of tokens from msg.sender and delegate the voting rights to `_delegate`.
/// The tokens have to be approved by msg.sender before calling this method. All tokens staked by msg.sender
/// will be have their voting rights assigned to `_delegate`.
/// @param _delegate The address to delegate voting rights to.
/// @param _amount The amount of tokens to stake.
function stake(address _delegate, uint256 _amount)
external
{
// CG: Transfer ABQ.
bool couldTransfer = token.transferFrom(msg.sender, address(this), _amount);
require(couldTransfer, "ABQDAO/could-not-transfer-stake");
// CG: Get previous stake details.
Stake storage stakerStake = stakes[msg.sender];
uint256 previousStake = stakerStake.amount;
address previousDelegate = stakerStake.delegate;
// CG: Remove previous delegate stake
votingPower[previousDelegate] = SafeMathTyped.sub256(votingPower[previousDelegate], previousStake);
// CG: Increase stake counts.
stakerStake.amount = SafeMathTyped.add256(stakerStake.amount, _amount);
stakerStake.delegate = _delegate;
votingPower[stakerStake.delegate] = SafeMathTyped.add256(votingPower[stakerStake.delegate], stakerStake.amount);
// CG: Update previous vote
bytes32 previousDelegateLastProposal = lastVotedOn[previousDelegate];
bytes32 newDelegateLastProposal = lastVotedOn[stakerStake.delegate];
updateVoteIfNeeded(previousDelegateLastProposal, previousDelegate, previousStake, newDelegateLastProposal, stakerStake.delegate, stakerStake.amount);
// CG: Update running total.
totalVotesStaked = SafeMathTyped.add256(totalVotesStaked, _amount);
emit StakeReceipt(msg.sender, _delegate, previousDelegate, true, _amount);
}
/// @notice Unstake `_amount` tokens for msg.sender and send them to msg.sender.
/// @param _amount The amount of tokens to unstake.
function unstake(uint256 _amount)
external
{
// CG: Decrease stake counts.
Stake storage stakerStake = stakes[msg.sender];
stakerStake.amount = SafeMathTyped.sub256(stakerStake.amount, _amount);
address delegate = stakerStake.delegate;
votingPower[delegate] = SafeMathTyped.sub256(votingPower[delegate], _amount);
// CG: Update previous vote
bytes32 lastProposal = lastVotedOn[delegate];
updateVoteIfNeeded(lastProposal, delegate, _amount, lastProposal, delegate, 0);
// CG: Transfer ABQ back.
bool couldTransfer = token.transfer(msg.sender, _amount);
require(couldTransfer, "ABQDAO/could-not-transfer-stake");
// CG: Update running total.
totalVotesStaked = SafeMathTyped.sub256(totalVotesStaked, _amount);
emit StakeReceipt(msg.sender, delegate, delegate, false, _amount);
}
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
// CG: Only update votes while voting is still open.
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
// CG: Only update votes for current submission round on proposal A.
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
// CG: If voter A has a decrease, decrease it.
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
// CG: Only update votes for current submission round on proposal B.
Proposal storage proposalB = proposals[_proposalHashB];
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
// CG: If voter B has an increase, increase it.
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
/// @notice Make a poposal for a resolution.
/// @param _executionAddress The address containing the smart contract to delegate call.
/// @param _data The data to send when executing the proposal.
function propose(address _executionAddress, bytes calldata _data)
onlyAcceptingProposalsState()
external
returns (bytes32 _hash)
{
// CG: Get proposal hash and make sure it is not already submitted.
bytes32 proposalHash = keccak256(abi.encodePacked(currentSubmissionBatchNumber, _executionAddress, _data));
Proposal storage proposal = proposals[proposalHash];
require(proposal.submissionBatchNumber == 0, "ABQDAO/proposal-already-submitted");
// CG: Transfer deposit.
bool couldTransferDeposit = token.transferFrom(msg.sender, address(this), proposalDeposit);
require(couldTransferDeposit, "ABQDAO/could-not-transfer-deposit");
// CG: If this is the first proposal, add a "do nothing" proposal as the first proposal
if (runningProposals.length == 0)
{
address doNothingAddress = address(0);
bytes memory doNothingData = new bytes(0);
bytes32 doNothingHash = keccak256(abi.encodePacked(currentSubmissionBatchNumber, doNothingAddress, doNothingData));
Proposal storage doNothingProposal = proposals[doNothingHash];
doNothingProposal.proposalAddress = doNothingAddress;
doNothingProposal.proposalDeposit = 0;
doNothingProposal.submissionBatchNumber = currentSubmissionBatchNumber;
doNothingProposal.proposer = address(0);
doNothingProposal.votesInSupport = 0;
doNothingProposal.votesInOpposition = 0;
doNothingProposal.proposalData = doNothingData;
runningProposals.push(doNothingHash);
emit ProposalReceipt(doNothingHash);
submissionStartedDate = uint64(block.timestamp);
}
// CG: Set the proposal data
proposal.proposalAddress = _executionAddress;
proposal.proposalDeposit = proposalDeposit;
proposal.submissionBatchNumber = currentSubmissionBatchNumber;
proposal.proposer = msg.sender;
proposal.votesInSupport = 0;
proposal.votesInOpposition = 0;
proposal.proposalData = _data;
runningProposals.push(proposalHash);
emit ProposalReceipt(proposalHash);
return proposalHash;
}
event VoteOpenedReceipt(bytes32 proposalHash);
/// @notice Select the most supported proposal.
/// @param maxIterations The max iteration to execute. This is used to throttle gas useage per call.
function selectMostSupportedProposal(uint8 maxIterations)
onlyAwaitingSelectionCallState()
external
returns (bool _isSelectionComplete)
{
if (votingStartedDate != 0)
{
return true;
}
while (runningProposals.length > 1 && maxIterations > 0)
{
Proposal storage firstProposal = proposals[runningProposals[0]];
Proposal storage lastProposal = proposals[runningProposals[runningProposals.length - 1]]; // CG: runningProposals.length - 1 will always be >= 1 since we check runningProposals.length > 1 in the while's condition. Hence no overflow will occur.
if (firstProposal.votesInSupport < lastProposal.votesInSupport)
{
burnAmount = SafeMathTyped.add256(burnAmount, firstProposal.proposalDeposit);
runningProposals[0] = runningProposals[runningProposals.length - 1]; // CG: runningProposals.length - 1 will always be >= 1 since we check runningProposals.length > 1 in the while's condition. Hence no overflow will occur.
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, lastProposal.proposalDeposit);
}
runningProposals.pop();
maxIterations = maxIterations - 1; // CG: We can safely subtract 1 without overflow issues, since the while test for maxIterations > 0;
}
if (runningProposals.length == 1)
{
currentProposalHash = runningProposals[0];
votingStartedDate = uint64(block.timestamp);
runningProposals.pop();
emit VoteOpenedReceipt(currentProposalHash);
return true;
}
else
{
return false;
}
}
event Ballot(address indexed voter, bytes32 proposalHash, VoteStatus vote, uint256 votes);
/// @notice Cast a vote for a specific proposal for msg.sender.
/// @param _proposalHash The hash for the proposal to vote on.
/// @param _vote Indication of if msg.sender is voting in support, opposition, or abstaining.
function vote(bytes32 _proposalHash, VoteStatus _vote)
external
{
// CG: Must be in submission selection or voting state.
GovernanceState state = proposalsState();
require(state == GovernanceState.SubmissionsOpen || state == GovernanceState.SubmissionsSelection || state == GovernanceState.VotingStarted, "ABQDAO/voting-not-open");
// CG: If in voting state, only votes on the current proposal allowed.
if (state == GovernanceState.VotingStarted)
{
require(currentProposalHash == _proposalHash, "ABQDAO/only-votes-on-current-proposal");
}
uint256 voteCount = votingPower[msg.sender];
// CG: Reverse previous vote on the current proposal round.
Proposal storage previousProposal = proposals[lastVotedOn[msg.sender]];
if (previousProposal.submissionBatchNumber == currentSubmissionBatchNumber)
{
VoteStatus previousVote = previousProposal.votesCasted[msg.sender];
if (previousVote == VoteStatus.Support)
{
previousProposal.votesInSupport = SafeMathTyped.sub256(previousProposal.votesInSupport, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
else if (previousVote == VoteStatus.Oppose)
{
previousProposal.votesInOpposition = SafeMathTyped.sub256(previousProposal.votesInOpposition, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
}
// CG: Only votes allowed on current proposal round.
Proposal storage proposal = proposals[_proposalHash];
require(proposal.submissionBatchNumber == currentSubmissionBatchNumber, "ABQDAO/only-votes-on-current-submissions");
// CG: Cast the voter's vote
if (_vote == VoteStatus.Support)
{
proposal.votesInSupport = SafeMathTyped.add256(proposal.votesInSupport, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Support;
}
else if (_vote == VoteStatus.Oppose)
{
proposal.votesInOpposition = SafeMathTyped.add256(proposal.votesInOpposition, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Oppose;
}
lastVotedOn[msg.sender] = _proposalHash;
emit Ballot(msg.sender, _proposalHash, _vote, voteCount);
}
event ProposalResolution(bytes32 proposalHash, bool wasPassed);
/// @notice Resolve the proposal that was voted on.
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
// CG: If a proposal already has more than 50% of all staked votes then it can be passed before voting concluded.
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
// CG: If a proposal already has more than 50% of all staked votes against it then it can be defeated before voting concluded.
else if (proposal.votesInOpposition >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
// CG: If the proposal was started voting on less than resolutionWindow ago, then resolve based on amount of votes.
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
// CG: After voting time has concluded it is a pass if more votes are in support than in opposition.
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
// CG: Since voting started resolutionWindow or more ago already and have not been executed yet, fail the proposal.
else
{
hasPassed = false;
}
}
// CG: Emit the event before we lose the hash stored in currentProposalHash.
emit ProposalResolution(currentProposalHash, hasPassed);
// CG: Close the proposal
currentProposalHash = 0;
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
// CG: Refund deposit to proposer.
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
// CG: Call into owner to execute the proposal.
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
// CG: If it isn't a passed proposal, then the deposit should be burned.
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
/// @notice Burns the deposits of failed submissions.
function burnDepositsOfFailedSubmissions()
external
{
token.burn(burnAmount);
burnAmount = 0;
}
/// @notice Refund the deposits for `_for` that was associated to succesful resolutions.
/// @param _for The address to refund deposits for.
function refundSuccessfulSubmissions(address _for)
external
{
uint256 amount = refundAmount[_for];
refundAmount[_for] = 0;
bool couldRefund = token.transfer(_for, amount);
require(couldRefund, "ABQDAO/could-not-refund");
}
}
|
Resolve the proposal that was voted on. CG: If a proposal already has more than 50% of all staked votes then it can be passed before voting concluded. CG: If the proposal was started voting on less than resolutionWindow ago, then resolve based on amount of votes. CG: After voting time has concluded it is a pass if more votes are in support than in opposition. CG: Refund deposit to proposer. CG: Call into owner to execute the proposal. CG: If it isn't a passed proposal, then the deposit should be burned.
|
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
| 264,723 |
./full_match/97/0x82a6A3D33caD7a3143D307a8fA019e2eb1C02AbA/sources/project:/contracts/Vesting.sol
|
Change the base token address of the token newToken address of the token./
|
function changeToken(
IERC20Upgradeable newToken
) external virtual onlyOwner {
require(
address(newToken) != address(0),
"Token: Address cant be zero address"
);
token = newToken;
}
| 3,290,137 |
./partial_match/5/0x8dee12fB4F1B18c35a6f294634ac4312E8ed996E/sources/DigitalaxRewards.sol
|
Gets the total rewards outstanding from last reward time
|
function totalRewards(uint256 _from, uint256 _to) public returns (uint256) {
uint256 gRewards = genesisRewards(lastRewardTime, block.timestamp);
uint256 pRewards = parentRewards(lastRewardTime, block.timestamp);
uint256 lRewards = LPRewards(lastRewardTime, block.timestamp);
return gRewards.add(pRewards).add(lRewards);
}
| 16,870,385 |
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.6.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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/contracts-ethereum-package/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 Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @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;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.5.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 not should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, with should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts-ethereum-package/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/contracts-ethereum-package/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 Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
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 _allowances[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(_msgSender(), 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(_msgSender(), 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, _msgSender(), _allowances[from][_msgSender()].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowances[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(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowances[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(_msgSender(), spender, _allowances[_msgSender()][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));
_allowances[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 amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount));
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.2;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is Initializable, Context, ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param amount The amount of token to be burned.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @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);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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/contracts-ethereum-package/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: @openzeppelin/contracts-ethereum-package/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/contracts-ethereum-package/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.2;
contract MinterRole is Initializable, Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.2;
contract PauserRole is Initializable, Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function initialize(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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 Initializable, Context, PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
function initialize(address sender) public initializer {
PauserRole.initialize(sender);
_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(_msgSender());
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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 is Initializable, Context {
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.
*/
function initialize(address sender) public initializer {
_owner = 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 _msgSender() == _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;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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: @openzeppelin/contracts-ethereum-package/contracts/access/roles/WhitelistAdminRole.sol
pragma solidity ^0.5.2;
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Initializable, Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
function initialize(address sender) public initializer {
if (!isWhitelistAdmin(sender)) {
_addWhitelistAdmin(sender);
}
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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 Initializable, Context, WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role");
_;
}
function initialize(address sender) public initializer {
WhitelistAdminRole.initialize(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(_msgSender());
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
uint256[50] private ______gap;
}
// File: contracts/InvictusWhitelist.sol
pragma solidity ^0.5.6;
/**
* Manages whitelisted addresses.
*
*/
contract InvictusWhitelist is Initializable, Ownable, WhitelistedRole {
function initialize() public initializer {
Ownable.initialize(msg.sender);
WhitelistedRole.initialize(msg.sender);
}
/// @dev override to support legacy name
function verifyParticipant(address participant) public onlyWhitelistAdmin {
if (!isWhitelisted(participant)) {
addWhitelisted(participant);
}
}
/// Allow the owner to remove a whitelistAdmin
function removeWhitelistAdmin(address account) public onlyOwner {
require(account != msg.sender, "Use renounceWhitelistAdmin");
_removeWhitelistAdmin(account);
}
}
// File: contracts/IMLToken.sol
pragma solidity ^0.5.6;
/**
* Contract for Invictus Margin Lending (IML) fund.
*
*/
contract IMLToken is Initializable, ERC20Detailed, ERC20Burnable, Ownable, Pausable, MinterRole {
using SafeERC20 for ERC20;
using SafeMath for uint256;
// Maps participant addresses to the withdrawal request
mapping (address => uint256) public pendingWithdrawals;
address[] public withdrawals;
uint256 private minTokenRedemption;
uint256 private maxWithdrawalsPerTx;
Price public price;
address public whitelistContract;
address public stableContract;
struct Price {
uint256 numerator;
uint256 denominator;
}
event PriceUpdate(uint256 numerator, uint256 denominator);
event AddLiquidity(address indexed account, address indexed stableAddress, uint256 value);
event RemoveLiquidity(address indexed account, uint256 value);
event WithdrawRequest(address indexed participant, uint256 amountTokens);
event Withdraw(address indexed participant, uint256 amountTokens, uint256 etherAmount);
event WithdrawInvalidAddress(address indexed participant, uint256 amountTokens);
event WithdrawFailed(address indexed participant, uint256 amountTokens);
event TokensClaimed(address indexed token, uint256 balance);
/**
* Sets the maximum number of withdrawals in a single transaction.
* @dev Allows us to configure batch sizes and avoid running out of gas.
*/
function setMaxWithdrawalsPerTx(uint256 newMaxWithdrawalsPerTx) external onlyOwner {
require(newMaxWithdrawalsPerTx > 0, "Must be greater than 0");
maxWithdrawalsPerTx = newMaxWithdrawalsPerTx;
}
/// Sets the minimum number of tokens to redeem.
function setMinimumTokenRedemption(uint256 newMinTokenRedemption) external onlyOwner {
require(newMinTokenRedemption > 0, "Minimum must be greater than 0");
minTokenRedemption = newMinTokenRedemption;
}
/// Updates the price numerator.
function updatePrice(uint256 newNumerator) external onlyMinter {
require(newNumerator > 0, "Must be positive value");
price.numerator = newNumerator;
processWithdrawals();
emit PriceUpdate(price.numerator, price.denominator);
}
/// Updates the price denominator.
function updatePriceDenominator(uint256 newDenominator) external onlyMinter {
require(newDenominator > 0, "Must be positive value");
price.denominator = newDenominator;
}
/**
* Whitelisted token holders can request token redemption, and withdraw stable coins.
* @param amountTokensToWithdraw The number of tokens to withdraw.
* @dev withdrawn tokens are burnt.
*/
function requestWithdrawal(uint256 amountTokensToWithdraw) external whenNotPaused
onlyWhitelisted {
address participant = msg.sender;
require(balanceOf(participant) >= amountTokensToWithdraw,
"Cannot withdraw more than balance held");
require(amountTokensToWithdraw >= minTokenRedemption, "Too few tokens");
burn(amountTokensToWithdraw);
uint256 pendingAmount = pendingWithdrawals[participant];
if (pendingAmount == 0) {
withdrawals.push(participant);
}
pendingWithdrawals[participant] = pendingAmount.add(amountTokensToWithdraw);
emit WithdrawRequest(participant, amountTokensToWithdraw);
}
/// Allows owner to claim any ERC20 tokens.
function claimTokens(ERC20 token) external onlyOwner {
require(address(token) != address(0), "Invalid address");
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(owner(), token.balanceOf(address(this)));
emit TokensClaimed(address(token), balance);
}
/**
* @dev Allows the owner to burn a specific amount of tokens on a participant's behalf.
* @param value The amount of tokens to be burned.
*/
function burnForParticipant(address account, uint256 value) external onlyOwner {
_burn(account, value);
}
/**
* @dev Function allowing the owner to change the stable contract when paused.
* @param stableContractInput The new stable contract address.
*/
function changeStableContract(address stableContractInput) external onlyOwner whenPaused {
require(stableContractInput != address(0), "Invalid stable coin address");
stableContract = stableContractInput;
}
/// Adds liquidity to the contract, allowing anyone to explicitly deposit stable coin.
function addLiquidity(uint256 amount) external {
ERC20 erc20 = ERC20(stableContract);
erc20.safeTransferFrom(msg.sender, address(this), amount);
emit AddLiquidity(msg.sender, stableContract, amount);
}
/// Removes liquidity, allowing owner to transfer stable coin to the fund wallet.
function removeLiquidity(uint256 amount) external onlyOwner {
ERC20(stableContract).safeTransfer(msg.sender, amount);
emit RemoveLiquidity(msg.sender, amount);
}
/// Allow the owner to remove a minter
function removeMinter(address account) external onlyOwner {
require(account != msg.sender, "Use renounceMinter");
_removeMinter(account);
}
/// Allow the owner to remove a pauser
function removePauser(address account) external onlyOwner {
require(account != msg.sender, "Use renouncePauser");
_removePauser(account);
}
/// returns the number of withdrawals pending.
function numberWithdrawalsPending() external view returns (uint256) {
return withdrawals.length;
}
/**
* Initialize the contract.
*/
function initialize(uint256 priceNumeratorInput, address whitelistContractInput, address stableContractInput) public initializer {
ERC20Detailed.initialize("Invictus Margin Lending", "IML", 18);
Pausable.initialize(msg.sender);
Ownable.initialize(msg.sender);
MinterRole.initialize(msg.sender);
price = Price(priceNumeratorInput, 1000);
require(priceNumeratorInput > 0, "Invalid price numerator");
require(whitelistContractInput != address(0), "Invalid whitelist address");
require(stableContractInput != address(0), "Invalid stable coin address");
whitelistContract = whitelistContractInput;
stableContract = stableContractInput;
minTokenRedemption = 1 ether;
maxWithdrawalsPerTx = 50;
}
/**
* @dev Function to mint tokens when not paused.
* @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 whenNotPaused returns (bool) {
_mint(to, value);
return true;
}
/// Internal function to process withdrawals.
function processWithdrawals() internal {
uint256 numberOfWithdrawals = Math.min(withdrawals.length, maxWithdrawalsPerTx);
uint256 startingIndex = withdrawals.length;
uint256 endingIndex = withdrawals.length.sub(numberOfWithdrawals);
for (uint256 i = startingIndex; i > endingIndex; i--) {
handleWithdrawal(i - 1);
}
}
function handleWithdrawal(uint256 index) internal {
address participant = withdrawals[index];
uint256 tokens = pendingWithdrawals[participant];
uint256 withdrawValue = tokens.mul(price.denominator) / price.numerator;
pendingWithdrawals[participant] = 0;
withdrawals.pop();
if (ERC20(stableContract).balanceOf(address(this)) < withdrawValue) {
mint(participant, tokens);
emit WithdrawFailed(participant, tokens);
return;
}
ERC20(stableContract).safeTransfer(participant, withdrawValue);
emit Withdraw(participant, tokens, withdrawValue);
}
modifier onlyWhitelisted() {
require(InvictusWhitelist(whitelistContract).isWhitelisted(msg.sender), "Must be whitelisted");
_;
}
}
|
Whitelisted token holders can request token redemption, and withdraw stable coins. amountTokensToWithdraw The number of tokens to withdraw. withdrawn tokens are burnt./
|
function requestWithdrawal(uint256 amountTokensToWithdraw) external whenNotPaused
onlyWhitelisted {
address participant = msg.sender;
require(balanceOf(participant) >= amountTokensToWithdraw,
"Cannot withdraw more than balance held");
require(amountTokensToWithdraw >= minTokenRedemption, "Too few tokens");
burn(amountTokensToWithdraw);
uint256 pendingAmount = pendingWithdrawals[participant];
if (pendingAmount == 0) {
withdrawals.push(participant);
}
pendingWithdrawals[participant] = pendingAmount.add(amountTokensToWithdraw);
emit WithdrawRequest(participant, amountTokensToWithdraw);
}
| 6,063,606 |
./full_match/5/0x6AfDCEaaF0249b4e000E022c78E7C11Ba8E43660/sources/contracts/CrowdFunding.sol
|
list of all compaignswe creating new variable called allCompaigns which is a type array of multiple compaign structures.
|
function getCompaigns() public view returns(Compaign[] memory){
Compaign[] memory allCompaigns = new Compaign[](numberOfCompaigns);
for(uint i=0; i < numberOfCompaigns; i++){
Compaign storage item = compaigns[i];
allCompaigns[i] = item;
}
return allCompaigns;
}
| 7,040,392 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* 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);
/**
* Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* 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);
/**
* 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);
function decimals() external view returns (uint8);
/**
* 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);
/**
* 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;
/**
* 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 {
/**
* 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;
}
/**
* 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");
}
/**
* 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;
}
/**
* 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;
}
/**
* 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");
}
/**
* 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;
}
/**
* 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");
}
/**
* 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;
/**
* Collection of functions related to the address type
*/
library Address {
/**
* Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* 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");
}
/**
* 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");
}
/**
* 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);
}
/**
* 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");
}
/**
* 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;
/**
* 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;
/**
* 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;
}
/**
* Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* 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 override returns (uint8) {
return _decimals;
}
/**
* See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* 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;
}
/**
* See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** 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");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* 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");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* 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_;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* 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);
/**
* Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _owner;
}
/**
* Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/zaToken.sol
// zaTokens are Stabilize proxy tokens that serve as receipts for deposits into the Aave lending pool
// zaTokens increase gradually in value as the underlying value of the contract increases
// The underlying asset in Aave does increase in size and users of zaTokens can share a percentage of the underlying asset
// When someone deposits into the zaToken contract, tokens are minted and when they redeem, tokens are burned
pragma solidity ^0.6.6;
interface LendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function getLendingPoolCore() external view returns (address);
}
interface LendingPool {
function deposit(address, uint256, uint16) external;
}
interface aTokenContract is IERC20 {
function redeem(uint256 _amount) external;
}
contract zaToken is ERC20("Stabilize Proxy Aave USDC Token", "za-USDC"), Ownable {
using SafeERC20 for IERC20;
// Variables
uint256 constant divisionFactor = 100000;
// First the fee schedule
uint256 public initialFee = 1000; // 1000 = 1%, 100000 = 100%, max fee restricted in contract is 10%
uint256 public endFee = 100; // 100 = 0.1%
uint256 public feeDuration = 604800; // The amount of seconds it takes from the initial to end fee
// Token information
// AaveProvider address on Mainnet: 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8
// Kovan Testnet: 0x506B0B2CF20FAA8f38a4E2B524EE43e1f4458Cc5
address public aaveProviderAddress = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
LendingPoolAddressesProvider aaveProvider;
IERC20 private _underlyingAsset; // Token of the deposited asset
aTokenContract private _aToken; // The aToken returned to this contract by depositing
address public treasuryAddress;
// Events
event Wrapped(address indexed user, uint256 amount);
event Unwrapped(address indexed user, uint256 amount, uint256 fee);
// Info of each user.
struct UserInfo {
uint256 depositTime; // The time the user made a deposit, every deposit resets the time
}
mapping(address => UserInfo) private userInfo;
constructor (IERC20 _asset, aTokenContract _aavetoken, address _treasury) public {
_underlyingAsset = _asset;
_aToken = _aavetoken;
treasuryAddress = _treasury;
aaveProvider = LendingPoolAddressesProvider(aaveProviderAddress); // Load the lending address provider
_setupDecimals(_aToken.decimals());
}
function underlyingAsset() public view returns (address) {
return address(_underlyingAsset);
}
function totalPrincipalAndInterest() public view returns (uint256) {
return _aToken.balanceOf(address(this)); // This will be the same balance as all deposited plus interest earned
}
function pricePerToken() external view returns (uint256) {
if(totalSupply() == 0){
return 1e18; // Shown in Wei units
}else{
return uint256(1e18).mul(totalPrincipalAndInterest()).div(totalSupply());
}
}
// Now handle deposits into Aave
function deposit(uint256 amount) public {
require(amount > 0, "Cannot deposit 0");
_underlyingAsset.safeTransferFrom(_msgSender(), address(this), amount); // Transfer stablecoin to this address
// Now send those same stablecoins to the Aave lending pool
LendingPool lendingPool = LendingPool(aaveProvider.getLendingPool()); // Get the lending pool
// Approve the lending pool core to transfer from this contract the amount deposited
_underlyingAsset.approve(aaveProvider.getLendingPoolCore(), amount);
// Now finally deposit and receive aTokens into this contract, the balance of aTokens increases
uint256 total = totalPrincipalAndInterest();
// We are going to verify Aave deposits 1:1
uint256 _underlyingBalance = _underlyingAsset.balanceOf(address(this));
lendingPool.deposit(underlyingAsset(), amount, 0); // Last field is referral code, there is none
// Aave tokens are returned to this contract 1:1 with what was deposited but increase in quantity with time
uint256 movedBalance = _underlyingBalance.sub(_underlyingAsset.balanceOf(address(this)));
require(movedBalance == amount, "Aave failed to properly move the entire amount");
// Now lets figure out how many tokens to print to user
uint256 mintAmount = amount;
if(total > 0){
// There is already a balance here, calculate our share
mintAmount = amount.mul(totalSupply()).div(total); // Our share of the total
}
_mint(_msgSender(),mintAmount); // Now mint new za-token to the depositor
userInfo[_msgSender()].depositTime = now; // Update the deposit time
emit Wrapped(_msgSender(), amount);
}
function redeem(uint256 amount) public {
// Essentially withdraw our equivalent share of the pool based on share value
require(amount > 0, "Cannot withdraw 0");
require(totalSupply() > 0, "No value redeemable");
uint256 tokenTotal = totalSupply();
// Now burn the token
_burn(_msgSender(),amount); // Burn the amount, will fail if user doesn't have enough
uint256 withdrawAmount = totalPrincipalAndInterest().mul(amount).div(tokenTotal);
// We are going to verify Aave redeems 1:1
uint256 _underlyingBalance = _underlyingAsset.balanceOf(address(this)); // Get the underlying asset amount in contract
_aToken.redeem(withdrawAmount); // Burn the aTokens to redeem the underlying asset 1:1
uint256 movedBalance = _underlyingAsset.balanceOf(address(this)).sub(_underlyingBalance);
require(movedBalance >= withdrawAmount, "Aave failed to properly move the entire amount"); // Should be equal at least
// Pay fee upon withdrawing
uint256 feeSubtraction = initialFee.sub(endFee).mul(now.sub(userInfo[_msgSender()].depositTime)).div(feeDuration);
if(feeSubtraction > initialFee.sub(endFee)){
// Cannot reduce fee more than this
feeSubtraction = initialFee.sub(endFee);
}
uint256 fee = initialFee.sub(feeSubtraction);
fee = withdrawAmount.mul(fee).div(divisionFactor);
withdrawAmount = withdrawAmount.sub(fee);
// Now withdraw this amount to the user and send fee to treasury
_underlyingAsset.safeTransfer(_msgSender(), withdrawAmount);
_underlyingAsset.safeTransfer(treasuryAddress, fee);
emit Unwrapped(_msgSender(), withdrawAmount, fee);
}
// Governance functions
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant _timelockDuration = 86400; // Timelock is 24 hours
// Reusable timelock variables
uint256[3] private _timelock_data;
address private _timelock_address;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(totalSupply() > 0){
// Timelock is only required after tokens exist
require(now >= _timelockStart + _timelockDuration, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Used to change the fee rates
// --------------------
function startChangeFeeRates(uint256 _initial, uint256 _end, uint256 _duration) external onlyGovernance {
require(_initial <= 10000,"Fee can never be greater than 10%");
require(_end <= _initial,"End fee must be less than or equal to initial fee");
require(_duration > 0, "Cannot be a zero amount");
_timelockStart = now;
_timelockType = 2;
_timelock_data[0] = _initial;
_timelock_data[1] = _end;
_timelock_data[2] = _duration;
}
function finishChangeFeeRates() external onlyGovernance timelockConditionsMet(2) {
initialFee = _timelock_data[0];
endFee = _timelock_data[1];
feeDuration = _timelock_data[2];
}
// --------------------
// Change the treasury address
// --------------------
function startChangeTreasury(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishChangeTreasury() external onlyGovernance timelockConditionsMet(3) {
treasuryAddress = _timelock_address;
}
// --------------------
}
|
Essentially withdraw our equivalent share of the pool based on share value Now burn the token We are going to verify Aave redeems 1:1 Pay fee upon withdrawing Cannot reduce fee more than this
|
function redeem(uint256 amount) public {
require(amount > 0, "Cannot withdraw 0");
require(totalSupply() > 0, "No value redeemable");
uint256 tokenTotal = totalSupply();
uint256 withdrawAmount = totalPrincipalAndInterest().mul(amount).div(tokenTotal);
uint256 movedBalance = _underlyingAsset.balanceOf(address(this)).sub(_underlyingBalance);
uint256 feeSubtraction = initialFee.sub(endFee).mul(now.sub(userInfo[_msgSender()].depositTime)).div(feeDuration);
if(feeSubtraction > initialFee.sub(endFee)){
feeSubtraction = initialFee.sub(endFee);
}
uint256 fee = initialFee.sub(feeSubtraction);
fee = withdrawAmount.mul(fee).div(divisionFactor);
withdrawAmount = withdrawAmount.sub(fee);
_underlyingAsset.safeTransfer(treasuryAddress, fee);
emit Unwrapped(_msgSender(), withdrawAmount, fee);
}
address private _timelock_address;
| 13,622,409 |
./partial_match/1/0x01cF6B5684C7D9d0BbBd57a385e5F2B06D42771f/sources/Frame.sol
|
this enables / dsiables stake
|
function setStakingState(bool available) public onlyOwner {
stakingAvailable = available;
}
| 16,050,528 |
pragma solidity ^0.5.0;
import "ERC1155Adapter-flat.sol";
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previous_owner, address indexed new_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 new_owner The address to transfer ownership to.
*/
function transferOwnership(address new_owner) public onlyOwner {
require(new_owner != address(0));
emit OwnershipTransferred(owner, new_owner);
owner = new_owner;
}
}
contract Admin is Ownable {
mapping(address => bool) public isAdmin;
function addAdmin(address who) external onlyOwner {
isAdmin[who] = true;
}
function removeAdmin(address who) external onlyOwner {
isAdmin[who] = false;
}
modifier onlyAdmin() {
require(msg.sender == owner || isAdmin[msg.sender]);
_;
}
}
contract ERC20 {
function balanceOf(address) external view returns(uint256);
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 amount) external returns(bool);
}
interface ERC20NonStandard {
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 amount) external;
function transferFrom(address from, address to, uint256 amount) external;
function approve(address spender, uint256 amount) external;
}
interface IDispatcher {
// external function
function trigger() external returns (bool);
function withdrawProfit() external returns (bool);
function drainFunds(uint256 _index) external returns (bool);
function refundDispather(address _receiver) external returns (bool);
function withdrawPrinciple (uint256 _amount) external returns (bool); //custom function
// get function
function getReserve() external view returns (uint256);
function getReserveRatio() external view returns (uint256);
function getPrinciple() external view returns (uint256);
function getBalance() external view returns (uint256);
function getProfit() external view returns (uint256);
function getTHPrinciple(uint256 _index) external view returns (uint256);
function getTHBalance(uint256 _index) external view returns (uint256);
function getTHProfit(uint256 _index) external view returns (uint256);
function getToken() external view returns (address);
function getFund() external view returns (address);
function getTHStructures() external view returns (uint256[] memory, address[] memory, address[] memory);
function getTHData(uint256 _index) external view returns (uint256, uint256, uint256, uint256);
function getTHCount() external view returns (uint256);
function getTHAddress(uint256 _index) external view returns (address);
function getTargetAddress(uint256 _index) external view returns (address);
function getPropotion() external view returns (uint256[] memory);
function getProfitBeneficiary() external view returns (address);
function getReserveUpperLimit() external view returns (uint256);
function getReserveLowerLimit() external view returns (uint256);
function getExecuteUnit() external view returns (uint256);
// Governmence Functions
function setAimedPropotion(uint256[] calldata _thPropotion) external returns (bool);
function addTargetHandler(address _targetHandlerAddr, uint256[] calldata _thPropotion) external returns (bool);
function removeTargetHandler(address _targetHandlerAddr, uint256 _index, uint256[] calldata _thPropotion) external returns (bool);
function setProfitBeneficiary(address _profitBeneficiary) external returns (bool);
function setReserveLowerLimit(uint256 _number) external returns (bool);
function setReserveUpperLimit(uint256 _number) external returns (bool);
function setExecuteUnit(uint256 _number) external returns (bool);
function newOwner() external view returns(address);
function acceptOwnership() external;
}
contract SimpleSwap is ERC1155withAdapter, Admin {
event TokenPurchase(address indexed buyer, address indexed token, uint256 coin_sold, uint256 tokens_bought);
event CoinPurchase(address indexed buyer, address indexed token, uint256 tokens_sold, uint256 coin_bought);
event AddLiquidity(address indexed provider, address indexed token, uint256 coin_amount, uint256 token_amount);
event RemoveLiquidity(address indexed provider, address indexed token, uint256 coin_amount, uint256 token_amount);
mapping(address => address) public DispatcherOf;
mapping(address => uint256) public coinReserveShare;
uint256 public totalCoinStored;
uint256 public globalIndex = 1e18;
uint256 public feeRate = 3000000000000000;
address public coin = address(0xdBCFff49D5F48DDf6e6df1f2C9B96E1FC0F31371);
/***********************************|
| Dispatcher Functions |
|__________________________________*/
function updateGlobalIndex() public {
if(totalCoinStored > 0) {
globalIndex = globalIndex.mul(tokenReserveOf(coin)).div(totalCoinStored);
totalCoinStored = tokenReserveOf(coin);
}
}
function coinReserveOf(address token) public view returns(uint256) {
return coinReserveShare[token].mul(globalIndex) / 1e18;
}
function tokenReserveOf(address token) public view returns(uint256) {
uint256 amount = ERC20(token).balanceOf(address(this));
if(DispatcherOf[token] != address(0)) {
amount = amount.add(IDispatcher(DispatcherOf[token]).getBalance());
}
return amount;
}
function depositAndTrigger(address token, address from, uint256 amount) internal {
require(doTransferIn(token, from, amount));
address dispatcher = DispatcherOf[token];
if(dispatcher != address(0)){
IDispatcher(dispatcher).trigger();
}
}
function checkAndWithdraw(address token, address to, uint256 amount) internal {
uint256 cash = ERC20(token).balanceOf(address(this));
if(cash < amount) {
IDispatcher(DispatcherOf[token]).withdrawProfit();
cash = ERC20(token).balanceOf(address(this));
if(cash < amount)
IDispatcher(DispatcherOf[token]).withdrawPrinciple(amount.sub(cash));
}
require(doTransferOut(token, to, amount));
}
/***********************************|
| Manager Functions |
|__________________________________*/
function setDispatcher(address token, address dispatcher) external onlyAdmin {
// maybe check previous dispatcher balance if exist?
DispatcherOf[token] = dispatcher;
require(IDispatcher(dispatcher).newOwner() == address(this));
IDispatcher(dispatcher).acceptOwnership();
IDispatcher(dispatcher).setProfitBeneficiary(address(this));
doApproval(token, dispatcher, uint256(-1));
}
function setFee(uint256 new_fee) external onlyAdmin {
require(new_fee <= 30000000000000000); //fee must be smaller than 3%
feeRate = new_fee;
}
function createAdapter(uint256 _id, string memory _name, string memory _symbol, uint8 _decimals) public onlyAdmin {
require(adapter[_id] == address(0));
address a = createClone(template);
ERC20Adapter(a).setup(_id, _name, _symbol, _decimals);
adapter[_id] = a;
emit NewAdapter(_id, a);
}
/***********************************|
| Exchange Functions |
|__________________________________*/
/**
* @dev Pricing function for converting between tokens.
* @param input_amount Amount of Tokens being sold.
* @param input_reserve Amount of Tokens in exchange reserves.
* @param output_reserve Amount of Tokens in exchange reserves.
* @return Amount of Tokens bought.
*/
function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) {
require(input_reserve > 0 && output_reserve > 0);
uint256 input_amount_with_fee = input_amount.mul(1e18 - feeRate);
uint256 numerator = input_amount_with_fee.mul(output_reserve);
uint256 denominator = input_reserve.mul(1e18).add(input_amount_with_fee);
return numerator / denominator;
}
/**
* @dev Pricing function for converting between Tokens.
* @param output_amount Amount of Tokens being bought.
* @param input_reserve Amount of Tokens in exchange reserves.
* @param output_reserve Amount of Tokens in exchange reserves.
* @return Amount of Tokens sold.
*/
function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) {
require(input_reserve > 0 && output_reserve > 0);
uint256 numerator = input_reserve.mul(output_amount).mul(1e18);
uint256 denominator = (output_reserve.sub(output_amount)).mul(1e18 - feeRate);
return (numerator / denominator).add(1);
}
function CoinToTokenInput(address token, uint256 coin_sold, uint256 min_tokens, uint256 deadline, address buyer, address recipient) private returns (uint256) {
//check if such trading pair exists
require(totalSupply[uint256(token)] > 0);
require(deadline >= block.timestamp && coin_sold > 0 && min_tokens > 0);
updateGlobalIndex();
uint256 tokens_bought = getInputPrice(coin_sold, coinReserveOf(token), tokenReserveOf(token));
coinReserveShare[token] = coinReserveShare[token].add(coin_sold.mul(1e18)/globalIndex);
require(tokens_bought >= min_tokens);
checkAndWithdraw(token, recipient, tokens_bought);
depositAndTrigger(coin, buyer, coin_sold);
totalCoinStored = totalCoinStored.add(coin_sold);
emit TokenPurchase(buyer, token, coin_sold, tokens_bought);
return tokens_bought;
}
/**
* @notice Convert coin to tokens.
* @dev User specifies exact coin input && minium output.
* @param token Address of Tokens bought.
* @param coin_sold Amount of coin user wants to pay.
* @param min_tokens Minium Tokens bought.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of Tokens bought.
*/
function CoinToTokenSwapInput(address token, uint256 coin_sold, uint256 min_tokens, uint256 deadline) public returns (uint256) {
return CoinToTokenInput(token, coin_sold, min_tokens, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert coin to Tokens && transfers Tokens to recipient.
* @dev User specifies exact coin input && minium output.
* @param token Address of Tokens bought.
* @param coin_sold Amount of coin user wants to pay.
* @param min_tokens Minium Tokens bought.
* @param deadline Time after which this transaction can no longer be executed.
* @param recipient The addresss that recieves output Tokens.
* @return Amount of Token bought.
*/
function CoinToTokenTransferInput(address token, uint256 coin_sold, uint256 min_tokens, uint256 deadline, address recipient) public returns(uint256) {
require(recipient != address(this) && recipient != address(0));
return CoinToTokenInput(token, coin_sold, min_tokens, deadline, msg.sender, recipient);
}
function CoinToTokenOutput(address token, uint256 tokens_bought, uint256 max_coin, uint256 deadline, address buyer, address recipient) private returns (uint256) {
//check if such trading pair exists
require(totalSupply[uint256(token)] > 0);
require(deadline >= block.timestamp && tokens_bought > 0 && max_coin > 0);
updateGlobalIndex();
uint256 coin_sold = getOutputPrice(tokens_bought, coinReserveOf(token), tokenReserveOf(token));
coinReserveShare[token] = coinReserveShare[token].add(coin_sold.mul(1e18)/globalIndex);
require(coin_sold <= max_coin);
checkAndWithdraw(token, recipient, tokens_bought);
depositAndTrigger(coin, buyer, coin_sold);
totalCoinStored = totalCoinStored.add(coin_sold);
emit TokenPurchase(buyer, token, coin_sold, tokens_bought);
return coin_sold;
}
/**
* @notice Convert coin to Tokens.
* @dev User specifies maxium coin input && exact output.
* @param token Address of Tokens bought.
* @param tokens_bought Amount of token bought.
* @param max_coin Maxium amount of coin sold.
* @param deadline Time after which this transaction can be no longer be executed.
* @return Amount of coin sold.
*/
function CoinToTokenSwapOutput(address token, uint256 tokens_bought, uint256 max_coin, uint256 deadline) public returns(uint256) {
return CoinToTokenOutput(token, tokens_bought, max_coin, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert coin to Tokens && transfer Tokens to recipient.
* @dev User specifies maxium coin input && exact output.
* @param token Address of Tokens bought.
* @param tokens_bought Amount of token bought.
* @param max_coin Maxium amount of coin sold.
* @param deadline Time after which this transaction can be no longer be executed.
* @param recipient The address the receives output Tokens.
* @return Amount of coin sold.
*/
function CoinToTokenTransferOutput(address token, uint256 tokens_bought, uint256 max_coin, uint256 deadline, address recipient) public returns (uint256) {
require(recipient != address(this) && recipient != address(0));
return CoinToTokenOutput(token, tokens_bought, max_coin, deadline, msg.sender, recipient);
}
function tokenToCoinInput(address token, uint256 tokens_sold, uint256 min_coin, uint256 deadline, address buyer, address recipient) private returns (uint256) {
//check if such trading pair exists
require(totalSupply[uint256(token)] > 0);
require(deadline >= block.timestamp && tokens_sold > 0 && min_coin > 0);
updateGlobalIndex();
uint256 coin_bought = getInputPrice(tokens_sold, tokenReserveOf(token), coinReserveOf(token));
coinReserveShare[token] = coinReserveShare[token].sub(coin_bought.mul(1e18)/globalIndex);
require(coin_bought >= min_coin);
depositAndTrigger(token, buyer, tokens_sold);
checkAndWithdraw(coin, recipient, coin_bought);
totalCoinStored = totalCoinStored.sub(coin_bought);
emit CoinPurchase(buyer, token, tokens_sold, coin_bought);
return coin_bought;
}
/**
* @notice Convert Tokens to coin.
* @dev User specifies exact input && minium output.
* @param token Address of Tokens sold.
* @param tokens_sold Amount of Tokens sold.
* @param min_coin Minium coin purchased.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of coin bought.
*/
function tokenToCoinSwapInput(address token, uint256 tokens_sold, uint256 min_coin, uint256 deadline) public returns (uint256) {
return tokenToCoinInput(token, tokens_sold, min_coin, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert Tokens to coin && transfer coin to recipient.
* @dev User specifies exact input && minium output.
* @param token The address of Tokens sold.
* @param tokens_sold Amount of Tokens sold.
* @param min_coin Minium coin purchased.
* @param deadline Time after which this transaction can no longer be executed.
* @param recipient The address that receives output coin.
* @return Amount of coin bought.
*/
function tokenToCoinTransferInput(address token, uint256 tokens_sold, uint256 min_coin, uint256 deadline, address recipient) public returns (uint256) {
require(recipient != address(this) && recipient != address(0));
return tokenToCoinInput(token, tokens_sold, min_coin, deadline, msg.sender, recipient);
}
function tokenToCoinOutput(address token, uint256 coin_bought, uint256 max_tokens, uint256 deadline, address buyer, address recipient) private returns (uint256) {
//check if such trading pair exists
require(totalSupply[uint256(token)] > 0);
require(deadline >= block.timestamp && coin_bought > 0);
updateGlobalIndex();
uint256 tokens_sold = getOutputPrice(coin_bought, tokenReserveOf(token), coinReserveOf(token));
coinReserveShare[token] = coinReserveShare[token].sub(coin_bought.mul(1e18)/globalIndex);
require(max_tokens >= tokens_sold);
depositAndTrigger(token, buyer, tokens_sold);
checkAndWithdraw(coin, recipient, coin_bought);
totalCoinStored = totalCoinStored.sub(coin_bought);
emit CoinPurchase(buyer, token, tokens_sold, coin_bought);
return tokens_sold;
}
/**
* @notice Convert Tokens to coin.
* @dev User specifies maxium input && exact output.
* @param token Address of Tokens sold.
* @param coin_bought Amount of coin bought.
* @param max_tokens Maxium Tokens sold.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of Tokens sold.
*/
function tokenToCoinSwapOutput(address token, uint256 coin_bought, uint256 max_tokens, uint256 deadline) public returns (uint256) {
return tokenToCoinOutput(token, coin_bought, max_tokens, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert Tokens to coin && transfers coin to recipient.
* @dev User specifies maxium input && exact output.
* @param token Address of Tokens sold.
* @param coin_bought Amount of coin bought.
* @param max_tokens Maxium Tokens sold.
* @param deadline Time after which this transaction can no longer be executed.
* @param recipient The address that receives output coin.
* @return Amount of Tokens sold.
*/
function tokenToCoinTransferOutput(address token, uint256 coin_bought, uint256 max_tokens, uint256 deadline, address recipient) public returns (uint256) {
require(recipient != address(this) && recipient != address(0));
return tokenToCoinOutput(token, coin_bought, max_tokens, deadline, msg.sender, recipient);
}
function tokenToTokenInput(
address input_token,
address output_token,
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 deadline,
address buyer,
address recipient)
private returns (uint256)
{
//check not self-swapping
require(input_token != output_token);
//check if such trading pair exists
require(totalSupply[uint256(input_token)] > 0 && totalSupply[uint256(output_token)] > 0);
require(deadline >= block.timestamp && tokens_sold > 0 && min_tokens_bought > 0);
updateGlobalIndex();
uint256 coin_bought = getInputPrice(tokens_sold, tokenReserveOf(input_token), coinReserveOf(input_token));
uint256 token_bought = getInputPrice(coin_bought, coinReserveOf(output_token), tokenReserveOf(output_token));
// move coin reserve
coinReserveShare[input_token] = coinReserveShare[input_token].sub(coin_bought.mul(1e18)/globalIndex);
coinReserveShare[output_token] = coinReserveShare[output_token].add(coin_bought.mul(1e18)/globalIndex);
// do input/output token transfer
require(min_tokens_bought <= token_bought);
checkAndWithdraw(output_token, recipient, token_bought);
depositAndTrigger(input_token, buyer, tokens_sold);
emit CoinPurchase(buyer, input_token, tokens_sold, coin_bought);
emit TokenPurchase(buyer, output_token, coin_bought, token_bought);
return token_bought;
}
/**
* @notice Convert Tokens to Tokens.
* @dev User specifies exact input && minium output.
* @param input_token Address of Tokens sold.
* @param output_token Address of Tokens bought.
* @param tokens_sold Amount of Tokens sold.
* @param min_tokens_bought Minium amount of Tokens bought.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of Tokens bought.
*/
function tokenToTokenSwapInput(
address input_token,
address output_token,
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 deadline)
public returns (uint256)
{
return tokenToTokenInput(input_token, output_token, tokens_sold, min_tokens_bought, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert Tokens to Tokens && transfers Tokens to recipient.
* @dev User specifies exact input && minium output.
* @param input_token Address of Tokens sold.
* @param output_token Address of Tokens bought.
* @param tokens_sold Amount of Tokens sold.
* @param min_tokens_bought Minium amount of Tokens bought.
* @param deadline Time after which this transaction can no longer be executed.
* @param recipient The address that recieves output token.
* @return Amount of Tokens bought.
*/
function tokenToTokenTransferInput(
address input_token,
address output_token,
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 deadline,
address recipient)
public returns (uint256)
{
return tokenToTokenInput(input_token, output_token, tokens_sold, min_tokens_bought, deadline, msg.sender, recipient);
}
function tokenToTokenOutput(
address input_token,
address output_token,
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 deadline,
address buyer,
address recipient)
private returns (uint256)
{
//check not self-swapping
require(input_token != output_token);
//check if such trading pair exists
require(totalSupply[uint256(input_token)] > 0 && totalSupply[uint256(output_token)] > 0);
require(deadline >= block.timestamp && tokens_bought > 0);
updateGlobalIndex();
uint256 coin_bought = getOutputPrice(tokens_bought, coinReserveOf(output_token), tokenReserveOf(output_token));
uint256 tokens_sold;
tokens_sold = tokenToTokenOutputHelper(input_token,coin_bought);
// move coin reserve
coinReserveShare[input_token] = coinReserveShare[input_token].sub(coin_bought.mul(1e18)/globalIndex);
coinReserveShare[output_token] = coinReserveShare[output_token].add(coin_bought.mul(1e18)/globalIndex);
require(max_tokens_sold >= tokens_sold);
checkAndWithdraw(output_token, recipient, tokens_bought);
depositAndTrigger(input_token, buyer, tokens_sold);
emit CoinPurchase(buyer, input_token, tokens_sold, coin_bought);
emit TokenPurchase(buyer, output_token, coin_bought, tokens_bought);
return tokens_sold;
}
function tokenToTokenOutputHelper(address input_token, uint256 coin_bought) private view returns(uint256) {
uint256 tokens_sold = getOutputPrice(coin_bought, tokenReserveOf(input_token), coinReserveOf(input_token));
return tokens_sold;
}
/**
* @notice Convert Tokens to Tokens.
* @dev User specifies maxium input && exact output.
* @param input_token Address of Tokens sold.
* @param output_token Address of Tokens bought.
* @param tokens_bought Amount of Tokens bought.
* @param max_tokens_sold Maxium amount of Tokens sold.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of Tokens sold.
*/
function tokenToTokenSwapOutput(
address input_token,
address output_token,
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 deadline)
public returns (uint256)
{
return tokenToTokenOutput(input_token, output_token, tokens_bought, max_tokens_sold, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert Tokens to Tokens && transfers Tokens to recipient.
* @dev User specifies maxium input && exact output.
* @param input_token Address of Tokens sold.
* @param output_token Address of Tokens bought.
* @param tokens_bought Amount of Tokens bought.
* @param max_tokens_sold Maxium amount of Tokens sold.
* @param deadline Time after which this transaction can no longer be executed.
* @param recipient The address that receives output Tokens.
* @return Amount of Tokens sold.
*/
function tokenToTokenTransferOutput(
address input_token,
address output_token,
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 deadline,
address recipient)
public returns (uint256)
{
return tokenToTokenOutput(input_token, output_token, tokens_bought, max_tokens_sold, deadline, msg.sender, recipient);
}
/***********************************|
| Getter Functions |
|__________________________________*/
/**
* @notice Public price function for coin to Token trades with an exact input.
* @param token address of token bought.
* @param coin_sold Amount of coin sold.
* @return Amount of Tokens that can be bought with input coin.
*/
function getCoinToTokenInputPrice(address token, uint256 coin_sold) public view returns (uint256) {
require(coin_sold > 0);
return getInputPrice(coin_sold, coinReserveOf(token), tokenReserveOf(token));
}
/**
* @notice Public price function for coin to Token trades with an exact output.
* @param token address of token to buy.
* @param tokens_bought Amount of Tokens bought.
* @return Amount of coin needed to buy output Tokens.
*/
function getCoinToTokenOutputPrice(address token, uint256 tokens_bought) public view returns (uint256) {
require(tokens_bought > 0);
return getOutputPrice(tokens_bought, coinReserveOf(token), tokenReserveOf(token));
}
/**
* @notice Public price function for Token to coin trades with an exact input.
* @param token address of token sold.
* @param tokens_sold Amount of Tokens sold.
* @return Amount of coin that can be bought with input Tokens.
*/
function getTokenToCoinInputPrice(address token, uint256 tokens_sold) public view returns (uint256) {
require(tokens_sold > 0);
return getInputPrice(tokens_sold, tokenReserveOf(token), coinReserveOf(token));
}
/**
* @notice Public price function for Token to coin trades with an exact output.
* @param token address of token sold.
* @param coin_bought Amount of output coin.
* @return Amount of Tokens needed to buy output coin.
*/
function getTokenToCoinOutputPrice(address token, uint256 coin_bought) public view returns (uint256) {
require(coin_bought > 0);
return getOutputPrice(coin_bought, tokenReserveOf(token), coinReserveOf(token));
}
/***********************************|
| Liquidity Functions |
|__________________________________*/
/**
* @notice Deposit coin && Tokens at current ratio to mint liquidity tokens.
* @dev min_liquidity does nothing when total liquidity supply is 0.
* @param token Address of Tokens reserved
* @param reserve_added Amount of coin reserved
* @param min_liquidity Minium number of liquidity sender will mint if total liquidity supply is greater than 0.
* @param max_tokens Maxium number of tokens deposited. Deposits max amount if total liquidity supply is 0.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of Liquidity minted
*/
function addLiquidity(address token, uint256 reserve_added, uint256 min_liquidity, uint256 max_tokens, uint256 deadline) public payable returns (uint256) {
require(deadline >= block.timestamp && max_tokens > 0 && reserve_added > 0);
require(token != coin);
uint256 total_liquidity = totalSupply[uint256(token)];
if (total_liquidity > 0) {
require(min_liquidity > 0);
updateGlobalIndex();
uint256 token_amount = (reserve_added.mul(tokenReserveOf(token)) / coinReserveOf(token)).add(1);
uint256 liquidity_minted = reserve_added.mul(total_liquidity) / coinReserveOf(token);
require(max_tokens >= token_amount && liquidity_minted >= min_liquidity);
balances[uint256(token)][msg.sender] = balances[uint256(token)][msg.sender].add(liquidity_minted);
totalSupply[uint256(token)] = total_liquidity.add(liquidity_minted);
coinReserveShare[token] = coinReserveShare[token].add(reserve_added.mul(1e18)/globalIndex);
depositAndTrigger(token, msg.sender, token_amount);
depositAndTrigger(coin, msg.sender, reserve_added);
totalCoinStored = totalCoinStored.add(reserve_added);
emit AddLiquidity(msg.sender, token, reserve_added, token_amount);
emit TransferSingle(msg.sender, address(0), msg.sender, uint256(token), liquidity_minted);
return liquidity_minted;
} else {
require(reserve_added >= 1000000000);
uint256 token_amount = max_tokens;
uint256 initial_liquidity = reserve_added;
totalSupply[uint256(token)] = initial_liquidity;
balances[uint256(token)][msg.sender] = initial_liquidity;
coinReserveShare[token] = coinReserveShare[token].add(reserve_added.mul(1e18)/globalIndex);
depositAndTrigger(token, msg.sender, token_amount);
depositAndTrigger(coin, msg.sender, reserve_added);
totalCoinStored = totalCoinStored.add(reserve_added);
emit AddLiquidity(msg.sender, token, reserve_added, token_amount);
emit TransferSingle(msg.sender, address(0), msg.sender, uint256(token), initial_liquidity);
return initial_liquidity;
}
}
/**
* @notice Withdraw coin && Tokens at current ratio to burn liquidity tokens.
* @dev Burn liquidity tokens to withdraw coin && Tokens at current ratio.
* @param token Address of Tokens withdrawn.
* @param amount Amount of liquidity burned.
* @param min_coin Minium coin withdrawn.
* @param min_tokens Minium Tokens withdrawn.
* @param deadline Time after which this transaction can no longer be executed.
* @return The amount of coin && Tokens withdrawn.
*/
function removeLiquidity(address token, uint256 amount, uint256 min_coin, uint256 min_tokens, uint256 deadline) public returns (uint256, uint256) {
require(amount > 0 && deadline >= block.timestamp && min_coin > 0 && min_tokens > 0);
uint256 total_liquidity = totalSupply[uint256(token)];
require(total_liquidity > 0);
updateGlobalIndex();
uint256 coin_amount = amount.mul(coinReserveOf(token)) / total_liquidity;
uint256 token_amount = amount.mul(tokenReserveOf(token)) / total_liquidity;
require(coin_amount >= min_coin && token_amount >= min_tokens);
balances[uint256(token)][msg.sender] = balances[uint256(token)][msg.sender].sub(amount);
totalSupply[uint256(token)] = total_liquidity.sub(amount);
coinReserveShare[token] = coinReserveShare[token].sub(coin_amount.mul(1e18)/globalIndex);
checkAndWithdraw(token, msg.sender, token_amount);
checkAndWithdraw(coin, msg.sender, coin_amount);
totalCoinStored = totalCoinStored.sub(coin_amount);
emit RemoveLiquidity(msg.sender, token, coin_amount, token_amount);
emit TransferSingle(msg.sender, msg.sender, address(0), uint256(token), amount);
return (coin_amount, token_amount);
}
/***********************************|
| SAFE Token Transfer |
|__________________________________*/
function doTransferIn(address tokenAddr, address from, uint amount) internal returns (bool result) {
ERC20NonStandard token = ERC20NonStandard(tokenAddr);
token.transferFrom(from, address(this), amount);
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
}
function doTransferOut(address tokenAddr, address to, uint amount) internal returns (bool result) {
ERC20NonStandard token = ERC20NonStandard(tokenAddr);
token.transfer(to, amount);
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
}
function doApproval(address tokenAddr, address to, uint amount) internal returns(bool result) {
ERC20NonStandard token = ERC20NonStandard(tokenAddr);
token.approve(to, amount);
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
}
}
|
Public price function for Token to coin trades with an exact output. token address of token sold. coin_bought Amount of output coin. return Amount of Tokens needed to buy output coin./
|
function getTokenToCoinOutputPrice(address token, uint256 coin_bought) public view returns (uint256) {
require(coin_bought > 0);
return getOutputPrice(coin_bought, tokenReserveOf(token), coinReserveOf(token));
}
|__________________________________*/
| 12,610,279 |
./full_match/5/0xF75A8C232e57AB589035cB269E7268e0eb02213b/sources/sir.sol
|
Sets maximum sell amount in percent. percent_ uint256 max sell in percent of liquidity. Reqired: - percent_ 1 to 10 Emits: {ChangedMaxSellAmountPercent} uint256 previous, uint256 percent./
|
function setMaxSellAmountPercent(
uint256 percent_
) external onlyOwner {
require(percent_ >= 1 && percent_ <= 10, "1-10");
uint256 previous = Max.sellAmountPercent;
Max.sellAmountPercent = percent_.mul(100);
emit MaxSellAmountPercentChanged(previous, percent_);
}
| 1,893,777 |
pragma solidity ^0.4.19;
import "./lib/usingOraclize.sol";
import "./lib/SafeMath.sol";
contract Betting is usingOraclize {
using SafeMath for uint256; //using safemath
bytes32 coin_pointer; // variable to differentiate different callbacks
bytes32 temp_ID; // temp variable to store oraclize IDs
uint countdown=3; // variable to check if all prices are received
address public owner; //owner address
uint public kickStarter = 0; // ethers to kickcstart the oraclize queries
uint public winnerPoolTotal;
string public constant version = "0.2.1.beta";
struct chronus_info {
bool betting_open; // boolean: check if betting is open
bool race_start; //boolean: check if race has started
bool race_end; //boolean: check if race has ended
bool voided_bet; //boolean: check if race has been voided
uint starting_time; // timestamp of when the race starts
uint betting_duration;
uint race_duration; // duration of the race
uint voided_timestamp;
}
struct horses_info{
int BTC_delta; //horses.BTC delta value
int ETH_delta; //horses.ETH delta value
int LTC_delta; //horses.LTC delta value
bytes32 BTC; //32-bytes equivalent of horses.BTC
bytes32 ETH; //32-bytes equivalent of horses.ETH
bytes32 LTC; //32-bytes equivalent of horses.LTC
uint customGasLimit;
}
struct bet_info{
bytes32 horse; // coin on which amount is bet on
uint amount; // amount bet by Bettor
}
struct coin_info{
uint total; // total coin pool
uint pre; // locking price
uint post; // ending price
uint count; // number of bets
bool price_check; // boolean: differentiating pre and post prices
}
struct voter_info {
uint bet_count; //number of bets
bool rewarded; // boolean: check for double spending
bet_info[] bets; //array of bets
}
mapping (bytes32 => bytes32) oraclizeIndex; // mapping oraclize IDs with coins
mapping (bytes32 => coin_info) coinIndex; // mapping coins with pool information
mapping (address => voter_info) voterIndex; // mapping voter address with Bettor information
uint public total_reward; // total reward to be awarded
mapping (bytes32 => bool) public winner_horse;
// tracking events
event newOraclizeQuery(string description);
event newPriceTicker(uint price);
event Deposit(address _from, uint256 _value);
event Withdraw(address _to, uint256 _value);
// constructor
function Betting() payable {
//oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
owner = msg.sender;
kickStarter = kickStarter.add(msg.value);
// oraclize_setCustomGasPrice(10000000000 wei);
horses.BTC = bytes32("BTC");
horses.ETH = bytes32("ETH");
horses.LTC = bytes32("LTC");
horses.customGasLimit = 300000;
}
// data access structures
horses_info public horses;
chronus_info public chronus;
// modifiers for restricting access to methods
modifier onlyOwner {
require(owner == msg.sender);
_;
}
modifier duringBetting {
require(chronus.betting_open);
_;
}
modifier beforeBetting {
require(!chronus.betting_open && !chronus.race_start);
_;
}
modifier afterRace {
require(chronus.race_end);
_;
}
//oraclize callback method
function __callback(bytes32 myid, string result, bytes proof) {
require (msg.sender == oraclize_cbAddress());
chronus.race_start = true;
chronus.betting_open = false;
coin_pointer = oraclizeIndex[myid];
if (!coinIndex[coin_pointer].price_check) {
coinIndex[coin_pointer].pre = stringToUintNormalize(result);
coinIndex[coin_pointer].price_check = true;
newPriceTicker(coinIndex[coin_pointer].pre);
} else if (coinIndex[coin_pointer].price_check){
coinIndex[coin_pointer].post = stringToUintNormalize(result);
newPriceTicker(coinIndex[coin_pointer].post);
countdown = countdown - 1;
if (countdown == 0) {
reward();
}
}
}
// place a bet on a coin(horse) lockBetting
function placeBet(bytes32 horse) external duringBetting payable {
require(msg.value >= 0.01 ether);
bet_info memory current_bet;
current_bet.amount = msg.value;
current_bet.horse = horse;
voterIndex[msg.sender].bets.push(current_bet);
voterIndex[msg.sender].bet_count = voterIndex[msg.sender].bet_count.add(1);
coinIndex[horse].total = (coinIndex[horse].total).add(msg.value);
coinIndex[horse].count = coinIndex[horse].count.add(1);
Deposit(msg.sender, msg.value);
}
// fallback method for accepting payments
function () private payable {}
// method to place the oraclize queries
function setupRace(uint delay, uint locking_duration) onlyOwner beforeBetting payable returns(bool) {
if (oraclize_getPrice("URL") > (this.balance)/6) {
newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
return false;
} else {
chronus.starting_time = block.timestamp;
chronus.betting_open = true;
newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
// bets open price query
delay = delay.add(60); //slack time 1 minute
chronus.betting_duration = delay;
temp_ID = oraclize_query(delay, "URL", "json(http://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd");
oraclizeIndex[temp_ID] = horses.ETH;
temp_ID = oraclize_query(delay, "URL", "json(http://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd");
oraclizeIndex[temp_ID] = horses.LTC;
temp_ID = oraclize_query(delay, "URL", "json(http://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd");
oraclizeIndex[temp_ID] = horses.BTC;
//bets closing price query
delay = delay.add(locking_duration);
temp_ID = oraclize_query(delay, "URL", "json(http://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd",horses.customGasLimit);
oraclizeIndex[temp_ID] = horses.ETH;
temp_ID = oraclize_query(delay, "URL", "json(http://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd",horses.customGasLimit);
oraclizeIndex[temp_ID] = horses.LTC;
temp_ID = oraclize_query(delay, "URL", "json(http://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd",horses.customGasLimit);
oraclizeIndex[temp_ID] = horses.BTC;
chronus.race_duration = delay;
return true;
}
}
// method to calculate reward (called internally by callback)
function reward() internal {
/*
calculating the difference in price with a precision of 5 digits
not using safemath since signed integers are handled
*/
horses.BTC_delta = int(coinIndex[horses.BTC].post - coinIndex[horses.BTC].pre)*10000/int(coinIndex[horses.BTC].pre);
horses.ETH_delta = int(coinIndex[horses.ETH].post - coinIndex[horses.ETH].pre)*10000/int(coinIndex[horses.ETH].pre);
horses.LTC_delta = int(coinIndex[horses.LTC].post - coinIndex[horses.LTC].pre)*10000/int(coinIndex[horses.LTC].pre);
total_reward = coinIndex[horses.BTC].total.add(coinIndex[horses.ETH].total).add(coinIndex[horses.LTC].total);
uint house_fee = total_reward.mul(5).div(100);
// house_fee = house_fee.add(kickStarter);
require(house_fee < this.balance);
total_reward = total_reward.sub(house_fee);
owner.transfer(house_fee);
if (horses.BTC_delta > horses.ETH_delta) {
if (horses.BTC_delta > horses.LTC_delta) {
winner_horse[horses.BTC] = true;
winnerPoolTotal = coinIndex[horses.BTC].total;
}
else if(horses.LTC_delta > horses.BTC_delta) {
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.LTC].total;
} else {
winner_horse[horses.BTC] = true;
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.BTC].total.add(coinIndex[horses.LTC].total);
}
} else if(horses.ETH_delta > horses.BTC_delta) {
if (horses.ETH_delta > horses.LTC_delta) {
winner_horse[horses.ETH] = true;
winnerPoolTotal = coinIndex[horses.ETH].total;
}
else if (horses.LTC_delta > horses.ETH_delta) {
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.LTC].total;
} else {
winner_horse[horses.ETH] = true;
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.ETH].total.add(coinIndex[horses.LTC].total);
}
} else {
if (horses.LTC_delta > horses.ETH_delta) {
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.LTC].total;
} else if(horses.LTC_delta < horses.ETH_delta){
winner_horse[horses.ETH] = true;
winner_horse[horses.BTC] = true;
winnerPoolTotal = coinIndex[horses.ETH].total.add(coinIndex[horses.BTC].total);
} else {
winner_horse[horses.LTC] = true;
winner_horse[horses.ETH] = true;
winner_horse[horses.BTC] = true;
winnerPoolTotal = coinIndex[horses.ETH].total.add(coinIndex[horses.BTC].total).add(coinIndex[horses.LTC].total);
}
}
chronus.race_end = true;
}
// method to calculate an invidual's reward
function calculateReward(address candidate) internal afterRace constant returns(uint winner_reward) {
uint i;
voter_info bettor = voterIndex[candidate];
if (!chronus.voided_bet) {
for(i=0; i<bettor.bet_count; i++) {
if (winner_horse[bettor.bets[i].horse]) {
winner_reward += (((total_reward.mul(10000000)).div(winnerPoolTotal)).mul(bettor.bets[i].amount)).div(10000000);
}
}
} else {
for(i=0; i<bettor.bet_count; i++) {
winner_reward += bettor.bets[i].amount;
}
}
}
// method to just check the reward amount
function checkReward() afterRace constant returns (uint) {
require(!voterIndex[msg.sender].rewarded);
return calculateReward(msg.sender);
}
// method to claim the reward amount
function claim_reward() afterRace {
require(!voterIndex[msg.sender].rewarded);
uint transfer_amount = calculateReward(msg.sender);
require(this.balance > transfer_amount);
voterIndex[msg.sender].rewarded = true;
msg.sender.transfer(transfer_amount);
Withdraw(msg.sender, transfer_amount);
}
// utility function to convert string to integer with precision consideration
function stringToUintNormalize(string s) constant returns (uint result) {
uint p =2;
bool precision=false;
bytes memory b = bytes(s);
uint i;
result = 0;
for (i = 0; i < b.length; i++) {
if (precision) {p = p-1;}
if (uint(b[i]) == 46){precision = true;}
uint c = uint(b[i]);
if (c >= 48 && c <= 57) {result = result * 10 + (c - 48);}
if (precision && p == 0){return result;}
}
while (p!=0) {
result = result*10;
p=p-1;
}
}
// exposing the coin pool details for DApp
function getCoinIndex(bytes32 index) constant returns (uint, uint, uint, bool, uint) {
return (coinIndex[index].total, coinIndex[index].pre, coinIndex[index].post, coinIndex[index].price_check, coinIndex[index].count);
}
// exposing the total reward amount for DApp
function reward_total() constant returns (uint) {
return (coinIndex[horses.BTC].total.add(coinIndex[horses.ETH].total).add(coinIndex[horses.LTC].total));
}
function getVoterIndex() constant returns (uint, bytes32, uint) {
voter_info voterInfoTemp = voterIndex[msg.sender];
return (voterInfoTemp.bet_count, voterInfoTemp.bets[0].horse, voterInfoTemp.bets[0].amount);
}
// in case of any errors in race, enable full refund for the Bettors to claim
function refund() onlyOwner {
require(now > chronus.starting_time.add(chronus.race_duration));
require((chronus.betting_open && !chronus.race_start)
|| (chronus.race_start && !chronus.race_end));
chronus.voided_bet = true;
chronus.race_end = true;
chronus.voided_timestamp=now;
}
// method to claim unclaimed winnings after 30 day notice period
function recovery() onlyOwner{
require((chronus.race_end && now > chronus.starting_time.add(chronus.race_duration).add(30 days))
|| (chronus.voided_bet && now > chronus.voided_timestamp.add(30 days)));
owner.transfer(this.balance);
}
}
|
method to calculate an invidual's reward
|
function calculateReward(address candidate) internal afterRace constant returns(uint winner_reward) {
uint i;
voter_info bettor = voterIndex[candidate];
if (!chronus.voided_bet) {
for(i=0; i<bettor.bet_count; i++) {
if (winner_horse[bettor.bets[i].horse]) {
winner_reward += (((total_reward.mul(10000000)).div(winnerPoolTotal)).mul(bettor.bets[i].amount)).div(10000000);
}
}
for(i=0; i<bettor.bet_count; i++) {
winner_reward += bettor.bets[i].amount;
}
}
}
| 12,734,284 |
./full_match/80001/0x136Ac3bb01Fa4b34c6a69766e08692D06c5eEf4E/sources/contracts/Contract.sol
|
Resolves 'stack too deep' error in `recoverAddress`.
|
function _encodeRequest(
MintRequest calldata _req
) internal pure returns (bytes memory) {
bytes32[] memory stringHashes = new bytes32[](_req.uris.length);
for (uint i = 0; i < _req.uris.length; i++) {
stringHashes[i] = keccak256(abi.encode(_req.uris[i]));
}
return
abi.encode(
TYPEHASH,
_req.to,
keccak256(abi.encode(_req.uris)),
keccak256(abi.encode(_req.candyTokenIds)),
keccak256(abi.encode(_req.pebbleNftTokenIds)),
_req.validityStartTimestamp,
_req.validityEndTimestamp,
_req.uid
);
}
| 5,631,263 |
./partial_match/1/0x6477960dd932d29518D7e8087d5Ea3D11E606068/sources/Component.sol
|
views the total amount of liquidity in the component in numeraire value and format - 18 decimals return total_ the total value in the component return individual_ the individual values in the component
|
function liquidity () public view returns (
uint total_,
uint[] memory individual_
) {
return ViewLiquidity.viewLiquidity(component);
}
| 4,270,223 |
./full_match/42161/0xAdaFb1A4b2aFec44586BdcF253d4AC69A1b1D6e1/sources/contracts/Arbdegens.sol
|
Function to withdraw stuck funds Withdraw ETH Withdraw ERC20 tokens
|
function withdrawStuckFunds(address _token) public {
require(msg.sender == communityVault, "Only the community vault can withdraw stuck funds");
if (_token == address(0)) {
uint256 ethBalance = address(this).balance;
payable(communityVault).transfer(ethBalance);
IERC20 token = IERC20(_token);
uint256 tokenBalance = token.balanceOf(address(this));
token.safeTransfer(communityVault, tokenBalance);
}
}
| 16,298,721 |
// SPDX-License-Identifier: GPL-3.0
// solhint-disable no-unused-vars
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "./XPowerNft.sol";
import "./XPowerNftStaked.sol";
/**
* NFT treasury to stake and unstake XPowerNft(s).
*/
contract NftTreasury is ERC1155Holder {
/** normal proof-of-work NFTs */
XPowerNft private _nft;
/** staked proof-of-work NFTs */
XPowerNftStaked private _nftStaked;
/** @param nft address of contract for normal NFTs */
/** @param nftStaked address of contract for staked NFTs */
constructor(address nft, address nftStaked) {
_nft = XPowerNft(nft);
_nftStaked = XPowerNftStaked(nftStaked);
}
/** emitted on staking an NFT */
event Stake(address from, uint256 nftId, uint256 amount);
/** stake NFT for given address and amount */
function stake(
address from,
uint256 nftId,
uint256 amount
) public {
require(amount > 0, "non-positive amount");
address self = (address)(this);
_nft.safeTransferFrom(from, self, nftId, amount, "");
_nftStaked.mint(from, nftId, amount);
emit Stake(from, nftId, amount);
}
/** emitted on staking NFTs */
event StakeBatch(address from, uint256[] nftIds, uint256[] amounts);
/** stake NFTs for given address and amounts */
function stakeBatch(
address from,
uint256[] memory nftIds,
uint256[] memory amounts
) public {
for (uint256 i = 0; i < amounts.length; i++) {
require(amounts[i] > 0, "non-positive amount");
}
address self = (address)(this);
_nft.safeBatchTransferFrom(from, self, nftIds, amounts, "");
_nftStaked.mintBatch(from, nftIds, amounts);
emit StakeBatch(from, nftIds, amounts);
}
/** emitted on unstaking an NFT */
event Unstake(address from, uint256 nftId, uint256 amount);
/** unstake NFT for given address and amount */
function unstake(
address from,
uint256 nftId,
uint256 amount
) public {
require(amount > 0, "non-positive amount");
address self = (address)(this);
_nftStaked.burn(from, nftId, amount);
_nft.safeTransferFrom(self, from, nftId, amount, "");
emit Unstake(from, nftId, amount);
}
/** emitted on unstaking NFTs */
event UnstakeBatch(address from, uint256[] nftIds, uint256[] amounts);
/** unstake NFTs for given address and amounts */
function unstakeBatch(
address from,
uint256[] memory nftIds,
uint256[] memory amounts
) public {
for (uint256 i = 0; i < amounts.length; i++) {
require(amounts[i] > 0, "non-positive amount");
}
address self = (address)(this);
_nftStaked.burnBatch(from, nftIds, amounts);
_nft.safeBatchTransferFrom(self, from, nftIds, amounts, "");
emit UnstakeBatch(from, nftIds, amounts);
}
}
|
stake NFT for given address and amount /
|
function stake(
address from,
uint256 nftId,
uint256 amount
) public {
require(amount > 0, "non-positive amount");
address self = (address)(this);
_nft.safeTransferFrom(from, self, nftId, amount, "");
_nftStaked.mint(from, nftId, amount);
emit Stake(from, nftId, amount);
}
| 13,084,211 |
./partial_match/1/0x1235f1b60df026B2620e48E735C422425E06b725/sources/contracts/src/TUPProxy.sol
|
Overrides the fallback method to check if system is not paused before Address Zero is allowed to perform calls even if system is paused. This allows view functions to be called when the system is paused as rpc providers can easily set the sender address to zero.
|
function _beforeFallback() internal override {
if (!StorageSlot.getBooleanSlot(_PAUSE_SLOT).value || msg.sender == address(0)) {
super._beforeFallback();
revert CallWhenPaused();
}
}
| 4,316,191 |
./full_match/84531/0xA943C5e9840c9D2b1D49195e750eBC80CE27426E/sources/contracts/oracle/OracleRouter.sol
|
The price feed contract to use for a particular asset. asset address of the asset/ Chainlink: DAI/USD Chainlink: USDC/USD Chainlink: USDT/USD Chainlink: COMP/USD Chainlink: AAVE/USD Chainlink: CRV/USD Chainlink: CVX/USD
|
function feed(address asset) internal pure override returns (address) {
if (asset == address(0x6B175474E89094C44Da98b954EedeAC495271d0F)) {
return address(0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9);
} else if (
asset == address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)
) {
return address(0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f6);
} else if (
asset == address(0xdAC17F958D2ee523a2206206994597C13D831ec7)
) {
return address(0x3E7d1eAB13ad0104d2750B8863b489D65364e32D);
} else if (
asset == address(0xc00e94Cb662C3520282E6f5717214004A7f26888)
) {
return address(0xdbd020CAeF83eFd542f4De03e3cF0C28A4428bd5);
} else if (
asset == address(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9)
) {
return address(0x547a514d5e3769680Ce22B2361c10Ea13619e8a9);
} else if (
asset == address(0xD533a949740bb3306d119CC777fa900bA034cd52)
) {
return address(0xCd627aA160A6fA45Eb793D19Ef54f5062F20f33f);
} else if (
asset == address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B)
) {
return address(0xd962fC30A72A84cE50161031391756Bf2876Af5D);
revert("Asset not available");
}
}
| 11,529,107 |
./partial_match/1/0xe300C0DBDd784Cc2CD1A86b2126Fc95629389F91/sources/contracts/interfaces/ISpigotedLine.sol
|
Log how many revenue tokens are used to repay debt after claimAndRepay dont need to track value like other events because _repay already emits that Mainly used to log debt that is paid via Spigot directly vs other sources. Without this event it's a lot harder to parse that offchain. Log many revenue tokens were traded for credit tokens. differs from Revenue Payment because we trade revenue at different times from repaying with revenue Can you use to figure out price of revenue tokens offchain since we only have an oracle for credit tokens Revenue tokens might be reserves or just claimed from Spigot. Borrower functions Spigot management functions getters
|
interface ISpigotedLine {
event RevenuePayment(address indexed token, uint256 indexed amount);
error ReservesOverdrawn(uint256 totalAvailable);
event TradeSpigotRevenue(
address indexed revenueToken,
uint256 revenueTokenAmount,
address indexed debtToken,
uint256 indexed debtTokensBought
);
function useAndRepay(uint256 amount) external returns (bool);
- see SpigotedLine._claimAndTrade and SpigotedLineLib.claimAndTrade for more details on Spigot and trading logic
function claimAndRepay(address claimToken, bytes calldata zeroExTradeData) external returns (uint256);
- sends all bought tokens to `unused` to be repaid later
function claimAndTrade(address claimToken, bytes calldata zeroExTradeData) external returns (uint256 tokensBought);
function addSpigot(address revenueContract, ISpigot.Setting calldata setting) external returns (bool);
function updateWhitelist(bytes4 func, bool allowed) external returns (bool);
function updateOwnerSplit(address revenueContract) external returns (bool);
or to the Arbiter (if the Line of Credit is liquidatable).
function releaseSpigot(address to) external returns (bool);
- does not send tokens out if line is ACTIVE
function sweep(address to, address token) external returns (uint256);
function unused(address token) external returns (uint256);
function spigot() external returns (ISpigot);
import {ISpigot} from "./ISpigot.sol";
}
| 15,654,300 |
./partial_match/1/0xB571eFe897F38C6cB03c42decb15a5f57BB62A75/sources/HairyPlotterSBFCoin.sol
|
Requirements: - The divisor cannot be zero./
|
{
unchecked
consuming all remaining gas).
function mod(
uint256 a
,
uint256 b
,
string memory errorMessage
)
internal pure returns
(uint256)
{
require
(b > 0,
errorMessage
)
;
return a % b;
}
}
| 11,024,955 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../libs/BaseRelayRecipient.sol";
interface ICitadelStrategy {
function getCurrentPool() external view returns (uint256);
function invest(uint256 _amount) external;
function yield() external;
function withdraw(uint256 _amount) external;
function reimburse() external;
function setAdmin(address _admin) external;
function setStrategist(address _strategist) external;
function emergencyWithdraw() external;
function reinvest() external;
}
interface IRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint[] memory amounts);
}
interface ICurveSwap {
function exchange(int128 i, int128 j, uint256 _dx, uint256 _min_dy) external;
}
interface IChainlink {
function latestAnswer() external view returns (int256);
}
contract CitadelVault is ERC20("DAO Vault Citadel", "daoCDV"), Ownable, BaseRelayRecipient {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct Token {
IERC20 token;
uint256 decimals;
uint256 percKeepInVault;
}
IERC20 private constant WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
ICitadelStrategy public strategy;
IRouter private constant router = IRouter(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
ICurveSwap private constant c3pool = ICurveSwap(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
uint256 private constant DENOMINATOR = 10000;
address public pendingStrategy;
bool public canSetPendingStrategy;
uint256 public unlockTime;
uint256 public constant LOCKTIME = 2 days;
// Calculation for fees
uint256[] public networkFeeTier2 = [50000*1e18+1, 100000*1e18];
uint256 public customNetworkFeeTier = 1000000*1e18;
uint256[] public networkFeePerc = [100, 75, 50];
uint256 public customNetworkFeePerc = 25;
uint256 public profitSharingFeePerc = 2000;
uint256 private _fees; // 18 decimals
// Address to collect fees
address public treasuryWallet;
address public communityWallet;
address public admin;
address public strategist;
mapping(address => uint256) public _balanceOfDeposit; // Record deposit amount (USD in 18 decimals)
mapping(uint256 => Token) private Tokens;
event Deposit(address indexed tokenDeposit, address caller, uint256 amtDeposit, uint256 sharesMint);
event Withdraw(address indexed tokenWithdraw, address caller, uint256 amtWithdraw, uint256 sharesBurn);
event TransferredOutFees(uint256 fees);
event ETHToInvest(uint256 _balanceOfWETH);
event SetNetworkFeeTier2(uint256[] oldNetworkFeeTier2, uint256[] newNetworkFeeTier2);
event SetNetworkFeePerc(uint256[] oldNetworkFeePerc, uint256[] newNetworkFeePerc);
event SetCustomNetworkFeeTier(uint256 indexed oldCustomNetworkFeeTier, uint256 indexed newCustomNetworkFeeTier);
event SetCustomNetworkFeePerc(uint256 oldCustomNetworkFeePerc, uint256 newCustomNetworkFeePerc);
event SetProfitSharingFeePerc(uint256 indexed oldProfileSharingFeePerc, uint256 indexed newProfileSharingFeePerc);
event MigrateFunds(address indexed fromStrategy, address indexed toStrategy, uint256 amount);
modifier onlyAdmin {
require(msg.sender == address(admin), "Only admin");
_;
}
constructor(
address _strategy,
address _treasuryWallet, address _communityWallet,
address _admin, address _strategist,
address _biconomy
) {
strategy = ICitadelStrategy(_strategy);
treasuryWallet = _treasuryWallet;
communityWallet = _communityWallet;
admin = _admin;
strategist = _strategist;
trustedForwarder = _biconomy;
IERC20 USDT = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
Tokens[0] = Token(USDT, 6, 200);
Tokens[1] = Token(USDC, 6, 200);
Tokens[2] = Token(DAI, 18, 200);
WETH.safeApprove(_strategy, type(uint256).max);
WETH.safeApprove(address(router), type(uint256).max);
USDT.safeApprove(address(router), type(uint256).max);
USDT.safeApprove(address(c3pool), type(uint256).max);
USDC.safeApprove(address(router), type(uint256).max);
USDC.safeApprove(address(c3pool), type(uint256).max);
DAI.safeApprove(address(router), type(uint256).max);
DAI.safeApprove(address(c3pool), type(uint256).max);
canSetPendingStrategy = true;
}
/// @notice Function that required for inherict BaseRelayRecipient
function _msgSender() internal override(Context, BaseRelayRecipient) view returns (address payable) {
return BaseRelayRecipient._msgSender();
}
/// @notice Function that required for inherict BaseRelayRecipient
function versionRecipient() external pure override returns (string memory) {
return "1";
}
/// @notice Function to deposit stablecoins
/// @param _amount Amount to deposit
/// @param _tokenIndex Type of stablecoin to deposit
function deposit(uint256 _amount, uint256 _tokenIndex) external {
require(msg.sender == tx.origin || isTrustedForwarder(msg.sender), "Only EOA or Biconomy");
require(_amount > 0, "Amount must > 0");
uint256 _ETHPrice = _determineETHPrice(_tokenIndex);
uint256 _pool = getAllPoolInETH(_ETHPrice);
address _sender = _msgSender();
Tokens[_tokenIndex].token.safeTransferFrom(_sender, address(this), _amount);
uint256 _amtDeposit = _amount; // For event purpose
if (Tokens[_tokenIndex].decimals == 6) {
_amount = _amount.mul(1e12);
}
// Calculate network fee
uint256 _networkFeePerc;
if (_amount < networkFeeTier2[0]) {
// Tier 1
_networkFeePerc = networkFeePerc[0];
} else if (_amount <= networkFeeTier2[1]) {
// Tier 2
_networkFeePerc = networkFeePerc[1];
} else if (_amount < customNetworkFeeTier) {
// Tier 3
_networkFeePerc = networkFeePerc[2];
} else {
// Custom Tier
_networkFeePerc = customNetworkFeePerc;
}
uint256 _fee = _amount.mul(_networkFeePerc).div(DENOMINATOR);
_fees = _fees.add(_fee);
_amount = _amount.sub(_fee);
_balanceOfDeposit[_sender] = _balanceOfDeposit[_sender].add(_amount);
uint256 _amountInETH = _amount.mul(_ETHPrice).div(1e18);
uint256 _shares = totalSupply() == 0 ? _amountInETH : _amountInETH.mul(totalSupply()).div(_pool);
_mint(_sender, _shares);
emit Deposit(address(Tokens[_tokenIndex].token), _sender, _amtDeposit, _shares);
}
/// @notice Function to withdraw
/// @param _shares Amount of shares to withdraw (from LP token, 18 decimals)
/// @param _tokenIndex Type of stablecoin to withdraw
function withdraw(uint256 _shares, uint256 _tokenIndex) external {
require(msg.sender == tx.origin, "Only EOA");
require(_shares > 0, "Shares must > 0");
uint256 _totalShares = balanceOf(msg.sender);
require(_totalShares >= _shares, "Insufficient balance to withdraw");
// Calculate deposit amount
uint256 _depositAmt = _balanceOfDeposit[msg.sender].mul(_shares).div(_totalShares);
// Subtract deposit amount
_balanceOfDeposit[msg.sender] = _balanceOfDeposit[msg.sender].sub(_depositAmt);
// Calculate withdraw amount
uint256 _ETHPrice = _determineETHPrice(_tokenIndex);
uint256 _withdrawAmt = getAllPoolInETH(_ETHPrice).mul(_shares).div(totalSupply());
_burn(msg.sender, _shares);
uint256 _withdrawAmtInUSD = _withdrawAmt.mul(_getPriceFromChainlink(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419)).div(1e8); // ETH/USD
Token memory _token = Tokens[_tokenIndex];
uint256 _balanceOfToken = _token.token.balanceOf(address(this));
// Change _balanceOfToken to 18 decimals same as _withdrawAmtInUSD
if (_token.decimals == 6) {
_balanceOfToken = _balanceOfToken.mul(1e12);
}
if (_withdrawAmtInUSD > _balanceOfToken) {
// Not enough stablecoin in vault, need to get from strategy
strategy.withdraw(_withdrawAmt);
uint256[] memory _amounts = _swapExactTokensForTokens(WETH.balanceOf(address(this)), address(WETH), address(_token.token));
// Change withdraw amount to 18 decimals if not DAI (for calculate profit sharing fee)
_withdrawAmtInUSD = _token.decimals == 6 ? _amounts[1].mul(1e12) : _amounts[1];
}
// Calculate profit sharing fee
if (_withdrawAmtInUSD > _depositAmt) {
uint256 _profit = _withdrawAmtInUSD.sub(_depositAmt);
uint256 _fee = _profit.mul(profitSharingFeePerc).div(DENOMINATOR);
_withdrawAmtInUSD = _withdrawAmtInUSD.sub(_fee);
_fees = _fees.add(_fee);
}
// Change back withdraw amount to 6 decimals if not DAI
if (_token.decimals == 6) {
_withdrawAmtInUSD = _withdrawAmtInUSD.div(1e12);
}
_token.token.safeTransfer(msg.sender, _withdrawAmtInUSD);
emit Withdraw(address(Tokens[_tokenIndex].token), msg.sender, _withdrawAmtInUSD, _shares);
}
/// @notice Function to invest funds into strategy
function invest() external onlyAdmin {
Token memory _USDT = Tokens[0];
Token memory _USDC = Tokens[1];
Token memory _DAI = Tokens[2];
// Transfer out network fees
_fees = _fees.div(1e12); // Convert to USDT decimals
if (_fees != 0 && _USDT.token.balanceOf(address(this)) > _fees) {
uint256 _treasuryFee = _fees.mul(2).div(5); // 40%
_USDT.token.safeTransfer(treasuryWallet, _treasuryFee); // 40%
_USDT.token.safeTransfer(communityWallet, _treasuryFee); // 40%
_USDT.token.safeTransfer(strategist, _fees.sub(_treasuryFee).sub(_treasuryFee)); // 20%
emit TransferredOutFees(_fees);
_fees = 0;
}
uint256 _poolInUSD = getAllPoolInUSD().sub(_fees);
// Calculation for keep portion of stablecoins and swap remainder to WETH
uint256 _toKeepUSDT = _poolInUSD.mul(_USDT.percKeepInVault).div(DENOMINATOR);
uint256 _toKeepUSDC = _poolInUSD.mul(_USDC.percKeepInVault).div(DENOMINATOR);
uint256 _toKeepDAI = _poolInUSD.mul(_DAI.percKeepInVault).div(DENOMINATOR);
_invest(_USDT.token, _toKeepUSDT);
_invest(_USDC.token, _toKeepUSDC);
_toKeepDAI = _toKeepDAI.mul(1e12); // Follow decimals of DAI
_invest(_DAI.token, _toKeepDAI);
// Invest all swapped WETH to strategy
uint256 _balanceOfWETH = WETH.balanceOf(address(this));
if (_balanceOfWETH > 0) {
strategy.invest(_balanceOfWETH);
emit ETHToInvest(_balanceOfWETH);
}
}
/// @notice Function to swap stablecoin to WETH
/// @param _token Stablecoin to swap
/// @param _toKeepAmt Amount to keep in vault (decimals follow stablecoins)
function _invest(IERC20 _token, uint256 _toKeepAmt) private {
uint256 _balanceOfToken = _token.balanceOf(address(this));
if (_balanceOfToken > _toKeepAmt) {
_swapExactTokensForTokens(_balanceOfToken.sub(_toKeepAmt), address(_token), address(WETH));
}
}
/// @notice Function to yield farms reward in strategy
function yield() external onlyAdmin {
strategy.yield();
}
/// @notice Function to swap stablecoin within vault with Curve
/// @notice Amount to swap == amount to keep in vault of _tokenTo stablecoin
/// @param _tokenFrom Type of stablecoin to be swapped
/// @param _tokenTo Type of stablecoin to be received
/// @param _amount Amount to be swapped (follow stablecoins decimals)
function swapTokenWithinVault(uint256 _tokenFrom, uint256 _tokenTo, uint256 _amount) external onlyAdmin {
require(Tokens[_tokenFrom].token.balanceOf(address(this)) > _amount, "Insufficient amount to swap");
int128 i = _determineCurveIndex(_tokenFrom);
int128 j = _determineCurveIndex(_tokenTo);
c3pool.exchange(i, j, _amount, 0);
}
/// @notice Function to determine Curve index for swapTokenWithinVault()
/// @param _tokenIndex Index of stablecoin
/// @return stablecoin index use in Curve
function _determineCurveIndex(uint256 _tokenIndex) private pure returns (int128) {
if (_tokenIndex == 0) {
return 2;
} else if (_tokenIndex == 1) {
return 1;
} else {
return 0;
}
}
/// @notice Function to reimburse keep Tokens from strategy
/// @notice This function remove liquidity from all strategy farm and will cost massive gas fee. Only call when needed.
function reimburseTokenFromStrategy() external onlyAdmin {
strategy.reimburse();
}
/// @notice Function to withdraw all farms and swap to WETH in strategy
function emergencyWithdraw() external onlyAdmin {
strategy.emergencyWithdraw();
}
/// @notice Function to reinvest all WETH back to farms in strategy
function reinvest() external onlyAdmin {
strategy.reinvest();
}
/// @notice Function to swap between tokens with Uniswap
/// @param _amountIn Amount to swap
/// @param _fromToken Token to be swapped
/// @param _toToken Token to be received
/// @return _amounts Array that contain amount swapped
function _swapExactTokensForTokens(uint256 _amountIn, address _fromToken, address _toToken) private returns (uint256[] memory _amounts) {
address[] memory _path = new address[](2);
_path[0] = _fromToken;
_path[1] = _toToken;
uint256[] memory _amountsOut = router.getAmountsOut(_amountIn, _path);
if (_amountsOut[1] > 0) {
_amounts = router.swapExactTokensForTokens(_amountIn, 0, _path, address(this), block.timestamp);
} else {
// Not enough amount to swap
uint256[] memory _zeroReturn = new uint256[](2);
_zeroReturn[0] = 0;
_zeroReturn[1] = 0;
return _zeroReturn;
}
}
/// @notice Function to set new network fee for deposit amount tier 2
/// @param _networkFeeTier2 Array that contains minimum and maximum amount of tier 2 (18 decimals)
function setNetworkFeeTier2(uint256[] calldata _networkFeeTier2) external onlyOwner {
require(_networkFeeTier2[0] != 0, "Minimun amount cannot be 0");
require(_networkFeeTier2[1] > _networkFeeTier2[0], "Maximun amount must greater than minimun amount");
/**
* Network fees have three tier, but it is sufficient to have minimun and maximun amount of tier 2
* Tier 1: deposit amount < minimun amount of tier 2
* Tier 2: minimun amount of tier 2 <= deposit amount <= maximun amount of tier 2
* Tier 3: amount > maximun amount of tier 2
*/
uint256[] memory oldNetworkFeeTier2 = networkFeeTier2;
networkFeeTier2 = _networkFeeTier2;
emit SetNetworkFeeTier2(oldNetworkFeeTier2, _networkFeeTier2);
}
/// @notice Function to set new custom network fee tier
/// @param _customNetworkFeeTier Amount of new custom network fee tier (18 decimals)
function setCustomNetworkFeeTier(uint256 _customNetworkFeeTier) external onlyOwner {
require(_customNetworkFeeTier > networkFeeTier2[1], "Custom network fee tier must greater than tier 2");
uint256 oldCustomNetworkFeeTier = customNetworkFeeTier;
customNetworkFeeTier = _customNetworkFeeTier;
emit SetCustomNetworkFeeTier(oldCustomNetworkFeeTier, _customNetworkFeeTier);
}
/// @notice Function to set new network fee percentage
/// @param _networkFeePerc Array that contains new network fee percentage for tier 1, tier 2 and tier 3
function setNetworkFeePerc(uint256[] calldata _networkFeePerc) external onlyOwner {
require(
_networkFeePerc[0] < 3000 &&
_networkFeePerc[1] < 3000 &&
_networkFeePerc[2] < 3000,
"Network fee percentage cannot be more than 30%"
);
/**
* _networkFeePerc content a array of 3 element, representing network fee of tier 1, tier 2 and tier 3
* For example networkFeePerc is [100, 75, 50]
* which mean network fee for Tier 1 = 1%, Tier 2 = 0.75% and Tier 3 = 0.5%
*/
uint256[] memory oldNetworkFeePerc = networkFeePerc;
networkFeePerc = _networkFeePerc;
emit SetNetworkFeePerc(oldNetworkFeePerc, _networkFeePerc);
}
/// @notice Function to set new custom network fee percentage
/// @param _percentage Percentage of new custom network fee
function setCustomNetworkFeePerc(uint256 _percentage) public onlyOwner {
require(_percentage < networkFeePerc[2], "Custom network fee percentage cannot be more than tier 2");
uint256 oldCustomNetworkFeePerc = customNetworkFeePerc;
customNetworkFeePerc = _percentage;
emit SetCustomNetworkFeePerc(oldCustomNetworkFeePerc, _percentage);
}
/// @notice Function to set new profit sharing fee percentage
/// @param _percentage Percentage of new profit sharing fee
function setProfitSharingFeePerc(uint256 _percentage) external onlyOwner {
require(_percentage < 3000, "Profile sharing fee percentage cannot be more than 30%");
uint256 oldProfitSharingFeePerc = profitSharingFeePerc;
profitSharingFeePerc = _percentage;
emit SetProfitSharingFeePerc(oldProfitSharingFeePerc, _percentage);
}
/// @notice Function to set new treasury wallet address
/// @param _treasuryWallet Address of new treasury wallet
function setTreasuryWallet(address _treasuryWallet) external onlyOwner {
treasuryWallet = _treasuryWallet;
}
/// @notice Function to set new community wallet address
/// @param _communityWallet Address of new community wallet
function setCommunityWallet(address _communityWallet) external onlyOwner {
communityWallet = _communityWallet;
}
/// @notice Function to set new admin address
/// @param _admin Address of new admin
function setAdmin(address _admin) external onlyOwner {
admin = _admin;
strategy.setAdmin(_admin);
}
/// @notice Function to set new strategist address
/// @param _strategist Address of new strategist
function setStrategist(address _strategist) external {
require(msg.sender == strategist || msg.sender == owner(), "Not authorized");
strategist = _strategist;
strategy.setStrategist(_strategist);
}
/// @notice Function to set pending strategy address
/// @param _pendingStrategy Address of pending strategy
function setPendingStrategy(address _pendingStrategy) external onlyOwner {
require(canSetPendingStrategy, "Cannot set pending strategy now");
pendingStrategy = _pendingStrategy;
}
/// @notice Function to set new trusted forwarder address (Biconomy)
/// @param _biconomy Address of new trusted forwarder
function setBiconomy(address _biconomy) external onlyOwner {
trustedForwarder = _biconomy;
}
/// @notice Function to set percentage of stablecoins that keep in vault
/// @param _percentages Array with new percentages of stablecoins that keep in vault
function setPercTokenKeepInVault(uint256[] memory _percentages) external onlyAdmin {
Tokens[0].percKeepInVault = _percentages[0];
Tokens[1].percKeepInVault = _percentages[1];
Tokens[2].percKeepInVault = _percentages[2];
}
/// @notice Function to unlock migrate funds function
function unlockMigrateFunds() external onlyOwner {
unlockTime = block.timestamp.add(LOCKTIME);
canSetPendingStrategy = false;
}
/// @notice Function to migrate all funds from old strategy contract to new strategy contract
function migrateFunds() external onlyOwner {
require(unlockTime <= block.timestamp && unlockTime.add(1 days) >= block.timestamp, "Function locked");
require(WETH.balanceOf(address(strategy)) > 0, "No balance to migrate");
require(pendingStrategy != address(0), "No pendingStrategy");
uint256 _amount = WETH.balanceOf(address(strategy));
WETH.safeTransferFrom(address(strategy), pendingStrategy, _amount);
// Set new strategy
address oldStrategy = address(strategy);
strategy = ICitadelStrategy(pendingStrategy);
pendingStrategy = address(0);
canSetPendingStrategy = true;
// Approve new strategy
WETH.safeApprove(address(strategy), type(uint256).max);
WETH.safeApprove(oldStrategy, 0);
unlockTime = 0; // Lock back this function
emit MigrateFunds(oldStrategy, address(strategy), _amount);
}
/// @notice Function to get all pool amount(vault+strategy) in USD (use USDT/ETH as price feed)
/// @return All pool in USD (6 decimals follow USDT)
function getAllPoolInUSD() public view returns (uint256) {
uint256 _currentETHprice = _getPriceFromChainlink(0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46); // USDT/ETH
uint256 _currentUSDprice = _getPriceFromChainlink(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); // ETH/USD
return getAllPoolInETH(_currentETHprice).mul(_currentUSDprice).div(1e20);
}
/// @notice Same as getAllPoolInETH() above with parameter
/// @param _price ETH price from ChainLink (USDT/ETH)
/// @return All pool in ETH (18 decimals)
function getAllPoolInETH(uint256 _price) public view returns (uint256) {
uint256 _vaultPoolInETH = _getVaultPoolInUSD().mul(_price);
return strategy.getCurrentPool().add(_vaultPoolInETH);
}
/// @notice Function to get exact USD amount of pool in vault
/// @return Exact USD amount of pool in vault (no decimals)
function _getVaultPoolInUSD() private view returns (uint256) {
uint256 _vaultPoolInUSD = (Tokens[0].token.balanceOf(address(this)).mul(1e12))
.add(Tokens[1].token.balanceOf(address(this)).mul(1e12))
.add(Tokens[2].token.balanceOf(address(this)))
.sub(_fees);
// In very rare case that fees > vault pool, above calculation will raise error
// Use getReimburseTokenAmount() to get some stablecoin from strategy
return _vaultPoolInUSD.div(1e18);
}
/// @notice Function to get price from ChainLink contract
/// @param _priceFeedProxy Address of ChainLink contract that provide price
/// @return Price (8 decimals for USD, 18 decimals for ETH)
function _getPriceFromChainlink(address _priceFeedProxy) private view returns (uint256) {
IChainlink _pricefeed = IChainlink(_priceFeedProxy);
int256 _price = _pricefeed.latestAnswer();
return uint256(_price);
}
/// @notice Function to determine ETH price based on stablecoin
/// @param _tokenIndex Type of stablecoin to determine
/// @return Price of ETH (18 decimals)
function _determineETHPrice(uint256 _tokenIndex) private view returns (uint256) {
address _priceFeedContract;
if (address(Tokens[_tokenIndex].token) == 0xdAC17F958D2ee523a2206206994597C13D831ec7) { // USDT
_priceFeedContract = 0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46; // USDT/ETH
} else if (address(Tokens[_tokenIndex].token) == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) { // USDC
_priceFeedContract = 0x986b5E1e1755e3C2440e960477f25201B0a8bbD4; // USDC/ETH
} else { // DAI
_priceFeedContract = 0x773616E4d11A78F511299002da57A0a94577F1f4; // DAI/ETH
}
return _getPriceFromChainlink(_priceFeedContract);
}
/// @notice Function to get amount need to fill up minimum amount keep in vault
/// @param _tokenIndex Type of stablecoin requested
/// @return Amount to reimburse (USDT, USDC 6 decimals, DAI 18 decimals)
function getReimburseTokenAmount(uint256 _tokenIndex) public view returns (uint256) {
Token memory _token = Tokens[_tokenIndex];
uint256 _toKeepAmt = getAllPoolInUSD().mul(_token.percKeepInVault).div(DENOMINATOR);
if (_token.decimals == 18) {
_toKeepAmt = _toKeepAmt.mul(1e12);
}
uint256 _balanceOfToken = _token.token.balanceOf(address(this));
if (_balanceOfToken < _toKeepAmt) {
return _toKeepAmt.sub(_balanceOfToken);
}
return 0; // amount keep in vault is full
}
}
// 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;
/**
* @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 "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.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 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier:MIT
pragma solidity 0.7.6;
import "../interfaces/IRelayRecipient.sol";
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
/*
* require a function to be called through GSN only
*/
modifier trustedForwarderOnly() {
require(msg.sender == address(trustedForwarder), "Function can only be called through the trusted Forwarder");
_;
}
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier:MIT
pragma solidity 0.7.6;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
function versionRecipient() external virtual view returns (string memory);
}
|
Function to determine ETH price based on stablecoin _tokenIndex Type of stablecoin to determine return Price of ETH (18 decimals)
|
function _determineETHPrice(uint256 _tokenIndex) private view returns (uint256) {
address _priceFeedContract;
}
return _getPriceFromChainlink(_priceFeedContract);
| 13,715,958 |
./full_match/80001/0xBB24d7CBade17c26a19B97A1E6204125985f0412/sources/useCases/vehicle-management/vehicleModificationTracker.sol
|
modifier to check if the user is a super admin or car owner
|
modifier onlySuperAdminOrCarOwner() {
require(
userTypes[msg.sender] == UserType.SuperAdmin ||
userTypes[msg.sender] == UserType.CarOwner,
"Only super admin or car owner can call this function"
);
_;
}
| 9,495,800 |
./full_match/1/0xF7873f6F603b3C3d2C8a5e2b123A386373F2095f/sources/contracts/interfaces/ICollateralOracle.sol
|
Interface to a Collateral Oracle/
|
interface ICollateralOracle {
error UnsupportedCollateral();
function currencyToken() external view returns (IERC20);
function collateralValue(address collateralToken, uint256 collateralTokenId) external view returns (uint256);
pragma solidity ^0.8.0;
}
| 17,037,617 |
// File: contracts/installed_contracts/DLL.sol
pragma solidity^0.4.11;
library DLL {
uint constant NULL_NODE_ID = 0;
struct Node {
uint next;
uint prev;
}
struct Data {
mapping(uint => Node) dll;
}
function isEmpty(Data storage self) public view returns (bool) {
return getStart(self) == NULL_NODE_ID;
}
function contains(Data storage self, uint _curr) public view returns (bool) {
if (isEmpty(self) || _curr == NULL_NODE_ID) {
return false;
}
bool isSingleNode = (getStart(self) == _curr) && (getEnd(self) == _curr);
bool isNullNode = (getNext(self, _curr) == NULL_NODE_ID) && (getPrev(self, _curr) == NULL_NODE_ID);
return isSingleNode || !isNullNode;
}
function getNext(Data storage self, uint _curr) public view returns (uint) {
return self.dll[_curr].next;
}
function getPrev(Data storage self, uint _curr) public view returns (uint) {
return self.dll[_curr].prev;
}
function getStart(Data storage self) public view returns (uint) {
return getNext(self, NULL_NODE_ID);
}
function getEnd(Data storage self) public view returns (uint) {
return getPrev(self, NULL_NODE_ID);
}
/**
@dev Inserts a new node between _prev and _next. When inserting a node already existing in
the list it will be automatically removed from the old position.
@param _prev the node which _new will be inserted after
@param _curr the id of the new node being inserted
@param _next the node which _new will be inserted before
*/
function insert(Data storage self, uint _prev, uint _curr, uint _next) public {
require(_curr != NULL_NODE_ID);
remove(self, _curr);
require(_prev == NULL_NODE_ID || contains(self, _prev));
require(_next == NULL_NODE_ID || contains(self, _next));
require(getNext(self, _prev) == _next);
require(getPrev(self, _next) == _prev);
self.dll[_curr].prev = _prev;
self.dll[_curr].next = _next;
self.dll[_prev].next = _curr;
self.dll[_next].prev = _curr;
}
function remove(Data storage self, uint _curr) public {
if (!contains(self, _curr)) {
return;
}
uint next = getNext(self, _curr);
uint prev = getPrev(self, _curr);
self.dll[next].prev = prev;
self.dll[prev].next = next;
delete self.dll[_curr];
}
}
// File: contracts/installed_contracts/AttributeStore.sol
/* solium-disable */
pragma solidity^0.4.11;
library AttributeStore {
struct Data {
mapping(bytes32 => uint) store;
}
function getAttribute(Data storage self, bytes32 _UUID, string _attrName)
public view returns (uint) {
bytes32 key = keccak256(_UUID, _attrName);
return self.store[key];
}
function setAttribute(Data storage self, bytes32 _UUID, string _attrName, uint _attrVal)
public {
bytes32 key = keccak256(_UUID, _attrName);
self.store[key] = _attrVal;
}
}
// File: contracts/zeppelin-solidity/token/ERC20/IERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/zeppelin-solidity/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts/installed_contracts/PLCRVoting.sol
pragma solidity ^0.4.8;
/**
@title Partial-Lock-Commit-Reveal Voting scheme with ERC20 tokens
@author Team: Aspyn Palatnick, Cem Ozer, Yorke Rhodes
*/
contract PLCRVoting {
// ============
// EVENTS:
// ============
event _VoteCommitted(uint indexed pollID, uint numTokens, address indexed voter);
event _VoteRevealed(uint indexed pollID, uint numTokens, uint votesFor, uint votesAgainst, uint indexed choice, address indexed voter, uint salt);
event _PollCreated(uint voteQuorum, uint commitEndDate, uint revealEndDate, uint indexed pollID, address indexed creator);
event _VotingRightsGranted(uint numTokens, address indexed voter);
event _VotingRightsWithdrawn(uint numTokens, address indexed voter);
event _TokensRescued(uint indexed pollID, address indexed voter);
// ============
// DATA STRUCTURES:
// ============
using AttributeStore for AttributeStore.Data;
using DLL for DLL.Data;
using SafeMath for uint;
struct Poll {
uint commitEndDate; /// expiration date of commit period for poll
uint revealEndDate; /// expiration date of reveal period for poll
uint voteQuorum; /// number of votes required for a proposal to pass
uint votesFor; /// tally of votes supporting proposal
uint votesAgainst; /// tally of votes countering proposal
mapping(address => bool) didCommit; /// indicates whether an address committed a vote for this poll
mapping(address => bool) didReveal; /// indicates whether an address revealed a vote for this poll
}
// ============
// STATE VARIABLES:
// ============
uint constant public INITIAL_POLL_NONCE = 0;
uint public pollNonce;
mapping(uint => Poll) public pollMap; // maps pollID to Poll struct
mapping(address => uint) public voteTokenBalance; // maps user's address to voteToken balance
mapping(address => DLL.Data) dllMap;
AttributeStore.Data store;
IERC20 public token;
/**
@param _token The address where the ERC20 token contract is deployed
*/
constructor(address _token) public {
require(_token != 0);
token = IERC20(_token);
pollNonce = INITIAL_POLL_NONCE;
}
// ================
// TOKEN INTERFACE:
// ================
/**
@notice Loads _numTokens ERC20 tokens into the voting contract for one-to-one voting rights
@dev Assumes that msg.sender has approved voting contract to spend on their behalf
@param _numTokens The number of votingTokens desired in exchange for ERC20 tokens
*/
function requestVotingRights(uint _numTokens) public {
require(token.balanceOf(msg.sender) >= _numTokens);
voteTokenBalance[msg.sender] += _numTokens;
require(token.transferFrom(msg.sender, this, _numTokens));
emit _VotingRightsGranted(_numTokens, msg.sender);
}
/**
@notice Withdraw _numTokens ERC20 tokens from the voting contract, revoking these voting rights
@param _numTokens The number of ERC20 tokens desired in exchange for voting rights
*/
function withdrawVotingRights(uint _numTokens) external {
uint availableTokens = voteTokenBalance[msg.sender].sub(getLockedTokens(msg.sender));
require(availableTokens >= _numTokens);
voteTokenBalance[msg.sender] -= _numTokens;
require(token.transfer(msg.sender, _numTokens));
emit _VotingRightsWithdrawn(_numTokens, msg.sender);
}
/**
@dev Unlocks tokens locked in unrevealed vote where poll has ended
@param _pollID Integer identifier associated with the target poll
*/
function rescueTokens(uint _pollID) public {
require(isExpired(pollMap[_pollID].revealEndDate));
require(dllMap[msg.sender].contains(_pollID));
dllMap[msg.sender].remove(_pollID);
emit _TokensRescued(_pollID, msg.sender);
}
/**
@dev Unlocks tokens locked in unrevealed votes where polls have ended
@param _pollIDs Array of integer identifiers associated with the target polls
*/
function rescueTokensInMultiplePolls(uint[] _pollIDs) public {
// loop through arrays, rescuing tokens from all
for (uint i = 0; i < _pollIDs.length; i++) {
rescueTokens(_pollIDs[i]);
}
}
// =================
// VOTING INTERFACE:
// =================
/**
@notice Commits vote using hash of choice and secret salt to conceal vote until reveal
@param _pollID Integer identifier associated with target poll
@param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order)
@param _numTokens The number of tokens to be committed towards the target poll
@param _prevPollID The ID of the poll that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
*/
function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public {
require(commitPeriodActive(_pollID));
// if msg.sender doesn't have enough voting rights,
// request for enough voting rights
if (voteTokenBalance[msg.sender] < _numTokens) {
uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]);
requestVotingRights(remainder);
}
// make sure msg.sender has enough voting rights
require(voteTokenBalance[msg.sender] >= _numTokens);
// prevent user from committing to zero node placeholder
require(_pollID != 0);
// prevent user from committing a secretHash of 0
require(_secretHash != 0);
// Check if _prevPollID exists in the user's DLL or if _prevPollID is 0
require(_prevPollID == 0 || dllMap[msg.sender].contains(_prevPollID));
uint nextPollID = dllMap[msg.sender].getNext(_prevPollID);
// edge case: in-place update
if (nextPollID == _pollID) {
nextPollID = dllMap[msg.sender].getNext(_pollID);
}
require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens));
dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID);
bytes32 UUID = attrUUID(msg.sender, _pollID);
store.setAttribute(UUID, "numTokens", _numTokens);
store.setAttribute(UUID, "commitHash", uint(_secretHash));
pollMap[_pollID].didCommit[msg.sender] = true;
emit _VoteCommitted(_pollID, _numTokens, msg.sender);
}
/**
@notice Commits votes using hashes of choices and secret salts to conceal votes until reveal
@param _pollIDs Array of integer identifiers associated with target polls
@param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order)
@param _numsTokens Array of numbers of tokens to be committed towards the target polls
@param _prevPollIDs Array of IDs of the polls that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
*/
function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external {
// make sure the array lengths are all the same
require(_pollIDs.length == _secretHashes.length);
require(_pollIDs.length == _numsTokens.length);
require(_pollIDs.length == _prevPollIDs.length);
// loop through arrays, committing each individual vote values
for (uint i = 0; i < _pollIDs.length; i++) {
commitVote(_pollIDs[i], _secretHashes[i], _numsTokens[i], _prevPollIDs[i]);
}
}
/**
@dev Compares previous and next poll's committed tokens for sorting purposes
@param _prevID Integer identifier associated with previous poll in sorted order
@param _nextID Integer identifier associated with next poll in sorted order
@param _voter Address of user to check DLL position for
@param _numTokens The number of tokens to be committed towards the poll (used for sorting)
@return valid Boolean indication of if the specified position maintains the sort
*/
function validPosition(uint _prevID, uint _nextID, address _voter, uint _numTokens) public constant returns (bool valid) {
bool prevValid = (_numTokens >= getNumTokens(_voter, _prevID));
// if next is zero node, _numTokens does not need to be greater
bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0);
return prevValid && nextValid;
}
/**
@notice Reveals vote with choice and secret salt used in generating commitHash to attribute committed tokens
@param _pollID Integer identifier associated with target poll
@param _voteOption Vote choice used to generate commitHash for associated poll
@param _salt Secret number used to generate commitHash for associated poll
*/
function revealVote(uint _pollID, uint _voteOption, uint _salt) public {
// Make sure the reveal period is active
require(revealPeriodActive(_pollID));
require(pollMap[_pollID].didCommit[msg.sender]); // make sure user has committed a vote for this poll
require(!pollMap[_pollID].didReveal[msg.sender]); // prevent user from revealing multiple times
require(keccak256(_voteOption, _salt) == getCommitHash(msg.sender, _pollID)); // compare resultant hash from inputs to original commitHash
uint numTokens = getNumTokens(msg.sender, _pollID);
if (_voteOption == 1) {// apply numTokens to appropriate poll choice
pollMap[_pollID].votesFor += numTokens;
} else {
pollMap[_pollID].votesAgainst += numTokens;
}
dllMap[msg.sender].remove(_pollID); // remove the node referring to this vote upon reveal
pollMap[_pollID].didReveal[msg.sender] = true;
emit _VoteRevealed(_pollID, numTokens, pollMap[_pollID].votesFor, pollMap[_pollID].votesAgainst, _voteOption, msg.sender, _salt);
}
/**
@notice Reveals multiple votes with choices and secret salts used in generating commitHashes to attribute committed tokens
@param _pollIDs Array of integer identifiers associated with target polls
@param _voteOptions Array of vote choices used to generate commitHashes for associated polls
@param _salts Array of secret numbers used to generate commitHashes for associated polls
*/
function revealVotes(uint[] _pollIDs, uint[] _voteOptions, uint[] _salts) external {
// make sure the array lengths are all the same
require(_pollIDs.length == _voteOptions.length);
require(_pollIDs.length == _salts.length);
// loop through arrays, revealing each individual vote values
for (uint i = 0; i < _pollIDs.length; i++) {
revealVote(_pollIDs[i], _voteOptions[i], _salts[i]);
}
}
/**
@param _pollID Integer identifier associated with target poll
@param _salt Arbitrarily chosen integer used to generate secretHash
@return correctVotes Number of tokens voted for winning option
*/
function getNumPassingTokens(address _voter, uint _pollID, uint _salt) public constant returns (uint correctVotes) {
require(pollEnded(_pollID));
require(pollMap[_pollID].didReveal[_voter]);
uint winningChoice = isPassed(_pollID) ? 1 : 0;
bytes32 winnerHash = keccak256(winningChoice, _salt);
bytes32 commitHash = getCommitHash(_voter, _pollID);
require(winnerHash == commitHash);
return getNumTokens(_voter, _pollID);
}
// ==================
// POLLING INTERFACE:
// ==================
/**
@dev Initiates a poll with canonical configured parameters at pollID emitted by PollCreated event
@param _voteQuorum Type of majority (out of 100) that is necessary for poll to be successful
@param _commitDuration Length of desired commit period in seconds
@param _revealDuration Length of desired reveal period in seconds
*/
function startPoll(uint _voteQuorum, uint _commitDuration, uint _revealDuration) public returns (uint pollID) {
pollNonce = pollNonce + 1;
uint commitEndDate = block.timestamp.add(_commitDuration);
uint revealEndDate = commitEndDate.add(_revealDuration);
pollMap[pollNonce] = Poll({
voteQuorum: _voteQuorum,
commitEndDate: commitEndDate,
revealEndDate: revealEndDate,
votesFor: 0,
votesAgainst: 0
});
emit _PollCreated(_voteQuorum, commitEndDate, revealEndDate, pollNonce, msg.sender);
return pollNonce;
}
/**
@notice Determines if proposal has passed
@dev Check if votesFor out of totalVotes exceeds votesQuorum (requires pollEnded)
@param _pollID Integer identifier associated with target poll
*/
function isPassed(uint _pollID) constant public returns (bool passed) {
require(pollEnded(_pollID));
Poll memory poll = pollMap[_pollID];
return (100 * poll.votesFor) > (poll.voteQuorum * (poll.votesFor + poll.votesAgainst));
}
// ----------------
// POLLING HELPERS:
// ----------------
/**
@dev Gets the total winning votes for reward distribution purposes
@param _pollID Integer identifier associated with target poll
@return Total number of votes committed to the winning option for specified poll
*/
function getTotalNumberOfTokensForWinningOption(uint _pollID) constant public returns (uint numTokens) {
require(pollEnded(_pollID));
if (isPassed(_pollID))
return pollMap[_pollID].votesFor;
else
return pollMap[_pollID].votesAgainst;
}
/**
@notice Determines if poll is over
@dev Checks isExpired for specified poll's revealEndDate
@return Boolean indication of whether polling period is over
*/
function pollEnded(uint _pollID) constant public returns (bool ended) {
require(pollExists(_pollID));
return isExpired(pollMap[_pollID].revealEndDate);
}
/**
@notice Checks if the commit period is still active for the specified poll
@dev Checks isExpired for the specified poll's commitEndDate
@param _pollID Integer identifier associated with target poll
@return Boolean indication of isCommitPeriodActive for target poll
*/
function commitPeriodActive(uint _pollID) constant public returns (bool active) {
require(pollExists(_pollID));
return !isExpired(pollMap[_pollID].commitEndDate);
}
/**
@notice Checks if the reveal period is still active for the specified poll
@dev Checks isExpired for the specified poll's revealEndDate
@param _pollID Integer identifier associated with target poll
*/
function revealPeriodActive(uint _pollID) constant public returns (bool active) {
require(pollExists(_pollID));
return !isExpired(pollMap[_pollID].revealEndDate) && !commitPeriodActive(_pollID);
}
/**
@dev Checks if user has committed for specified poll
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Boolean indication of whether user has committed
*/
function didCommit(address _voter, uint _pollID) constant public returns (bool committed) {
require(pollExists(_pollID));
return pollMap[_pollID].didCommit[_voter];
}
/**
@dev Checks if user has revealed for specified poll
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Boolean indication of whether user has revealed
*/
function didReveal(address _voter, uint _pollID) constant public returns (bool revealed) {
require(pollExists(_pollID));
return pollMap[_pollID].didReveal[_voter];
}
/**
@dev Checks if a poll exists
@param _pollID The pollID whose existance is to be evaluated.
@return Boolean Indicates whether a poll exists for the provided pollID
*/
function pollExists(uint _pollID) constant public returns (bool exists) {
return (_pollID != 0 && _pollID <= pollNonce);
}
// ---------------------------
// DOUBLE-LINKED-LIST HELPERS:
// ---------------------------
/**
@dev Gets the bytes32 commitHash property of target poll
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Bytes32 hash property attached to target poll
*/
function getCommitHash(address _voter, uint _pollID) constant public returns (bytes32 commitHash) {
return bytes32(store.getAttribute(attrUUID(_voter, _pollID), "commitHash"));
}
/**
@dev Wrapper for getAttribute with attrName="numTokens"
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Number of tokens committed to poll in sorted poll-linked-list
*/
function getNumTokens(address _voter, uint _pollID) constant public returns (uint numTokens) {
return store.getAttribute(attrUUID(_voter, _pollID), "numTokens");
}
/**
@dev Gets top element of sorted poll-linked-list
@param _voter Address of user to check against
@return Integer identifier to poll with maximum number of tokens committed to it
*/
function getLastNode(address _voter) constant public returns (uint pollID) {
return dllMap[_voter].getPrev(0);
}
/**
@dev Gets the numTokens property of getLastNode
@param _voter Address of user to check against
@return Maximum number of tokens committed in poll specified
*/
function getLockedTokens(address _voter) constant public returns (uint numTokens) {
return getNumTokens(_voter, getLastNode(_voter));
}
/*
@dev Takes the last node in the user's DLL and iterates backwards through the list searching
for a node with a value less than or equal to the provided _numTokens value. When such a node
is found, if the provided _pollID matches the found nodeID, this operation is an in-place
update. In that case, return the previous node of the node being updated. Otherwise return the
first node that was found with a value less than or equal to the provided _numTokens.
@param _voter The voter whose DLL will be searched
@param _numTokens The value for the numTokens attribute in the node to be inserted
@return the node which the propoded node should be inserted after
*/
function getInsertPointForNumTokens(address _voter, uint _numTokens, uint _pollID)
constant public returns (uint prevNode) {
// Get the last node in the list and the number of tokens in that node
uint nodeID = getLastNode(_voter);
uint tokensInNode = getNumTokens(_voter, nodeID);
// Iterate backwards through the list until reaching the root node
while(nodeID != 0) {
// Get the number of tokens in the current node
tokensInNode = getNumTokens(_voter, nodeID);
if(tokensInNode <= _numTokens) { // We found the insert point!
if(nodeID == _pollID) {
// This is an in-place update. Return the prev node of the node being updated
nodeID = dllMap[_voter].getPrev(nodeID);
}
// Return the insert point
return nodeID;
}
// We did not find the insert point. Continue iterating backwards through the list
nodeID = dllMap[_voter].getPrev(nodeID);
}
// The list is empty, or a smaller value than anything else in the list is being inserted
return nodeID;
}
// ----------------
// GENERAL HELPERS:
// ----------------
/**
@dev Checks if an expiration date has been reached
@param _terminationDate Integer timestamp of date to compare current timestamp with
@return expired Boolean indication of whether the terminationDate has passed
*/
function isExpired(uint _terminationDate) constant public returns (bool expired) {
return (block.timestamp > _terminationDate);
}
/**
@dev Generates an identifier which associates a user and a poll together
@param _pollID Integer identifier associated with target poll
@return UUID Hash which is deterministic from _user and _pollID
*/
function attrUUID(address _user, uint _pollID) public pure returns (bytes32 UUID) {
return keccak256(_user, _pollID);
}
}
// File: contracts/installed_contracts/Parameterizer.sol
pragma solidity^0.4.11;
contract Parameterizer {
// ------
// EVENTS
// ------
event _ReparameterizationProposal(string name, uint value, bytes32 propID, uint deposit, uint appEndDate, address indexed proposer);
event _NewChallenge(bytes32 indexed propID, uint challengeID, uint commitEndDate, uint revealEndDate, address indexed challenger);
event _ProposalAccepted(bytes32 indexed propID, string name, uint value);
event _ProposalExpired(bytes32 indexed propID);
event _ChallengeSucceeded(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _ChallengeFailed(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _RewardClaimed(uint indexed challengeID, uint reward, address indexed voter);
// ------
// DATA STRUCTURES
// ------
using SafeMath for uint;
struct ParamProposal {
uint appExpiry;
uint challengeID;
uint deposit;
string name;
address owner;
uint processBy;
uint value;
}
struct Challenge {
uint rewardPool; // (remaining) pool of tokens distributed amongst winning voters
address challenger; // owner of Challenge
bool resolved; // indication of if challenge is resolved
uint stake; // number of tokens at risk for either party during challenge
uint winningTokens; // (remaining) amount of tokens used for voting by the winning side
mapping(address => bool) tokenClaims;
}
// ------
// STATE
// ------
mapping(bytes32 => uint) public params;
// maps challengeIDs to associated challenge data
mapping(uint => Challenge) public challenges;
// maps pollIDs to intended data change if poll passes
mapping(bytes32 => ParamProposal) public proposals;
// Global Variables
IERC20 public token;
PLCRVoting public voting;
uint public PROCESSBY = 604800; // 7 days
/**
@param _token The address where the ERC20 token contract is deployed
@param _plcr address of a PLCR voting contract for the provided token
@notice _parameters array of canonical parameters
*/
constructor(
address _token,
address _plcr,
uint[] _parameters
) public {
token = IERC20(_token);
voting = PLCRVoting(_plcr);
// minimum deposit for listing to be whitelisted
set("minDeposit", _parameters[0]);
// minimum deposit to propose a reparameterization
set("pMinDeposit", _parameters[1]);
// period over which applicants wait to be whitelisted
set("applyStageLen", _parameters[2]);
// period over which reparmeterization proposals wait to be processed
set("pApplyStageLen", _parameters[3]);
// length of commit period for voting
set("commitStageLen", _parameters[4]);
// length of commit period for voting in parameterizer
set("pCommitStageLen", _parameters[5]);
// length of reveal period for voting
set("revealStageLen", _parameters[6]);
// length of reveal period for voting in parameterizer
set("pRevealStageLen", _parameters[7]);
// percentage of losing party's deposit distributed to winning party
set("dispensationPct", _parameters[8]);
// percentage of losing party's deposit distributed to winning party in parameterizer
set("pDispensationPct", _parameters[9]);
// type of majority out of 100 necessary for candidate success
set("voteQuorum", _parameters[10]);
// type of majority out of 100 necessary for proposal success in parameterizer
set("pVoteQuorum", _parameters[11]);
}
// -----------------------
// TOKEN HOLDER INTERFACE
// -----------------------
/**
@notice propose a reparamaterization of the key _name's value to _value.
@param _name the name of the proposed param to be set
@param _value the proposed value to set the param to be set
*/
function proposeReparameterization(string _name, uint _value) public returns (bytes32) {
uint deposit = get("pMinDeposit");
bytes32 propID = keccak256(_name, _value);
if (keccak256(_name) == keccak256("dispensationPct") ||
keccak256(_name) == keccak256("pDispensationPct")) {
require(_value <= 100);
}
require(!propExists(propID)); // Forbid duplicate proposals
require(get(_name) != _value); // Forbid NOOP reparameterizations
// attach name and value to pollID
proposals[propID] = ParamProposal({
appExpiry: now.add(get("pApplyStageLen")),
challengeID: 0,
deposit: deposit,
name: _name,
owner: msg.sender,
processBy: now.add(get("pApplyStageLen"))
.add(get("pCommitStageLen"))
.add(get("pRevealStageLen"))
.add(PROCESSBY),
value: _value
});
require(token.transferFrom(msg.sender, this, deposit)); // escrow tokens (deposit amt)
emit _ReparameterizationProposal(_name, _value, propID, deposit, proposals[propID].appExpiry, msg.sender);
return propID;
}
/**
@notice challenge the provided proposal ID, and put tokens at stake to do so.
@param _propID the proposal ID to challenge
*/
function challengeReparameterization(bytes32 _propID) public returns (uint challengeID) {
ParamProposal memory prop = proposals[_propID];
uint deposit = prop.deposit;
require(propExists(_propID) && prop.challengeID == 0);
//start poll
uint pollID = voting.startPoll(
get("pVoteQuorum"),
get("pCommitStageLen"),
get("pRevealStageLen")
);
challenges[pollID] = Challenge({
challenger: msg.sender,
rewardPool: SafeMath.sub(100, get("pDispensationPct")).mul(deposit).div(100),
stake: deposit,
resolved: false,
winningTokens: 0
});
proposals[_propID].challengeID = pollID; // update listing to store most recent challenge
//take tokens from challenger
require(token.transferFrom(msg.sender, this, deposit));
var (commitEndDate, revealEndDate,) = voting.pollMap(pollID);
emit _NewChallenge(_propID, pollID, commitEndDate, revealEndDate, msg.sender);
return pollID;
}
/**
@notice for the provided proposal ID, set it, resolve its challenge, or delete it depending on whether it can be set, has a challenge which can be resolved, or if its "process by" date has passed
@param _propID the proposal ID to make a determination and state transition for
*/
function processProposal(bytes32 _propID) public {
ParamProposal storage prop = proposals[_propID];
address propOwner = prop.owner;
uint propDeposit = prop.deposit;
// Before any token transfers, deleting the proposal will ensure that if reentrancy occurs the
// prop.owner and prop.deposit will be 0, thereby preventing theft
if (canBeSet(_propID)) {
// There is no challenge against the proposal. The processBy date for the proposal has not
// passed, but the proposal's appExpirty date has passed.
set(prop.name, prop.value);
emit _ProposalAccepted(_propID, prop.name, prop.value);
delete proposals[_propID];
require(token.transfer(propOwner, propDeposit));
} else if (challengeCanBeResolved(_propID)) {
// There is a challenge against the proposal.
resolveChallenge(_propID);
} else if (now > prop.processBy) {
// There is no challenge against the proposal, but the processBy date has passed.
emit _ProposalExpired(_propID);
delete proposals[_propID];
require(token.transfer(propOwner, propDeposit));
} else {
// There is no challenge against the proposal, and neither the appExpiry date nor the
// processBy date has passed.
revert();
}
assert(get("dispensationPct") <= 100);
assert(get("pDispensationPct") <= 100);
// verify that future proposal appExpiry and processBy times will not overflow
now.add(get("pApplyStageLen"))
.add(get("pCommitStageLen"))
.add(get("pRevealStageLen"))
.add(PROCESSBY);
delete proposals[_propID];
}
/**
@notice Claim the tokens owed for the msg.sender in the provided challenge
@param _challengeID the challenge ID to claim tokens for
@param _salt the salt used to vote in the challenge being withdrawn for
*/
function claimReward(uint _challengeID, uint _salt) public {
// ensure voter has not already claimed tokens and challenge results have been processed
require(challenges[_challengeID].tokenClaims[msg.sender] == false);
require(challenges[_challengeID].resolved == true);
uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID, _salt);
uint reward = voterReward(msg.sender, _challengeID, _salt);
// subtract voter's information to preserve the participation ratios of other voters
// compared to the remaining pool of rewards
challenges[_challengeID].winningTokens -= voterTokens;
challenges[_challengeID].rewardPool -= reward;
// ensures a voter cannot claim tokens again
challenges[_challengeID].tokenClaims[msg.sender] = true;
emit _RewardClaimed(_challengeID, reward, msg.sender);
require(token.transfer(msg.sender, reward));
}
/**
@dev Called by a voter to claim their rewards for each completed vote.
Someone must call updateStatus() before this can be called.
@param _challengeIDs The PLCR pollIDs of the challenges rewards are being claimed for
@param _salts The salts of a voter's commit hashes in the given polls
*/
function claimRewards(uint[] _challengeIDs, uint[] _salts) public {
// make sure the array lengths are the same
require(_challengeIDs.length == _salts.length);
// loop through arrays, claiming each individual vote reward
for (uint i = 0; i < _challengeIDs.length; i++) {
claimReward(_challengeIDs[i], _salts[i]);
}
}
// --------
// GETTERS
// --------
/**
@dev Calculates the provided voter's token reward for the given poll.
@param _voter The address of the voter whose reward balance is to be returned
@param _challengeID The ID of the challenge the voter's reward is being calculated for
@param _salt The salt of the voter's commit hash in the given poll
@return The uint indicating the voter's reward
*/
function voterReward(address _voter, uint _challengeID, uint _salt)
public view returns (uint) {
uint winningTokens = challenges[_challengeID].winningTokens;
uint rewardPool = challenges[_challengeID].rewardPool;
uint voterTokens = voting.getNumPassingTokens(_voter, _challengeID, _salt);
return (voterTokens * rewardPool) / winningTokens;
}
/**
@notice Determines whether a proposal passed its application stage without a challenge
@param _propID The proposal ID for which to determine whether its application stage passed without a challenge
*/
function canBeSet(bytes32 _propID) view public returns (bool) {
ParamProposal memory prop = proposals[_propID];
return (now > prop.appExpiry && now < prop.processBy && prop.challengeID == 0);
}
/**
@notice Determines whether a proposal exists for the provided proposal ID
@param _propID The proposal ID whose existance is to be determined
*/
function propExists(bytes32 _propID) view public returns (bool) {
return proposals[_propID].processBy > 0;
}
/**
@notice Determines whether the provided proposal ID has a challenge which can be resolved
@param _propID The proposal ID whose challenge to inspect
*/
function challengeCanBeResolved(bytes32 _propID) view public returns (bool) {
ParamProposal memory prop = proposals[_propID];
Challenge memory challenge = challenges[prop.challengeID];
return (prop.challengeID > 0 && challenge.resolved == false && voting.pollEnded(prop.challengeID));
}
/**
@notice Determines the number of tokens to awarded to the winning party in a challenge
@param _challengeID The challengeID to determine a reward for
*/
function challengeWinnerReward(uint _challengeID) public view returns (uint) {
if(voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) {
// Edge case, nobody voted, give all tokens to the challenger.
return 2 * challenges[_challengeID].stake;
}
return (2 * challenges[_challengeID].stake) - challenges[_challengeID].rewardPool;
}
/**
@notice gets the parameter keyed by the provided name value from the params mapping
@param _name the key whose value is to be determined
*/
function get(string _name) public view returns (uint value) {
return params[keccak256(_name)];
}
/**
@dev Getter for Challenge tokenClaims mappings
@param _challengeID The challengeID to query
@param _voter The voter whose claim status to query for the provided challengeID
*/
function tokenClaims(uint _challengeID, address _voter) public view returns (bool) {
return challenges[_challengeID].tokenClaims[_voter];
}
// ----------------
// PRIVATE FUNCTIONS
// ----------------
/**
@dev resolves a challenge for the provided _propID. It must be checked in advance whether the _propID has a challenge on it
@param _propID the proposal ID whose challenge is to be resolved.
*/
function resolveChallenge(bytes32 _propID) private {
ParamProposal memory prop = proposals[_propID];
Challenge storage challenge = challenges[prop.challengeID];
// winner gets back their full staked deposit, and dispensationPct*loser's stake
uint reward = challengeWinnerReward(prop.challengeID);
challenge.winningTokens = voting.getTotalNumberOfTokensForWinningOption(prop.challengeID);
challenge.resolved = true;
if (voting.isPassed(prop.challengeID)) { // The challenge failed
if(prop.processBy > now) {
set(prop.name, prop.value);
}
emit _ChallengeFailed(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens);
require(token.transfer(prop.owner, reward));
}
else { // The challenge succeeded or nobody voted
emit _ChallengeSucceeded(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens);
require(token.transfer(challenges[prop.challengeID].challenger, reward));
}
}
/**
@dev sets the param keted by the provided name to the provided value
@param _name the name of the param to be set
@param _value the value to set the param to be set
*/
function set(string _name, uint _value) internal {
params[keccak256(_name)] = _value;
}
}
// File: contracts/tcr/CivilParameterizer.sol
pragma solidity ^0.4.19;
contract CivilParameterizer is Parameterizer {
/**
@param tokenAddr The address where the ERC20 token contract is deployed
@param plcrAddr address of a PLCR voting contract for the provided token
@notice parameters array of canonical parameters
*/
constructor(
address tokenAddr,
address plcrAddr,
uint[] parameters
) public Parameterizer(tokenAddr, plcrAddr, parameters)
{
set("challengeAppealLen", parameters[12]);
set("challengeAppealCommitLen", parameters[13]);
set("challengeAppealRevealLen", parameters[14]);
}
}
|
/ Make sure the reveal period is active
|
function revealVote(uint _pollID, uint _voteOption, uint _salt) public {
require(revealPeriodActive(_pollID));
uint numTokens = getNumTokens(msg.sender, _pollID);
pollMap[_pollID].votesFor += numTokens;
pollMap[_pollID].votesAgainst += numTokens;
}
pollMap[_pollID].didReveal[msg.sender] = true;
emit _VoteRevealed(_pollID, numTokens, pollMap[_pollID].votesFor, pollMap[_pollID].votesAgainst, _voteOption, msg.sender, _salt);
| 2,519,049 |
./partial_match/1/0x7eBc9E1B2bE8D0E32E0aFa95761538EBDD8304fD/sources/testContractCross.sol
|
routerSend This is internal function to generate a cross chain communication request. destChainId Destination ChainID. _selector Selector to interface on destination side. _data Data to be sent on Destination side. _gasLimit Gas limit provided for cross chain send. _gasPrice Gas price provided for cross chain send.
|
function routerSend(
uint8 destChainId,
bytes4 _selector,
bytes memory _data,
uint256 _gasLimit,
uint256 _gasPrice
) internal isLinkSet(destChainId) returns (bool) {
bytes memory data = abi.encode(_selector, _data);
uint64 nonce = handler.genericDeposit(
destChainId,
data,
_gasLimit,
_gasPrice,
feeToken
);
bytes32 hash = _hash(destChainId, nonce);
executes[hash] = ExecutesStruct(destChainId, nonce);
emitCrossTalkSendEvent(destChainId, _selector, _data, hash);
return (true);
}
| 15,766,660 |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./oraclize.sol";
// REQUIREMENT 1
// FlightSuretyData : contracts used for data persistence
contract FlightSuretyData is usingOraclize {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Account used to deploy contract
address private contractOwner;
// Blocks all state changes throughout the contract if false
bool private operational = true;
/** REQUIREMENT 2: Airlines
- To make it simpler, have the first airline automatically deployed
- Only existing airlines may register a new airlane until there
are at least 4 airlined registered
The second, third and fourth register airlnes are registered
by any of the airlines that had been registered to that point.
- use multi-party consensus technique to have at least 50% of the currently registered airlines
to apporve the registration.
- registration : when they get registered and approved
- 2 insuerance : each arline has to submit 10 ether
As exercise exerciseC6A create struct
uint constant M = 2;
struct UserProfile {
bool isRegistered;
bool isAdmin;
}
mapping(address => UserProfile) userProfiles // Mapping for storing user profiles
*/
// removed new status cause complex to manage with oracles
//uint8 private constant STATUS_ACCEPT_PASSENGERS = 5;
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
uint constant M = 1;
address[] multiCalls = new address[](0);
uint private constant LIMIT_PASSENGER = 100;
//create airline
struct Airline {
uint numberAirline;
address addressAirline;
bool isFunded;
}
uint countAirline = 0;
mapping(address => Airline) mapAirline;
mapping(uint => address) mapCountToAddressAirline;
/* as showed with default method getFlightKey,
* It return a key identifier of bytes32 and flight got string name flight
*/
uint countFlight = 0;
struct Flight {
address addressAirline;
string flight;
mapping(address => Passenger) mapPassenger;
mapping(uint => address) mapNumberPassengerToAddress;
uint countPassengers;
uint numberFlight;
uint8 status;
uint256 timestamp;
}
// registration : when flights get registered and approved
// bytes is abi.encode of airline + flight
mapping(bytes32 => Flight) mapFlight;
// insurance : each arline has to submit 10 ether
uint countInsurance = 0;
struct FlightInsurance {
uint numberInsurance;
Payment payment;
bool isPayed;
}
/** REQUIREMENTS 3: PASSENGERS
- passengers may pay to tone ether for insurance
- cap for the amount that a passenger may invest
- flight numbers and timestamps are fixed for the purpose of the project
and can be defined in the Dapp Client
- if flight is delayed due to airline fault
passenger receives credito fo 1.5X the amount they paid
*/
struct Payment {
uint amountToPay;
uint multiplier;
}
mapping(address => uint) mapPaymentsToDo;
/**
REQUIREMENTS 4: ORACLES
*/
/**
REQUIREMENTS 5: GENERAL
- operational status control
- function must fail fast - use require
*/
struct Passenger {
/*
The funds are transferred, if airline delay,
the passenger does not actually get the funds in their wallet,
it accumulates in their account in the smart contract,
and they have to initiate a withdrawal at which point they will be able
to get the funds
*/
address passengerAddress;
string name;
string surname;
FlightInsurance insurance;
uint numberPassenger;
}
// AUTHORIZED CONTRACTS - who can register airline, flight or passenger
mapping(address => uint256) private mapAuthorized;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
// airlines
event RegisterAirlineEvent(address _airlineAddress);
event FundedEvent(address _addressAirline);
// flight
event RegisterFlightEvent(address _airlineAddress, string _flight);
event UpdateFlightEvent(address _airlineAddress, string _flight, uint _status, uint _timestamp);
event StatusChangedEvent(uint8 _status);
// passengers
event RegisterPassengerEvent(address _airlineAddress,string _flight, address _passenger);
event BoughtInsuranceEvent(address _airlineAddress, string _flight, address _passenger);
event PayedInsuranceEvent(address _airlineAddress, string _flight, address _passenger);
event AccountWithdrawnEvent(address _passenger);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(
// To make it simpler, have the first airline automatically deployed
address _addressAirline
) public
{
contractOwner = msg.sender;
_registerAirline(_addressAirline);
// first airline already funded at start
mapAirline[_addressAirline].isFunded = true;
}
function getContractOwner()
external
view
returns (string) {
return addressToString(contractOwner);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner,
strConcat("Caller is not contract owner : ",
addressToString(msg.sender),
addressToString(contractOwner)));
_;
}
modifier requireAuthorized(address _msgSender) {
require(mapAuthorized[_msgSender] == 1, strConcat("Caller is not authorized",
addressToString(_msgSender)));
_;
}
// removed but could be a good idea to have timer on registering and dont allow double entry
/*
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus( bool mode )
external
requireContractOwner
{
require(mode != operational, "Mode is different from operational");
bool isDuplicate = false;
for(uint i = 0; i < multiCalls.length; i++) {
if (multiCalls[i] == msg.sender) {
isDuplicate = true;
break;
}
}
require(!isDuplicate, "Already Present.");
multiCalls.push(msg.sender);
if (multiCalls.length >= M) {
operational = mode;
multiCalls = new address[](0);
}
}
// manage authorization
function authorizeCaller(address _addressToAuth)
external
requireContractOwner
{
mapAuthorized[_addressToAuth] = 1;
}
function isAuthorizedCaller(address _addressToAuth)
external
view
returns (bool)
{
return mapAuthorized[_addressToAuth] == 1;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
//-----------------------------------------------------//
// ------------------ PASSENGER ------------------------- //
//-----------------------------------------------------//
function registerPassenger (
address _addressAirline,
string _flight,
address _addressPassenger,
string _name,
string _surname
)
requireIsOperational
requireAuthorized(_addressAirline)
external {
require( mapAirline[_addressAirline].isFunded, "Airline is not already funded");
require( mapAirline[_addressAirline].numberAirline > 0, "Airline is not already registered");
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
require(mapFlight[_flightKey].numberFlight > 0,
"Flight doesn't exists");
/*require(mapFlight[_flightKey].status == STATUS_ACCEPT_PASSENGERS,
"Flight status doesn't accept anymore passengers");*/
require(mapFlight[_flightKey].mapPassenger[_addressPassenger].numberPassenger == 0,
'Already registered Passenger');
require(mapFlight[_flightKey].countPassengers < LIMIT_PASSENGER,
'All busy');
uint _countPassengers = mapFlight[_flightKey].countPassengers;
_countPassengers = _countPassengers.add(1);
mapFlight[_flightKey].mapPassenger[_addressPassenger].passengerAddress = _addressPassenger;
mapFlight[_flightKey].mapPassenger[_addressPassenger].name = _name;
mapFlight[_flightKey].mapPassenger[_addressPassenger].surname = _surname;
mapFlight[_flightKey].mapPassenger[_addressPassenger].numberPassenger = _countPassengers;
mapFlight[_flightKey].mapNumberPassengerToAddress[_countPassengers] = _addressPassenger;
mapFlight[_flightKey].countPassengers = _countPassengers;
emit RegisterPassengerEvent(_addressAirline, _flight, _addressPassenger);
}
function isPassenger(
address _addressAirline,
string _flight,
address _addressPassenger
)
external
view
returns(bool) {
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
return mapFlight[_flightKey].mapPassenger[_addressPassenger].numberPassenger > 0;
}
function getPassengerCountByFlight(
address _addressAirline,
string _flight
)
external
view
returns(uint) {
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
return mapFlight[_flightKey].countPassengers;
}
//-----------------------------------------------------//
// ------------------ FLIGHT ------------------------- //
//-----------------------------------------------------//
function registerFlight(
address _addressAirline,
string _flight,
address _msgSender
) external
requireIsOperational
requireAuthorized(_msgSender)
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
require(! (mapFlight[_flightKey].numberFlight > 0), "Flight has already been registered");
require( mapAirline[_addressAirline].isFunded, "Airline is not already funded");
countFlight = countFlight.add(1);
mapFlight[_flightKey].addressAirline = _addressAirline;
mapFlight[_flightKey].flight = _flight;
mapFlight[_flightKey].numberFlight = countFlight;
mapFlight[_flightKey].countPassengers = 0;
emit RegisterFlightEvent(_addressAirline, _flight);
}
// check if is flight registered
function isFlight(
address _addressAirline,
string _flight
)
external
view
returns(bool) {
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
return mapFlight[_flightKey].numberFlight > 0;
}
function getFlightCount()
external
view
returns(uint) {
return countFlight;
}
//-----------------------------------------------------//
// ------------------ AIRLINE ------------------------ //
//-----------------------------------------------------//
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline (
address _addressAirline,
address _msgSender
)
requireIsOperational
requireAuthorized(_msgSender)
external
{
require(getAirlineNumberByAddress(_addressAirline) == 0,
"Airline is already registered");
require(mapAirline[_addressAirline].isFunded,
"Airline is not funded");
_registerAirline(_addressAirline);
emit RegisterAirlineEvent(_addressAirline);
}
function _registerAirline (
address _addressAirline
)
internal
{
countAirline = countAirline.add(1);
mapAirline[_addressAirline].numberAirline = countAirline;
mapAirline[_addressAirline].addressAirline = _addressAirline;
mapCountToAddressAirline[countAirline] = _addressAirline;
}
function getAirlinesCount()
external
view
requireIsOperational
returns (uint){
return countAirline;
}
function isAirline(address _addressAirline)
external
view
returns (bool result) {
for (uint idxAirlines = 1 ;
idxAirlines <= countAirline;
idxAirlines++) {
if(_addressAirline == mapCountToAddressAirline[idxAirlines]) {
return true;
}
}
return false;
}
function getAirlineNumberByAddress(address _addressAirline)
public
view
returns (uint _numberAirline) {
for (uint idxAirlines = 1 ;
idxAirlines <= countAirline;
idxAirlines++) {
if(_addressAirline == mapCountToAddressAirline[idxAirlines]) {
return idxAirlines;
}
}
return 0;
}
function getAirlineAddressByNumber(uint _numberAirline)
public
view
returns (address _addressAirline) {
for (uint idxAirlines = 1 ;
idxAirlines <= countAirline;
idxAirlines++) {
if(idxAirlines == _numberAirline) {
return mapCountToAddressAirline[idxAirlines];
}
}
}
function getAirlineAddressStringByNumber(uint _numberAirline)
public
view
returns (string _addressAirline) {
for (uint idxAirlines = 1 ;
idxAirlines <= countAirline;
idxAirlines++) {
if(idxAirlines == _numberAirline) {
return addressToString(mapCountToAddressAirline[idxAirlines]);
}
}
}
function isFund(address _addressAirline)
public
view
returns (bool) {
return mapAirline[_addressAirline].isFunded;
}
// has required form suretyApp, need a method to processFlightStatus
function processFlightStatus(
address _addressAirline,
string _flight,
uint8 _status,
uint _timestamp,
address _oracleAddress)
requireIsOperational
requireAuthorized(_oracleAddress)
external
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
require(mapFlight[_flightKey].numberFlight > 0, "Flight is not registered");
mapFlight[_flightKey].status = _status;
mapFlight[_flightKey].timestamp = _timestamp;
if(_status == STATUS_CODE_LATE_AIRLINE) {
for (uint idxPassenger = 1 ;
idxPassenger <= mapFlight[_flightKey].countPassengers;
idxPassenger++) {
address _addressPassenger = mapFlight[_flightKey].mapNumberPassengerToAddress[idxPassenger];
if(_addressPassenger != address(0)) {
creditInsurees(
_addressAirline,
_flight,
_addressPassenger);
}
}
}
emit StatusChangedEvent(_status);
}
function fund( address _addressAirline)
external
payable
requireIsOperational
{
require(!mapAirline[_addressAirline].isFunded, "Airline already funded");
mapAirline[_addressAirline].isFunded = true;
emit FundedEvent(_addressAirline);
}
/**
* @dev Buy insurance for a flight
*
*/
function buy (
address _addressAirline,
string _flight,
address _passengerAddress,
uint _amount,
uint _multiplier,
address msgSender
)
external
payable
requireIsOperational
requireAuthorized(msgSender)
returns (uint)
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
require(msgSender == tx.origin, "Contracts not allowed");
require(mapFlight[_flightKey].numberFlight > 0, "Flight is not registered");
require(mapFlight[_flightKey].mapPassenger[_passengerAddress].numberPassenger > 0,
"Its not a passenger of this flight");
countInsurance = countInsurance.add(1);
mapFlight[_flightKey].mapPassenger[_passengerAddress].insurance.numberInsurance = countInsurance;
mapFlight[_flightKey].mapPassenger[_passengerAddress].insurance.isPayed = false;
Payment memory _payment = Payment({
amountToPay : _amount,
multiplier : _multiplier
});
mapFlight[_flightKey].mapPassenger[_passengerAddress].insurance.payment = _payment;
emit BoughtInsuranceEvent(_addressAirline, _flight, _passengerAddress);
return countInsurance;
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees (
address _addressAirline,
string _flight,
address _passengerAddress
) public
requireIsOperational
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
require(mapFlight[_flightKey].numberFlight > 0, "Flight is not registered");
require(mapFlight[_flightKey].mapPassenger[_passengerAddress].numberPassenger > 0,
"Passenger is not registered");
mapFlight[_flightKey].mapPassenger[_passengerAddress].insurance.isPayed = true;
uint _amountToPay =
mapFlight[_flightKey].mapPassenger[_passengerAddress].insurance.payment.amountToPay
.mul(mapFlight[_flightKey].mapPassenger[_passengerAddress].insurance.payment.multiplier)
.div(100);
mapPaymentsToDo[_passengerAddress] = _amountToPay;
emit PayedInsuranceEvent(_addressAirline, _flight, _passengerAddress);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay (
address _passengerAddress
)
external
requireIsOperational
requireAuthorized(_passengerAddress)
{
uint _amountToPay = mapPaymentsToDo[_passengerAddress];
mapPaymentsToDo[_passengerAddress] = 0;
_passengerAddress.transfer(_amountToPay);
emit AccountWithdrawnEvent(_passengerAddress);
}
function hasInsurance(
address _addressAirline,
string _flight,
address _addressPassenger
)
external
view
requireIsOperational
returns (bool)
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
return mapFlight[_flightKey].mapPassenger[_addressPassenger].insurance.numberInsurance != 0;
}
function getInsurance(
address _addressAirline,
string _flight,
address _addressPassenger
)
external
view
requireIsOperational
returns (uint)
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
return mapFlight[_flightKey].mapPassenger[_addressPassenger].insurance.numberInsurance;
}
function isPayed(
address _addressAirline,
string _flight,
address _addressPassenger
)
external
view
requireIsOperational
returns (bool)
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
return mapFlight[_flightKey].mapPassenger[_addressPassenger].insurance.isPayed;
}
function getCountInsurance()
external
view
requireIsOperational
returns (uint)
{
return countInsurance;
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
)
public
payable
{
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function getFlightKeyOfMap
(
address airline,
string memory flight
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight));
}
function getFlightStatus
(
address _addressAirline,
string _flight
)
external
view
returns(uint8)
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
return mapFlight[_flightKey].status;
}
// conversion function tiped by stackoverflow
function addressToString(address _address)
pure
internal
returns (string memory _uintAsString) {
bytes32 value = bytes32(uint256(_address));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(51);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < 20; i++) {
str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))];
str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];
}
return string(str);
}
// conversion function tiped by stackoverflow
function uintToString(uint v)
pure
internal
returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i + 1);
for (uint j = 0; j <= i; j++) {
s[j] = reversed[i - j];
}
str = string(s);
}
function getPassengerInfo
(
address _addressAirline,
string _flight,
uint idx
)
public
view
returns(string)
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
address _addressPassenger = mapFlight[_flightKey].mapNumberPassengerToAddress[idx];
mapFlight[_flightKey].mapPassenger[_addressPassenger].passengerAddress;
mapFlight[_flightKey].mapPassenger[_addressPassenger].name;
mapFlight[_flightKey].mapPassenger[_addressPassenger].surname;
mapFlight[_flightKey].mapPassenger[_addressPassenger].numberPassenger;
string memory addressPassengerString = strConcat("addressPassengerString :",
addressToString(mapFlight[_flightKey].mapPassenger[_addressPassenger].passengerAddress));
string memory nameString = strConcat("name :",
mapFlight[_flightKey].mapPassenger[_addressPassenger].name);
string memory surnameString = strConcat("surname :",
mapFlight[_flightKey].mapPassenger[_addressPassenger].surname);
string memory numberString = strConcat("numberPassenger :",
uintToString(mapFlight[_flightKey].mapPassenger[_addressPassenger].numberPassenger));
string memory part1 = strConcat(addressPassengerString, nameString, surnameString, numberString);
return part1;
}
function getFlightInfo
(
address _addressAirline,
string _flight
)
public
view
returns(string)
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
string memory addressString = strConcat("airline :", addressToString(mapFlight[_flightKey].addressAirline));
string memory flightString = strConcat("flight :", mapFlight[_flightKey].flight);
string memory timestampString = strConcat("timestamp :", uintToString(mapFlight[_flightKey].timestamp));
string memory countPassString = strConcat("countPassengers :", uintToString(mapFlight[_flightKey].countPassengers));
string memory numberString = strConcat("numberFlight :", uintToString(mapFlight[_flightKey].numberFlight));
string memory statusString = strConcat("status :", uintToString(mapFlight[_flightKey].status));
string memory part1 = strConcat(addressString, flightString, timestampString);
string memory part2 = strConcat(countPassString, numberString, statusString);
return strConcat(part1, part2);
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
|
Credits payouts to insurees/
|
function creditInsurees (
address _addressAirline,
string _flight,
address _passengerAddress
) public
requireIsOperational
{
bytes32 _flightKey = getFlightKeyOfMap(_addressAirline, _flight);
require(mapFlight[_flightKey].numberFlight > 0, "Flight is not registered");
require(mapFlight[_flightKey].mapPassenger[_passengerAddress].numberPassenger > 0,
"Passenger is not registered");
mapFlight[_flightKey].mapPassenger[_passengerAddress].insurance.isPayed = true;
uint _amountToPay =
mapFlight[_flightKey].mapPassenger[_passengerAddress].insurance.payment.amountToPay
.mul(mapFlight[_flightKey].mapPassenger[_passengerAddress].insurance.payment.multiplier)
.div(100);
mapPaymentsToDo[_passengerAddress] = _amountToPay;
emit PayedInsuranceEvent(_addressAirline, _flight, _passengerAddress);
}
| 12,788,876 |
./full_match/11155111/0x372b8E841e62Ab5852521420847929cc752dDB83/sources/contracts/shared/libraries/LibAccessControl.sol
|
Checks if an account has a role roleId Role ID account Account address return bool True if account has the role, false otherwise/
|
function hasRole(bytes32 roleId, address account) internal view returns (bool) {
AccessControlStorage storage acs = diamondStorage();
return acs.roles[roleId][account];
}
| 3,804,943 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./NeoAnunnaki.sol";
/// @title NeoLocker
/// @author aceplxx (https://twitter.com/aceplxx)
contract NeoLocker is ReentrancyGuard, Ownable {
bool public rewardPaused = true;
address public genetix;
NeoAnunnaki private neoAnunnaki;
uint256 public baseReward;
// Mapping from token ID to locker address
mapping(uint256 => address) private _lockedBy;
mapping(address => uint256) public lockedAmount;
mapping(address => uint256) public lastClaimed;
/* ========== MODIFIERS ========== */
modifier onlyNFTContract() {
require(msg.sender == address(neoAnunnaki), "Only NFT Contract");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(address _genetix, address payable _neoAnunnaki, uint256 _baseReward){
genetix = _genetix;
neoAnunnaki = NeoAnunnaki(_neoAnunnaki);
baseReward = _baseReward;
}
/* ========== OWNER FUNCTIONS ========== */
function toggleRewardPaused() external onlyOwner{
rewardPaused = !rewardPaused;
}
function setToken(address _token) external onlyOwner{
genetix = _token;
}
function setNeoNFT(address payable _neoAnunnaki) external onlyOwner{
neoAnunnaki = NeoAnunnaki(_neoAnunnaki);
}
function clearLock(uint256 _tokenId) external onlyNFTContract{
delete _lockedBy[_tokenId];
}
/* ========== PUBLIC READ ========== */
function neoAnunnakiContract() external view returns (address){
return address(neoAnunnaki);
}
/// @notice get pending reward of a user (if any)
/// @param _user wallet address of a user
function getPendingReward(address _user)
external
view
returns (uint256 rewards)
{
rewards = _getPendingReward(_user);
}
/// @notice check whether an NFT is locked by an address
/// @param tokenId NFT token id
function lockedBy(uint256 tokenId) external view returns (address) {
return _lockedBy[tokenId];
}
/* ========== PUBLIC MUTATIVE ========== */
/// @notice lock an NFT to earn $GENETIX, locked NFT is not transferable
/// @param tokenId NFT token id to be locked
function lock(uint256 tokenId) external nonReentrant {
require(
neoAnunnaki.ownerOf(tokenId) == msg.sender,
"Not owner nor approved"
);
require(_lockedBy[tokenId] == address(0), "already locked");
_lockedBy[tokenId] = msg.sender;
uint256 reward = _getPendingReward(msg.sender);
lastClaimed[msg.sender] = block.timestamp;
lockedAmount[msg.sender]++;
if (reward > 0 && !rewardPaused) {
_harvestReward(reward);
}
}
/// @notice unlock an NFT
/// @param tokenId NFT token id to be unlocked
function unlock(uint256 tokenId) external nonReentrant {
require(
neoAnunnaki.exists(tokenId),
"Nonexistent token"
);
require(_lockedBy[tokenId] == msg.sender, "caller is not locker");
delete _lockedBy[tokenId];
uint256 reward = _getPendingReward(msg.sender);
lastClaimed[msg.sender] = block.timestamp;
lockedAmount[msg.sender]--;
if (reward > 0 && !rewardPaused) {
_harvestReward(reward);
}
}
function harvestReward() external {
uint256 reward = _getPendingReward(msg.sender);
_harvestReward(reward);
}
/* ========== INTERNAL FUNCTIONS ========== */
function _getPendingReward(address _user) internal view returns (uint256) {
return
(lockedAmount[_user] *
baseReward *
(block.timestamp - lastClaimed[_user])) / 86400;
}
function _harvestReward(uint256 _reward) internal {
require(!rewardPaused, "Claiming reward has been paused");
lastClaimed[msg.sender] = block.timestamp;
IERC20(genetix).transfer(msg.sender, _reward);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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
pragma solidity ^0.8.0;
import "./SignedAllowance.sol";
import "./ERC721A.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./PaymentSplitter.sol";
import "./NeoLocker.sol";
/// @title NeoAnunnaki
/// @author aceplxx (https://twitter.com/aceplxx)
enum SaleState {
Paused,
Presale,
Public
}
contract NeoAnunnaki is ERC721A, Ownable, SignedAllowance, PaymentSplitter {
/* ========== STORAGE ========== */
SaleState public saleState;
NeoLocker private neoLocker;
string public baseURI;
string public lockedURI;
string public contractURI;
uint256 public maxPerTx = 3;
uint256 public constant MAX_SUPPLY = 3690;
uint256 public constant TEAM_RESERVES = 30;
uint256 public price = 0.06 ether;
bool public notRevealed = true;
/* ========== CONSTRUCTOR ========== */
constructor(
string memory baseURI_,
address allowancesSigner_,
address[] memory _payees,
uint256[] memory _shares
)
ERC721A("Neo Anunnaki", "NEO-ANUNNAKI")
PaymentSplitter(_payees, _shares)
{
baseURI = baseURI_;
_setAllowancesSigner(allowancesSigner_);
}
/* ========== MODIFIERS ========== */
modifier mintCompliance(uint256 _amount){
require(_amount > 0, "Bad mints");
require(totalSupply() + _amount <= MAX_SUPPLY, "Exceeds max supply");
require(_amount <= maxPerTx, "Exceeds max amount");
_;
}
modifier notPaused(){
require(saleState != SaleState.Paused, "Minting paused");
_;
}
/* ========== OWNER FUNCTIONS ========== */
/// @notice set the state of the sale
/// @param _state the state in int accordingly
function setSaleState(SaleState _state) external onlyOwner {
saleState = _state;
}
/// @notice toggle the reveal / unreveal status
function toggleReveal() external onlyOwner {
notRevealed = !notRevealed;
}
function setLocker(address _locker) external onlyOwner {
neoLocker = NeoLocker(_locker);
}
function mintConfig(
uint256 _price,
uint256 _maxPerTx
) external onlyOwner {
price = _price;
maxPerTx = _maxPerTx;
}
function setBaseURI(string memory baseURI_) external onlyOwner {
baseURI = baseURI_;
}
function setContractURI(string memory _contractURI) external onlyOwner {
contractURI = _contractURI;
}
/// @notice set lockedURI. If NFT is locked, lockedURI will be displayed instead of baseURI
/// @param _lockedURI uri string for the locked NFT
function setLockedURI(string memory _lockedURI) external onlyOwner {
lockedURI = _lockedURI;
}
/// @notice sets allowance signer, this can be used to revoke all unused allowances already out there
/// @param newSigner the new signer
function setAllowancesSigner(address newSigner) external onlyOwner {
_setAllowancesSigner(newSigner);
}
function mintReserves() external onlyOwner {
require(saleState == SaleState.Paused, "Not paused");
_safeMint(msg.sender, TEAM_RESERVES);
}
function withdraw() public virtual override {
require(msg.sender == owner(), "Only owner!");
super.withdraw();
}
/* ========== PUBLIC READ FUNCTIONS ========== */
function exists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(_exists(tokenId), "Token does not exist.");
if(neoLocker.lockedBy(tokenId) == address(0)) {
return
notRevealed ? baseURI : bytes(baseURI).length > 0
? string(
abi.encodePacked(
baseURI,
Strings.toString(tokenId),
".json"
)
)
: "";
} else {
return lockedURI;
}
}
/* ========== PUBLIC MUTATIVE FUNCTIONS ========== */
/// @notice public mint function
/// @param _amount amount of token to mint
function mint(uint256 _amount) external payable notPaused mintCompliance(_amount) {
require(saleState == SaleState.Public, "Public sale not started");
require(msg.value >= _amount * price, "Insufficient fund");
_safeMint(msg.sender, _amount);
}
/// @notice presale mint function
/// @param nonce the nonce
/// @param signature ECDSA based signed whitelist
/// @param _amount amount of token to mint
function presaleMint(uint256 nonce, bytes memory signature, uint256 _amount)
external
payable
notPaused
mintCompliance(_amount) {
require(saleState == SaleState.Presale, "Presale not started");
require(msg.value >= _amount * price, "Insufficient fund");
validateSignature(msg.sender, nonce, signature);
_safeMint(msg.sender, _amount);
}
/* ========== INTERNAL FUNCTIONS ========== */
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual override {
if (neoLocker.lockedBy(startTokenId) != to) {
require(
neoLocker.lockedBy(startTokenId) == address(0),
"Transfer while locked"
);
} else {
neoLocker.clearLock(startTokenId);
}
super._beforeTokenTransfers(from, to, startTokenId, quantity);
}
}
// 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
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/// @title SignedAllowance
/// @author Simon Fremaux (@dievardump)
contract SignedAllowance {
using ECDSA for bytes32;
// list of already used allowances
mapping(bytes32 => bool) public usedAllowances;
// address used to sign the allowances
address private _allowancesSigner;
/// @notice Helper to know allowancesSigner address
/// @return the allowance signer address
function allowancesSigner() public view virtual returns (address) {
return _allowancesSigner;
}
/// @notice Helper that creates the message that signer needs to sign to allow a mint
/// this is usually also used when creating the allowances, to ensure "message"
/// is the same
/// @param account the account to allow
/// @param nonce the nonce
/// @return the message to sign
function createMessage(address account, uint256 nonce)
public
view
returns (bytes32)
{
return keccak256(abi.encode(account, nonce, address(this)));
}
/// @notice Helper that creates a list of messages that signer needs to sign to allow mintings
/// @param accounts the accounts to allow
/// @param nonces the corresponding nonces
/// @return messages the messages to sign
function createMessages(address[] memory accounts, uint256[] memory nonces)
external
view
returns (bytes32[] memory messages)
{
require(accounts.length == nonces.length, '!LENGTH_MISMATCH!');
messages = new bytes32[](accounts.length);
for (uint256 i; i < accounts.length; i++) {
messages[i] = createMessage(accounts[i], nonces[i]);
}
}
/// @notice This function verifies that the current request is valid
/// @dev It ensures that _allowancesSigner signed a message containing (account, nonce, address(this))
/// and that this message was not already used
/// @param account the account the allowance is associated to
/// @param nonce the nonce associated to this allowance
/// @param signature the signature by the allowance signer wallet
/// @return the message to mark as used
function validateSignature(
address account,
uint256 nonce,
bytes memory signature
) public view returns (bytes32) {
return
_validateSignature(account, nonce, signature, allowancesSigner());
}
/// @dev It ensures that signer signed a message containing (account, nonce, address(this))
/// and that this message was not already used
/// @param account the account the allowance is associated to
/// @param nonce the nonce associated to this allowance
/// @param signature the signature by the allowance signer wallet
/// @param signer the signer
/// @return the message to mark as used
function _validateSignature(
address account,
uint256 nonce,
bytes memory signature,
address signer
) internal view returns (bytes32) {
bytes32 message = createMessage(account, nonce)
.toEthSignedMessageHash();
// verifies that the sha3(account, nonce, address(this)) has been signed by signer
require(message.recover(signature) == signer, '!INVALID_SIGNATURE!');
// verifies that the allowances was not already used
require(usedAllowances[message] == false, '!ALREADY_USED!');
return message;
}
/// @notice internal function that verifies an allowance and marks it as used
/// this function throws if signature is wrong or this nonce for this user has already been used
/// @param account the account the allowance is associated to
/// @param nonce the nonce
/// @param signature the signature by the allowance wallet
function _useAllowance(
address account,
uint256 nonce,
bytes memory signature
) internal {
bytes32 message = validateSignature(account, nonce, signature);
usedAllowances[message] = true;
}
/// @notice Allows to change the allowance signer. This can be used to revoke any signed allowance not already used
/// @param newSigner the new signer address
function _setAllowancesSigner(address newSigner) internal {
_allowancesSigner = newSigner;
}
}
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/interfaces/IERC721.sol";
import "@openzeppelin/contracts/interfaces/IERC721Metadata.sol";
import "@openzeppelin/contracts/interfaces/IERC721Enumerable.sol";
import "@openzeppelin/contracts/interfaces/IERC721Receiver.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*
* Assumes that an owner cannot have more than the 2**128 (max value of uint128) of supply
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 internal currentIndex = 0;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721A: balance query for the zero address"
);
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
for (uint256 curr = tokenId; ; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721A: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
override
{
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity > 0, "ERC721A: quantity must be greater 0");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
}
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721A: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol)
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*
* NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
* tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
* to run tests before sending real value to this contract.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
mapping(IERC20 => uint256) private _erc20TotalReleased;
mapping(IERC20 => mapping(address => uint256)) private _erc20Released;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
* contract.
*/
function totalReleased(IERC20 token) public view returns (uint256) {
return _erc20TotalReleased[token];
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
* IERC20 contract.
*/
function released(IERC20 token, address account) public view returns (uint256) {
return _erc20Released[token][account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
function withdraw() public virtual{
for (uint256 i = 0; i < _payees.length; i++) {
_release(payable(_payees[i]));
}
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function _release(address payable account) internal {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + totalReleased();
uint256 payment = _pendingPayment(account, totalReceived, released(account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] += payment;
_totalReleased += payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev internal logic for computing the pending payment of an `account` given the token historical balances and
* already released amounts.
*/
function _pendingPayment(
address account,
uint256 totalReceived,
uint256 alreadyReleased
) private view returns (uint256) {
return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// 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/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 (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 (interfaces/IERC721.sol)
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../token/ERC721/extensions/IERC721Metadata.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../token/ERC721/extensions/IERC721Enumerable.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Receiver.sol)
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721Receiver.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// 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/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");
}
}
}
|
Transfers `tokenId` from `from` to `to`. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./ Clear approvals from the previous owner Underflow of the sender's balance is impossible because we check for ownership above and the recipient's balance can't realistically overflow.
|
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
}
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
| 1,263,374 |
pragma solidity ^0.5.16;
contract Account {
uint public balance;
uint public constant MAX_UINT = 2 ** 256 - 1;
function deposit(uint _amount) public {
uint oldBalance = balance;
uint newBalance = balance + _amount;
// Require should be used to validate conditions such as:
// - inputs
// - conditions before execution
// - return values from calls to other functions
// balance + _amount does not overflow if balance + _amount >= balance
require(newBalance >= oldBalance, "Overflow");
balance = newBalance;
// Assert should only be used to test for internal errors,
// and to check invariants.
assert(balance >= oldBalance);
}
function withdraw(uint _amount) public {
uint oldBalance = balance;
// balance - _amount does not underflow if balance >= _amount
require(balance >= _amount, "Underflow");
// Revert can be used to throw an error.
if (balance < _amount) {
revert("Underflow");
}
balance -= _amount;
assert(balance <= oldBalance);
}
}
|
Require should be used to validate conditions such as: - inputs - conditions before execution - return values from calls to other functions balance + _amount does not overflow if balance + _amount >= balance Assert should only be used to test for internal errors, and to check invariants.
|
function deposit(uint _amount) public {
uint oldBalance = balance;
uint newBalance = balance + _amount;
require(newBalance >= oldBalance, "Overflow");
balance = newBalance;
assert(balance >= oldBalance);
}
| 6,417,827 |
./full_match/1/0xd9bF1095718405B4dF89f8E54EcC6D388aE2Be91/sources/contracts/danglydoodads.sol
|
change royalty settings/
|
function updateRoyalties(address _receiver, uint16 _basisPoint) external onlyOwner {
_setDefaultRoyalty(_receiver, _basisPoint);
}
| 9,645,174 |
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { IClaimAdapter } from "../../interfaces/IClaimAdapter.sol";
import { IController } from "../../interfaces/IController.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
/**
* @title ClaimModule
* @author Set Protocol
*
* Module that enables managers to claim tokens from external protocols given to the Set as part of participating in
* incentivized activities of other protocols. The ClaimModule works in conjunction with ClaimAdapters, in which the
* claimAdapterID / integrationNames are stored on the integration registry.
*
* Design:
* The ecosystem is coalescing around a few standards of how reward programs are created, using forks of popular
* contracts such as Synthetix's Mintr. Thus, the Claim architecture reflects a more functional vs external-protocol
* approach where an adapter with common functionality can be used across protocols.
*
* Definitions:
* Reward Pool: A reward pool is a contract associated with an external protocol's reward. Examples of reward pools
* include the Curve sUSDV2 Gauge or the Synthetix iBTC StakingReward contract.
* Adapter: An adapter contains the logic and context for how a reward pool should be claimed - returning the requisite
* function signature. Examples of adapters include StakingRewardAdapter (for getting rewards from Synthetix-like
* reward contracts) and CurveClaimAdapter (for calling Curve Minter contract's mint function)
* ClaimSettings: A reward pool can be associated with multiple awards. For example, a Curve liquidity gauge can be
* associated with the CURVE_CLAIM adapter to claim CRV and CURVE_DIRECT adapter to claim BPT.
*/
contract ClaimModule is ModuleBase {
using AddressArrayUtils for address[];
/* ============ Events ============ */
event RewardClaimed(
ISetToken indexed _setToken,
address indexed _rewardPool,
IClaimAdapter indexed _adapter,
uint256 _amount
);
event AnyoneClaimUpdated(
ISetToken indexed _setToken,
bool _anyoneClaim
);
/* ============ Modifiers ============ */
/**
* Throws if claim is confined to the manager and caller is not the manager
*/
modifier onlyValidCaller(ISetToken _setToken) {
require(_isValidCaller(_setToken), "Must be valid caller");
_;
}
/* ============ State Variables ============ */
// Indicates if any address can call claim or just the manager of the SetToken
mapping(ISetToken => bool) public anyoneClaim;
// Map and array of rewardPool addresses to claim rewards for the SetToken
mapping(ISetToken => address[]) public rewardPoolList;
// Map from set tokens to rewards pool address to isAdded boolean. Used to check if a reward pool has been added in O(1) time
mapping(ISetToken => mapping(address => bool)) public rewardPoolStatus;
// Map and array of adapters associated to the rewardPool for the SetToken
mapping(ISetToken => mapping(address => address[])) public claimSettings;
// Map from set tokens to rewards pool address to claim adapters to isAdded boolean. Used to check if an adapter has been added in O(1) time
mapping(ISetToken => mapping(address => mapping(address => bool))) public claimSettingsStatus;
/* ============ Constructor ============ */
constructor(IController _controller) public ModuleBase(_controller) {}
/* ============ External Functions ============ */
/**
* Claim the rewards available on the rewardPool for the specified claim integration.
* Callable only by manager unless manager has set anyoneClaim to true.
*
* @param _setToken Address of SetToken
* @param _rewardPool Address of the rewardPool that identifies the contract governing claims
* @param _integrationName ID of claim module integration (mapping on integration registry)
*/
function claim(
ISetToken _setToken,
address _rewardPool,
string calldata _integrationName
)
external
onlyValidAndInitializedSet(_setToken)
onlyValidCaller(_setToken)
{
_claim(_setToken, _rewardPool, _integrationName);
}
/**
* Claims rewards on all the passed rewardPool/claim integration pairs. Callable only by manager unless manager has
* set anyoneClaim to true.
*
* @param _setToken Address of SetToken
* @param _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same
* index integrationNames
* @param _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index
* in rewardPools
*/
function batchClaim(
ISetToken _setToken,
address[] calldata _rewardPools,
string[] calldata _integrationNames
)
external
onlyValidAndInitializedSet(_setToken)
onlyValidCaller(_setToken)
{
uint256 poolArrayLength = _validateBatchArrays(_rewardPools, _integrationNames);
for (uint256 i = 0; i < poolArrayLength; i++) {
_claim(_setToken, _rewardPools[i], _integrationNames[i]);
}
}
/**
* SET MANAGER ONLY. Update whether manager allows other addresses to call claim.
*
* @param _setToken Address of SetToken
*/
function updateAnyoneClaim(ISetToken _setToken, bool _anyoneClaim) external onlyManagerAndValidSet(_setToken) {
anyoneClaim[_setToken] = _anyoneClaim;
emit AnyoneClaimUpdated(_setToken, _anyoneClaim);
}
/**
* SET MANAGER ONLY. Adds a new claim integration for an existent rewardPool. If rewardPool doesn't have existing
* claims then rewardPool is added to rewardPoolLiost. The claim integration is associated to an adapter that
* provides the functionality to claim the rewards for a specific token.
*
* @param _setToken Address of SetToken
* @param _rewardPool Address of the rewardPool that identifies the contract governing claims
* @param _integrationName ID of claim module integration (mapping on integration registry)
*/
function addClaim(
ISetToken _setToken,
address _rewardPool,
string calldata _integrationName
)
external
onlyManagerAndValidSet(_setToken)
{
_addClaim(_setToken, _rewardPool, _integrationName);
}
/**
* SET MANAGER ONLY. Adds a new rewardPool to the list to perform claims for the SetToken indicating the list of
* claim integrations. Each claim integration is associated to an adapter that provides the functionality to claim
* the rewards for a specific token.
*
* @param _setToken Address of SetToken
* @param _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same
* index integrationNames
* @param _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index
* in rewardPools
*/
function batchAddClaim(
ISetToken _setToken,
address[] calldata _rewardPools,
string[] calldata _integrationNames
)
external
onlyManagerAndValidSet(_setToken)
{
_batchAddClaim(_setToken, _rewardPools, _integrationNames);
}
/**
* SET MANAGER ONLY. Removes a claim integration from an existent rewardPool. If no claim remains for reward pool then
* reward pool is removed from rewardPoolList.
*
* @param _setToken Address of SetToken
* @param _rewardPool Address of the rewardPool that identifies the contract governing claims
* @param _integrationName ID of claim module integration (mapping on integration registry)
*/
function removeClaim(
ISetToken _setToken,
address _rewardPool,
string calldata _integrationName
)
external
onlyManagerAndValidSet(_setToken)
{
_removeClaim(_setToken, _rewardPool, _integrationName);
}
/**
* SET MANAGER ONLY. Batch removes claims from SetToken's settings.
*
* @param _setToken Address of SetToken
* @param _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same index
* integrationNames
* @param _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index in
* rewardPools
*/
function batchRemoveClaim(
ISetToken _setToken,
address[] calldata _rewardPools,
string[] calldata _integrationNames
)
external
onlyManagerAndValidSet(_setToken)
{
uint256 poolArrayLength = _validateBatchArrays(_rewardPools, _integrationNames);
for (uint256 i = 0; i < poolArrayLength; i++) {
_removeClaim(_setToken, _rewardPools[i], _integrationNames[i]);
}
}
/**
* SET MANAGER ONLY. Initializes this module to the SetToken.
*
* @param _setToken Instance of the SetToken to issue
* @param _anyoneClaim Boolean indicating if anyone can claim or just manager
* @param _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same index
* integrationNames
* @param _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index in
* rewardPools
*/
function initialize(
ISetToken _setToken,
bool _anyoneClaim,
address[] calldata _rewardPools,
string[] calldata _integrationNames
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
_batchAddClaim(_setToken, _rewardPools, _integrationNames);
anyoneClaim[_setToken] = _anyoneClaim;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken.
*/
function removeModule() external override {
delete anyoneClaim[ISetToken(msg.sender)];
// explicitly delete all elements for gas refund
address[] memory setTokenPoolList = rewardPoolList[ISetToken(msg.sender)];
for (uint256 i = 0; i < setTokenPoolList.length; i++) {
address[] storage adapterList = claimSettings[ISetToken(msg.sender)][setTokenPoolList[i]];
for (uint256 j = 0; j < adapterList.length; j++) {
address toRemove = adapterList[j];
claimSettingsStatus[ISetToken(msg.sender)][setTokenPoolList[i]][toRemove] = false;
delete adapterList[j];
}
delete claimSettings[ISetToken(msg.sender)][setTokenPoolList[i]];
}
for (uint256 i = 0; i < rewardPoolList[ISetToken(msg.sender)].length; i++) {
address toRemove = rewardPoolList[ISetToken(msg.sender)][i];
rewardPoolStatus[ISetToken(msg.sender)][toRemove] = false;
delete rewardPoolList[ISetToken(msg.sender)][i];
}
delete rewardPoolList[ISetToken(msg.sender)];
}
/**
* Get list of rewardPools to perform claims for the SetToken.
*
* @param _setToken Address of SetToken
* @return Array of rewardPool addresses to claim rewards for the SetToken
*/
function getRewardPools(ISetToken _setToken) external view returns (address[] memory) {
return rewardPoolList[_setToken];
}
/**
* Get boolean indicating if the rewardPool is in the list to perform claims for the SetToken.
*
* @param _setToken Address of SetToken
* @param _rewardPool Address of rewardPool
* @return Boolean indicating if the rewardPool is in the list for claims.
*/
function isRewardPool(ISetToken _setToken, address _rewardPool) public view returns (bool) {
return rewardPoolStatus[_setToken][_rewardPool];
}
/**
* Get list of claim integration of the rewardPool for the SetToken.
*
* @param _setToken Address of SetToken
* @param _rewardPool Address of rewardPool
* @return Array of adapter addresses associated to the rewardPool for the SetToken
*/
function getRewardPoolClaims(ISetToken _setToken, address _rewardPool) external view returns (address[] memory) {
return claimSettings[_setToken][_rewardPool];
}
/**
* Get boolean indicating if the adapter address of the claim integration is associated to the rewardPool.
*
* @param _setToken Address of SetToken
* @param _rewardPool Address of rewardPool
* @param _integrationName ID of claim module integration (mapping on integration registry)
* @return Boolean indicating if the claim integration is associated to the rewardPool.
*/
function isRewardPoolClaim(
ISetToken _setToken,
address _rewardPool,
string calldata _integrationName
)
external
view
returns (bool)
{
address adapter = getAndValidateAdapter(_integrationName);
return claimSettingsStatus[_setToken][_rewardPool][adapter];
}
/**
* Get the rewards available to be claimed by the claim integration on the rewardPool.
*
* @param _setToken Address of SetToken
* @param _rewardPool Address of the rewardPool that identifies the contract governing claims
* @param _integrationName ID of claim module integration (mapping on integration registry)
* @return rewards Amount of units available to be claimed
*/
function getRewards(
ISetToken _setToken,
address _rewardPool,
string calldata _integrationName
)
external
view
returns (uint256)
{
IClaimAdapter adapter = _getAndValidateIntegrationAdapter(_setToken, _rewardPool, _integrationName);
return adapter.getRewardsAmount(_setToken, _rewardPool);
}
/* ============ Internal Functions ============ */
/**
* Claim the rewards, if available, on the rewardPool using the specified adapter. Interact with the adapter to get
* the rewards available, the calldata for the SetToken to invoke the claim and the token associated to the claim.
*
* @param _setToken Address of SetToken
* @param _rewardPool Address of the rewardPool that identifies the contract governing claims
* @param _integrationName Human readable name of claim integration
*/
function _claim(ISetToken _setToken, address _rewardPool, string calldata _integrationName) internal {
require(isRewardPool(_setToken, _rewardPool), "RewardPool not present");
IClaimAdapter adapter = _getAndValidateIntegrationAdapter(_setToken, _rewardPool, _integrationName);
IERC20 rewardsToken = IERC20(adapter.getTokenAddress(_rewardPool));
uint256 initRewardsBalance = rewardsToken.balanceOf(address(_setToken));
(
address callTarget,
uint256 callValue,
bytes memory callByteData
) = adapter.getClaimCallData(
_setToken,
_rewardPool
);
_setToken.invoke(callTarget, callValue, callByteData);
uint256 finalRewardsBalance = rewardsToken.balanceOf(address(_setToken));
emit RewardClaimed(_setToken, _rewardPool, adapter, finalRewardsBalance.sub(initRewardsBalance));
}
/**
* Gets the adapter and validate it is associated to the list of claim integration of a rewardPool.
*
* @param _setToken Address of SetToken
* @param _rewardsPool Sddress of rewards pool
* @param _integrationName ID of claim module integration (mapping on integration registry)
*/
function _getAndValidateIntegrationAdapter(
ISetToken _setToken,
address _rewardsPool,
string calldata _integrationName
)
internal
view
returns (IClaimAdapter)
{
address adapter = getAndValidateAdapter(_integrationName);
require(claimSettingsStatus[_setToken][_rewardsPool][adapter], "Adapter integration not present");
return IClaimAdapter(adapter);
}
/**
* Validates and store the adapter address used to claim rewards for the passed rewardPool. If after adding
* adapter to pool length of adapters is 1 then add to rewardPoolList as well.
*
* @param _setToken Address of SetToken
* @param _rewardPool Address of the rewardPool that identifies the contract governing claims
* @param _integrationName ID of claim module integration (mapping on integration registry)
*/
function _addClaim(ISetToken _setToken, address _rewardPool, string calldata _integrationName) internal {
address adapter = getAndValidateAdapter(_integrationName);
address[] storage _rewardPoolClaimSettings = claimSettings[_setToken][_rewardPool];
require(!claimSettingsStatus[_setToken][_rewardPool][adapter], "Integration names must be unique");
_rewardPoolClaimSettings.push(adapter);
claimSettingsStatus[_setToken][_rewardPool][adapter] = true;
if (!rewardPoolStatus[_setToken][_rewardPool]) {
rewardPoolList[_setToken].push(_rewardPool);
rewardPoolStatus[_setToken][_rewardPool] = true;
}
}
/**
* Internal version. Adds a new rewardPool to the list to perform claims for the SetToken indicating the list of claim
* integrations. Each claim integration is associated to an adapter that provides the functionality to claim the rewards
* for a specific token.
*
* @param _setToken Address of SetToken
* @param _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same
* index integrationNames
* @param _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index
* in rewardPools
*/
function _batchAddClaim(
ISetToken _setToken,
address[] calldata _rewardPools,
string[] calldata _integrationNames
)
internal
{
uint256 poolArrayLength = _validateBatchArrays(_rewardPools, _integrationNames);
for (uint256 i = 0; i < poolArrayLength; i++) {
_addClaim(_setToken, _rewardPools[i], _integrationNames[i]);
}
}
/**
* Validates and stores the adapter address used to claim rewards for the passed rewardPool. If no adapters
* left after removal then remove rewardPool from rewardPoolList and delete entry in claimSettings.
*
* @param _setToken Address of SetToken
* @param _rewardPool Address of the rewardPool that identifies the contract governing claims
* @param _integrationName ID of claim module integration (mapping on integration registry)
*/
function _removeClaim(ISetToken _setToken, address _rewardPool, string calldata _integrationName) internal {
address adapter = getAndValidateAdapter(_integrationName);
require(claimSettingsStatus[_setToken][_rewardPool][adapter], "Integration must be added");
claimSettings[_setToken][_rewardPool].removeStorage(adapter);
claimSettingsStatus[_setToken][_rewardPool][adapter] = false;
if (claimSettings[_setToken][_rewardPool].length == 0) {
rewardPoolList[_setToken].removeStorage(_rewardPool);
rewardPoolStatus[_setToken][_rewardPool] = false;
}
}
/**
* For batch functions validate arrays are of equal length and not empty. Return length of array for iteration.
*
* @param _rewardPools Addresses of the rewardPool that identifies the contract governing claims
* @param _integrationNames IDs of claim module integration (mapping on integration registry)
* @return Length of arrays
*/
function _validateBatchArrays(
address[] memory _rewardPools,
string[] calldata _integrationNames
)
internal
pure
returns(uint256)
{
uint256 poolArrayLength = _rewardPools.length;
require(poolArrayLength == _integrationNames.length, "Array length mismatch");
require(poolArrayLength > 0, "Arrays must not be empty");
return poolArrayLength;
}
/**
* If claim is confined to the manager, manager must be caller
*
* @param _setToken Address of SetToken
* @return bool Whether or not the caller is valid
*/
function _isValidCaller(ISetToken _setToken) internal view returns(bool) {
return anyoneClaim[_setToken] || isSetManager(_setToken, msg.sender);
}
}
|
SET MANAGER ONLY. Adds a new rewardPool to the list to perform claims for the SetToken indicating the list of claim integrations. Each claim integration is associated to an adapter that provides the functionality to claim the rewards for a specific token. _setToken Address of SetToken _rewardPools Addresses of rewardPools that identifies the contract governing claims. Maps to same index integrationNames _integrationNames Human-readable names matching adapter used to collect claim on pool. Maps to same index in rewardPools/
|
function batchAddClaim(
ISetToken _setToken,
address[] calldata _rewardPools,
string[] calldata _integrationNames
)
external
onlyManagerAndValidSet(_setToken)
{
_batchAddClaim(_setToken, _rewardPools, _integrationNames);
}
| 12,620,114 |
pragma solidity >=0.4.22 <0.7.0;
contract PowerBid {
enum Phase {
AUCTION,
CONSUMPTION,
FINISHED,
GAIN_WITHDRAWN,
PRICE_WITHDRAWN,
COMPLETED,
VIOLATED,
VIOLATION_RESOLVED}
// Parameters of the auction. Times are either
// absolute unix timestamps (seconds since 1970-01-01)
// or time periods in seconds.
address payable public consumer;
uint public auctionStartTime;
uint public consumptionStartTime; // t0
uint public consumptionEndTime; // t1
uint public requiredNRG; // in watts hour
uint public maxPrice; // max flat rate price for watts * hours (t1-t0) in the given period
// Current state of the auction.
address payable public bestSupplier;
uint public bestPrice;
Phase public state;
uint public auctionEndTime;
uint public consumptionTime;
// Events that will be emitted on changes.
event BestPriceUpdated(address bidder, uint amount);
event AuctionEnded(address winner, uint amount);
event Consumed(address consumer, address supplier, uint amount,uint price);
/// Create a power bidding auction with `_consumptionStartTime`
/// that represents the start time of the future consumption with `_consumptionEndTimeseconds`
/// as the end time. `_requiredEnergy` is the amount of energy required between `_consumptionEndTimeseconds` - `_consumptionStartTime`
/// on a flat rate
constructor(
uint auctionPeriodSeconds,
uint consumptionPeriodSeconds,
uint requiredEnergy
) public payable {
require(requiredEnergy > 0, "required energy must be greater than 0 wh");
require(msg.value > 0 ,"max price must be greater than 0");
require(auctionPeriodSeconds > 0, "auction period must be greater than 0");
require(consumptionPeriodSeconds > 0, "consumption period must be greater than 0");
consumer = msg.sender;
maxPrice = msg.value;
requiredNRG = requiredEnergy;
auctionStartTime = now;
consumptionStartTime = now + auctionPeriodSeconds;
consumptionEndTime = consumptionStartTime + consumptionPeriodSeconds;
state = Phase.AUCTION;
auctionEndTime = consumptionTime = 0;
}
/// Bid on the auction
function bid(uint _price) public {
// No arguments are necessary, all
// information is already part of
// the transaction. Function is not reciving Ether
// as the consumer pays
// Revert the call if the bidding
// period is over.
require(state == Phase.AUCTION, "Auction already ended.");
// Don't allow self bids
require(msg.sender != consumer);
// no free power
require(_price > 0);
// If the price is not better, send the
// money back.
require(
_price < bestPrice || (bestSupplier == address(0) && _price <= maxPrice),
"There already is a better price."
);
bestPrice = _price;
bestSupplier = msg.sender;
emit BestPriceUpdated(msg.sender, bestPrice);
}
function auctionEnd() public{
require(state == Phase.AUCTION);
if(msg.sender == consumer){
auctionEndTime = now;
state = auctionEndTime >= consumptionStartTime ? Phase.CONSUMPTION : Phase.VIOLATED;
}else if(now >= consumptionStartTime){
auctionEndTime = now;
state = Phase.CONSUMPTION;
}
}
function isValidWithdrawGain() private view returns(bool){
return state != Phase.GAIN_WITHDRAWN &&
state != Phase.COMPLETED &&
state != Phase.VIOLATED &&
state != Phase.VIOLATION_RESOLVED;
}
function isValidWithdraw() private view returns(bool){
return state != Phase.PRICE_WITHDRAWN &&
state != Phase.COMPLETED &&
state != Phase.VIOLATED &&
state != Phase.VIOLATION_RESOLVED;
}
function setEndTimes() private{
if(auctionEndTime == 0){
auctionEndTime = consumptionStartTime;
}
if(consumptionTime == 0){
consumptionTime = consumptionEndTime;
}
}
/// Withdraw the gain by the sender.
function withdrawGain() public returns (bool) {
require(msg.sender == consumer);
require(isValidWithdrawGain(), "gain can't be withdrawn");
if(now >= consumptionEndTime){
setEndTimes();
uint amount = maxPrice - bestPrice;
state = state == Phase.PRICE_WITHDRAWN || bestSupplier == address(0) ? Phase.COMPLETED : Phase.GAIN_WITHDRAWN;
msg.sender.transfer(amount);
return true;
}
return false;
}
// withdraw price of energy by the best supplier
function withdraw() public returns (bool) {
require(msg.sender == bestSupplier);
require(isValidWithdraw(), "price can't be withdrawn");
if(now >= consumptionEndTime){
setEndTimes();
uint amount = bestPrice;
state = state == Phase.GAIN_WITHDRAWN || (maxPrice - bestPrice) == 0 ? Phase.COMPLETED : Phase.PRICE_WITHDRAWN;
msg.sender.transfer(amount);
return true;
}
return false;
}
function auctionStatus() public view returns (uint,address,address,uint,uint){
return (consumptionStartTime,bestSupplier,consumer,bestPrice,consumptionEndTime);
}
function withdrawableAmount() public view returns (uint){
if(!isValidWithdraw()) return 0;
else return bestPrice;
}
function withdrawableGain() public view returns (uint){
if(!isValidWithdrawGain()) return 0;
else return maxPrice - bestPrice;
}
function consumePower() public
{
// It is a good guideline to structure functions that interact
// with other contracts (i.e. they call functions or send Ether)
// into three phases:
// 1. checking conditions
// 2. performing actions (potentially changing conditions)
// 3. interacting with other contracts
// If these phases are mixed up, the other contract could call
// back into the current contract and modify the state or cause
// effects (ether payout) to be performed multiple times.
// If functions called internally include interaction with external
// contracts, they also have to be considered interaction with
// external contracts.
//1. Conditions
require(state == Phase.CONSUMPTION || state == Phase.AUCTION, "Auction has not ended yet");
//2. Effects
if(consumer == msg.sender && now < consumptionStartTime){
auctionEndTime = now;
consumptionTime = now;
state = Phase.VIOLATED;
} else if(consumer == msg.sender && now >= consumptionStartTime){
state = Phase.FINISHED;
consumptionTime = now;
emit Consumed(msg.sender, bestSupplier,requiredNRG,bestPrice);
}else if(now >= consumptionEndTime) {
consumptionTime = consumptionEndTime;
state = Phase.FINISHED;
}
}
function resolveViolation() public {
require(state == Phase.VIOLATED);
if(bestSupplier != address(0)){
bestSupplier.transfer(bestPrice);
}
consumer.transfer(maxPrice-bestPrice);
state = Phase.VIOLATION_RESOLVED;
}
function destroy() public {
// Should be a 3rd party, trusted static account
// that will resolve the payments
require(msg.sender == consumer);
selfdestruct(consumer);
}
}
|
Withdraw the gain by the sender.
|
function withdrawGain() public returns (bool) {
require(msg.sender == consumer);
require(isValidWithdrawGain(), "gain can't be withdrawn");
if(now >= consumptionEndTime){
setEndTimes();
uint amount = maxPrice - bestPrice;
state = state == Phase.PRICE_WITHDRAWN || bestSupplier == address(0) ? Phase.COMPLETED : Phase.GAIN_WITHDRAWN;
msg.sender.transfer(amount);
return true;
}
return false;
}
| 14,038,231 |
// SPDX-License-Identifier: BSD-2-Clause
pragma solidity ^0.6.0;
import "./ENS.sol";
/**
* The ENS registry contract.
*/
contract ENSRegistry is ENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping (bytes32 => Record) records;
mapping (address => mapping(address => bool)) operators;
// Permits modifications only by the _owner of the specified _node.
modifier authorised(bytes32 _node) {
address _owner = records[_node].owner;
require(_owner == msg.sender || operators[_owner][msg.sender], "ENS: Not Authorized");
_;
}
/**
* @dev Constructs a new ENS registrar.
*/
constructor() public {
records[0x0].owner = msg.sender;
}
/**
* @dev Sets the record for a _node.
* @param _node The _node to update.
* @param _owner The address of the new _owner.
* @param _resolver The address of the _resolver.
* @param _ttl The TTL in seconds.
*/
function setRecord(bytes32 _node, address _owner, address _resolver, uint64 _ttl) external override {
setOwner(_node, _owner);
_setResolverAndTTL(_node, _resolver, _ttl);
}
/**
* @dev Sets the record for a subnode.
* @param _node The parent _node.
* @param _label The hash of the _label specifying the subnode.
* @param _owner The address of the new _owner.
* @param _resolver The address of the _resolver.
* @param _ttl The TTL in seconds.
*/
function setSubnodeRecord(bytes32 _node, bytes32 _label, address _owner, address _resolver, uint64 _ttl) external override {
bytes32 subnode = setSubnodeOwner(_node, _label, _owner);
_setResolverAndTTL(subnode, _resolver, _ttl);
}
/**
* @dev Transfers ownership of a _node to a new address. May only be called by the current _owner of the _node.
* @param _node The _node to transfer ownership of.
* @param _owner The address of the new _owner.
*/
function setOwner(bytes32 _node, address _owner) public override authorised(_node) {
_setOwner(_node, _owner);
emit Transfer(_node, _owner);
}
/**
* @dev Transfers ownership of a subnode keccak256(_node, _label) to a new address. May only be called by the _owner of the parent _node.
* @param _node The parent _node.
* @param _label The hash of the _label specifying the subnode.
* @param _owner The address of the new _owner.
*/
function setSubnodeOwner(bytes32 _node, bytes32 _label, address _owner) public override authorised(_node) returns(bytes32) {
bytes32 subnode = keccak256(abi.encodePacked(_node, _label));
_setOwner(subnode, _owner);
emit NewOwner(_node, _label, _owner);
return subnode;
}
/**
* @dev Sets the _resolver address for the specified _node.
* @param _node The _node to update.
* @param _resolver The address of the _resolver.
*/
function setResolver(bytes32 _node, address _resolver) public override authorised(_node) {
emit NewResolver(_node, _resolver);
records[_node].resolver = _resolver;
}
/**
* @dev Sets the TTL for the specified _node.
* @param _node The _node to update.
* @param _ttl The TTL in seconds.
*/
function setTTL(bytes32 _node, uint64 _ttl) public override authorised(_node) {
emit NewTTL(_node, _ttl);
records[_node].ttl = _ttl;
}
/**
* @dev Enable or disable approval for a third party ("_operator") to manage
* all of `msg.sender`'s ENS records. Emits the ApprovalForAll event.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the _operator is _approved, false to revoke approval.
*/
function setApprovalForAll(address _operator, bool _approved) external override {
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Returns the address that owns the specified _node.
* @param _node The specified _node.
* @return address of the _owner.
*/
function owner(bytes32 _node) public view override returns (address) {
address addr = records[_node].owner;
if (addr == address(this)) {
return address(0x0);
}
return addr;
}
/**
* @dev Returns the address of the _resolver for the specified _node.
* @param _node The specified _node.
* @return address of the _resolver.
*/
function resolver(bytes32 _node) public view override returns (address) {
return records[_node].resolver;
}
/**
* @dev Returns the TTL of a _node, and any records associated with it.
* @param _node The specified _node.
* @return _ttl of the _node.
*/
function ttl(bytes32 _node) public view override returns (uint64) {
return records[_node].ttl;
}
/**
* @dev Returns whether a record has been imported to the registry.
* @param _node The specified _node.
* @return Bool if record exists
*/
function recordExists(bytes32 _node) public view override returns (bool) {
return records[_node].owner != address(0x0);
}
/**
* @dev Query if an address is an authorized _operator for another address.
* @param _owner The address that owns the records.
* @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 override returns (bool) {
return operators[_owner][_operator];
}
function _setOwner(bytes32 _node, address _owner) internal {
records[_node].owner = _owner;
}
function _setResolverAndTTL(bytes32 _node, address _resolver, uint64 _ttl) internal {
if(_resolver != records[_node].resolver) {
records[_node].resolver = _resolver;
emit NewResolver(_node, _resolver);
}
if(_ttl != records[_node].ttl) {
records[_node].ttl = _ttl;
emit NewTTL(_node, _ttl);
}
}
}
|
Returns the address that owns the specified _node. _node The specified _node. return address of the _owner./
|
function owner(bytes32 _node) public view override returns (address) {
address addr = records[_node].owner;
if (addr == address(this)) {
return address(0x0);
}
return addr;
}
| 5,360,930 |
/*
Copyright 2018 The Hydro Protocol Foundation
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.4.23;
/**
* A relayer can register a delegate address.
* Delegates can send matching requests on behalf of relayers.
* The delegate scheme allows additional possibilities for smart contract interaction.
* on behalf of the relayer.
*/
contract LibRelayer {
/**
* Mapping of relayerAddress => delegateAddress
*/
mapping (address => mapping (address => bool)) public relayerDelegates;
event RelayerApproveDelegate(address indexed relayer, address indexed delegate);
event RelayerRevokeDelegate(address indexed relayer, address indexed delegate);
/**
* Approve an address to match orders on behalf of msg.sender
*/
function approveDelegate(address delegate) external {
relayerDelegates[msg.sender][delegate] = true;
emit RelayerApproveDelegate(msg.sender, delegate);
}
/**
* Revoke an existing delegate
*/
function revokeDelegate(address delegate) external {
relayerDelegates[msg.sender][delegate] = false;
emit RelayerRevokeDelegate(msg.sender, delegate);
}
/**
* @return true if msg.sender is allowed to match orders which belong to relayer
*/
function canMatchOrdersFrom(address relayer) public view returns(bool) {
return msg.sender == relayer || relayerDelegates[relayer][msg.sender] == true;
}
}
|
return true if msg.sender is allowed to match orders which belong to relayer/
|
function canMatchOrdersFrom(address relayer) public view returns(bool) {
return msg.sender == relayer || relayerDelegates[relayer][msg.sender] == true;
}
| 12,697,544 |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/AssetHelpers.sol";
import "./Moartroller.sol";
import "./SimplePriceOracle.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers {
/**
* @notice get the maximum asset value that can be still optimized.
* @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value'
* which is helpful to recalculate how much of this protection can be optimized again
*/
function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){
uint returnValue;
uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments);
uint totalProtectionLockedValue;
(totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments);
if(hypotheticalOptimizableValue <= totalProtectionLockedValue){
returnValue = 0;
}
else{
returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue);
}
return returnValue;
}
/**
* @notice get the maximum value of an asset that can be optimized by protection for the given user
* @dev optimizable = asset value * MPC
* @return the hypothetical optimizable value
* TODO: replace hardcoded 1e18 values
*/
function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) {
uint assetValue = div_(
mul_(
div_(
mul_(
arguments.asset.balanceOf(arguments.account),
arguments.asset.exchangeRateStored()
),
1e18
),
arguments.oracle.getUnderlyingPrice(arguments.asset)
),
getAssetDecimalsMantissa(arguments.asset.getUnderlying())
);
uint256 hypotheticalOptimizableValue = div_(
mul_(
assetValue,
arguments.asset.maxProtectionComposition()
),
arguments.asset.maxProtectionCompositionMantissa()
);
return hypotheticalOptimizableValue;
}
/**
* @dev gets all locked protections values with mark to market value. Used by Moartroller.
*/
function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) {
uint _lockedValue = 0;
uint _markToMarket = 0;
uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying());
for (uint j = 0; j < _protectionCount; j++) {
uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j);
bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId);
if(protectionIsAlive){
_lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId));
uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset);
uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId);
if( assetSpotPrice > protectionStrikePrice) {
_markToMarket = _markToMarket + div_(
mul_(
div_(
mul_(
assetSpotPrice - protectionStrikePrice,
arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId)
),
getAssetDecimalsMantissa(arguments.asset.underlying())
),
arguments.collateralFactorMantissa
),
1e18
);
}
}
}
return (_lockedValue , _markToMarket);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../MProtection.sol";
import "../Interfaces/PriceOracle.sol";
interface LiquidityMathModelInterface {
struct LiquidityMathArgumentsSet {
MToken asset;
address account;
uint collateralFactorMantissa;
MProtection cprotection;
PriceOracle oracle;
}
function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint);
function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint);
function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Utils/ErrorReporter.sol";
import "./Utils/Exponential.sol";
import "./Interfaces/EIP20Interface.sol";
import "./MTokenStorage.sol";
import "./Interfaces/MTokenInterface.sol";
import "./Interfaces/MProxyInterface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
/**
* @title MOAR's MToken Contract
* @notice Abstract base for MTokens
* @author MOAR
*/
abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage {
/**
* @notice Indicator that this is a MToken contract (for inspection)
*/
bool public constant isMToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address MTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when moartroller is changed
*/
event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/**
* @notice Max protection composition value updated event
*/
event MpcUpdated(uint newValue);
/**
* @notice Initialize the money market
* @param moartroller_ The address of the Moartroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function init(Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "not_admin");
require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "too_low");
// Set the moartroller
uint err = _setMoartroller(moartroller_);
require(err == uint(Error.NO_ERROR), "setting moartroller failed");
// Initialize block number and borrow index (block number mocks depend on moartroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting IRM failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
maxProtectionComposition = 5000;
maxProtectionCompositionMantissa = 1e4;
reserveFactorMaxMantissa = 1e18;
borrowRateMaxMantissa = 0.0005e16;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = moartroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srmTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srmTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srmTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// moartroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external virtual override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external virtual override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external virtual 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 virtual 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 virtual override view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external virtual override returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance_calculation_failed");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by moartroller 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 virtual override view returns (uint, uint, uint, uint) {
uint mTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), mTokenBalance, 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 mToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this mToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external virtual override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external virtual override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public virtual view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public virtual nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public virtual view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this mToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external virtual override view returns (uint) {
return getCashPrior();
}
function getRealBorrowIndex() public view returns (uint) {
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
Exp memory simpleInterestFactor;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor");
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex");
return borrowIndexNew;
}
/**
* @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 virtual returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
AccrueInterestTempStorage memory temp;
(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, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = temp.borrowIndexNew;
totalBorrows = temp.totalBorrowsNew;
totalReserves = temp.totalReservesNew;
if(temp.splitedReserves_2 > 0){
address mProxy = moartroller.mProxy();
EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2);
MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2);
}
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives mTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives mTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = moartroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the mToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of mTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/*
* We calculate the new total supply of mTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
// unused function
// moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems mTokens 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 mTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems mTokens 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 mTokens 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 mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/* Fail if user tries to redeem more than he has locked with c-op*/
// TODO: update error codes
uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18);
if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) {
require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing");
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(borrower, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = moartroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
//unused function
// moartroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
/* If the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */
if (repayAmount == uint(-1)) {
require(tx.origin == borrower, "specify a precise amount");
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// moartroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, MToken mTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = mTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, mTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, MToken mTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify mTokenCollateral market's block number equals current block number */
if (mTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower);
require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(mTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = mTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(mTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another mToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external virtual 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 MToken.
* Its absolutely critical to use msg.sender as the seizer mToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed mToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external virtual override returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external virtual override returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new moartroller for the market
* @dev Admin function to set a new moartroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK);
}
Moartroller oldMoartroller = moartroller;
// Ensure invoke moartroller.isMoartroller() returns true
require(newMoartroller.isMoartroller(), "not_moartroller");
// Set market's moartroller to newMoartroller
moartroller = newMoartroller;
// Emit NewMoartroller(oldMoartroller, newMoartroller)
emit NewMoartroller(oldMoartroller, newMoartroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external virtual override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
reserveSplitFactorMantissa = newReserveSplitFactorMantissa;
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external virtual override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(AbstractInterestRateModel newInterestRateModel) public virtual returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(AbstractInterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModelInterface oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "not_interest_model");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets new value for max protection composition parameter
* @param newMPC New value of MPC
* @return uint 0=success, otherwise a failure
*/
function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
maxProtectionComposition = newMPC;
emit MpcUpdated(newMPC);
return uint(Error.NO_ERROR);
}
/**
* @notice Returns address of underlying token
* @return address of underlying token
*/
function getUnderlying() external override view returns(address){
return underlying;
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal virtual view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal virtual returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal virtual;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
contract MoartrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
MOARTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SUPPORT_PROTECTION_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
MOARTROLLER_REJECTION,
MOARTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_MOARTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_MOARTROLLER_REJECTION,
LIQUIDATE_MOARTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_MOARTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_MOARTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_MOARTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_MOARTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_MOARTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_MOARTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract LiquidityMathModelErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
PRICE_ERROR,
SNAPSHOT_ERROR
}
enum FailureInfo {
ORACLE_PRICE_CHECK_FAILED
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Exponential module for storing fixed-precision decimals
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../Interfaces/EIP20Interface.sol";
contract AssetHelpers {
/**
* @dev return asset decimals mantissa. Returns 1e18 if ETH
*/
function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){
uint assetDecimals = 1e18;
if (assetAddress != address(0)) {
EIP20Interface token = EIP20Interface(assetAddress);
assetDecimals = 10 ** uint256(token.decimals());
}
return assetDecimals;
}
}
// SPDX-License-Identifier: BSD-3-Clause
// Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon.
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/MoartrollerInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Interfaces/MProxyInterface.sol";
import "./MoartrollerStorage.sol";
import "./Governance/UnionGovernanceToken.sol";
import "./MProtection.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./LiquidityMathModelV1.sol";
import "./Utils/SafeEIP20.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title MOAR's Moartroller Contract
* @author MOAR
*/
contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable {
using SafeEIP20 for EIP20Interface;
/// @notice Indicator that this is a Moartroller contract (for inspection)
bool public constant isMoartroller = true;
/// @notice Emitted when an admin supports a market
event MarketListed(MToken mToken);
/// @notice Emitted when an account enters a market
event MarketEntered(MToken mToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(MToken mToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when protection is changed
event NewCProtection(MProtection oldCProtection, MProtection newCProtection);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPausedMToken(MToken mToken, string action, bool pauseState);
/// @notice Emitted when a new MOAR speed is calculated for a market
event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed);
/// @notice Emitted when a new MOAR speed is set for a contributor
event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed);
/// @notice Emitted when MOAR is distributed to a supplier
event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex);
/// @notice Emitted when MOAR is distributed to a borrower
event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex);
/// @notice Emitted when borrow cap for a mToken is changed
event NewBorrowCap(MToken indexed mToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when MOAR is granted by admin
event MoarGranted(address recipient, uint amount);
event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel);
event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel);
/// @notice The initial MOAR index for a market
uint224 public constant moarInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// Custom initializer
function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer {
admin = msg.sender;
liquidityMathModel = mathModel;
liquidationModel = lqdModel;
rewardClaimEnabled = false;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (MToken[] memory) {
MToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param mToken The mToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, MToken mToken) external view returns (bool) {
return markets[address(mToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param mTokens The list of addresses of the mToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) {
uint len = mTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
MToken mToken = MToken(mTokens[i]);
results[i] = uint(addToMarketInternal(mToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param mToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(mToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(mToken);
emit MarketEntered(mToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param mTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address mTokenAddress) external override returns (uint) {
MToken mToken = MToken(mTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the mToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(mToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set mToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete mToken from the account’s list of assets */
// load into memory for faster iteration
MToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == mToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
MToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(mToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param mToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[mToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param mToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of mTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) {
uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[mToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param mToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {
// Shh - currently unused
mToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param mToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[mToken], "borrow is paused");
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[mToken].accountMembership[borrower]) {
// only mTokens may call borrowAllowed if borrower not in market
require(msg.sender == mToken, "sender must be mToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(MToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[mToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[mToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = MToken(mToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param mToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) {
return uint(Error.MOARTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mTokenCollateral);
distributeSupplierMoar(mTokenCollateral, borrower);
distributeSupplierMoar(mTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param mToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of mTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(mToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, src);
distributeSupplierMoar(mToken, dst);
return uint(Error.NO_ERROR);
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address mTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
MToken mTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
MToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
MToken asset = assets[i];
address _account = account;
// Read the balances and exchange rate from the mToken
(oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals()));
// Pre-compute a conversion factor from tokens -> dai (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * mTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral);
// Protection value calculation sumCollateral += protectionValueLocked
// Mark to market value calculation sumCollateral += markToMarketValue
uint protectionValueLocked;
uint markToMarketValue;
(protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle));
if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) {
vars.sumCollateral = 0;
} else {
vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor));
}
vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked);
vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with mTokenModify
if (asset == mTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
_account = account;
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Returns the value of possible optimization left for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The value of possible optimization
*/
function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getMaxOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
/**
* @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of hypothetical optimization
*/
function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getHypotheticalOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) {
return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens(
LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet(
oracle,
this,
mTokenBorrowed,
mTokenCollateral,
actualRepayAmount,
account,
liquidationIncentiveMantissa
)
);
}
/**
* @notice Returns the amount of a specific asset that is locked under all c-ops
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of asset locked under c-ops
*/
function getUserLockedAmount(MToken asset, address account) public override view returns(uint) {
uint protectionLockedAmount;
address currency = asset.underlying();
uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency);
for (uint i = 0; i < numOfProtections; i++) {
uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i);
if(cprotection.isProtectionAlive(cProtectionId)){
protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId);
}
}
return protectionLockedAmount;
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the moartroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the moartroller
PriceOracle oldOracle = oracle;
// Set moartroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new CProtection that is allowed to use as a collateral optimisation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setProtection(address newCProtection) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
MProtection oldCProtection = cprotection;
cprotection = MProtection(newCProtection);
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewCProtection(oldCProtection, cprotection);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param mToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(mToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
// TODO: this check is temporary switched off. we can make exception for UNN later
// Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
//
//
// Check collateral factor <= 0.9
// Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
// if (lessThanExp(highLimit, newCollateralFactorExp)) {
// return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
// }
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
function _setRewardClaimEnabled(bool status) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
rewardClaimEnabled = status;
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param mToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(MToken mToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(mToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
mToken.isMToken(); // Sanity check to make sure its really a MToken
// Note that isMoared is not in active use anymore
markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0});
tokenAddressToMToken[address(mToken.underlying())] = mToken;
_addMarketInternal(address(mToken));
emit MarketListed(mToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address mToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != MToken(mToken), "market already added");
}
allMarkets.push(MToken(mToken));
}
/**
* @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param mTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = mTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(mTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(mTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Mint", state);
return state;
}
function _setBorrowPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == moartrollerImplementation;
}
/*** MOAR Distribution ***/
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal {
uint currentMoarSpeed = moarSpeeds[address(mToken)];
if (currentMoarSpeed != 0) {
// note that MOAR speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarSupplyIndex(address(mToken));
updateMoarBorrowIndex(address(mToken), borrowIndex);
} else if (moarSpeed != 0) {
// Add the MOAR market
Market storage market = markets[address(mToken)];
require(market.isListed == true, "MOAR market is not listed");
if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) {
moarSupplyState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) {
moarBorrowState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
if (currentMoarSpeed != moarSpeed) {
moarSpeeds[address(mToken)] = moarSpeed;
emit MoarSpeedUpdated(mToken, moarSpeed);
}
}
/**
* @notice Accrue MOAR to the market by updating the supply index
* @param mToken The market whose supply index to update
*/
function updateMoarSupplyIndex(address mToken) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
uint supplySpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = MToken(mToken).totalSupply();
uint moarAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
moarSupplyState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue MOAR to the market by updating the borrow index
* @param mToken The market whose borrow index to update
*/
function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
uint borrowSpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex);
uint moarAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
moarBorrowState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate MOAR accrued by a supplier and possibly transfer it to them
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute MOAR to
*/
function distributeSupplierMoar(address mToken, address supplier) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]});
moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = moarInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = MToken(mToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta);
moarAccrued[supplier] = supplierAccrued;
emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate MOAR accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOAR to
*/
function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]});
moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta);
moarAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Calculate additional accrued MOAR for a contributor since last accrual
* @param contributor The address to calculate contributor rewards for
*/
function updateContributorRewards(address contributor) public {
uint moarSpeed = moarContributorSpeeds[contributor];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]);
if (deltaBlocks > 0 && moarSpeed > 0) {
uint newAccrued = mul_(deltaBlocks, moarSpeed);
uint contributorAccrued = add_(moarAccrued[contributor], newAccrued);
moarAccrued[contributor] = contributorAccrued;
lastContributorBlock[contributor] = blockNumber;
}
}
/**
* @notice Claim all the MOAR accrued by holder in all markets
* @param holder The address to claim MOAR for
*/
function claimMoarReward(address holder) public {
return claimMoar(holder, allMarkets);
}
/**
* @notice Claim all the MOAR accrued by holder in the specified markets
* @param holder The address to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
*/
function claimMoar(address holder, MToken[] memory mTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimMoar(holders, mTokens, true, true);
}
/**
* @notice Claim all MOAR accrued by the holders
* @param holders The addresses to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
* @param borrowers Whether or not to claim MOAR earned by borrowing
* @param suppliers Whether or not to claim MOAR earned by supplying
*/
function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public {
require(rewardClaimEnabled, "reward claim is disabled");
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
require(markets[address(mToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarBorrowIndex(address(mToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerMoar(address(mToken), holders[j], borrowIndex);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
if (suppliers == true) {
updateMoarSupplyIndex(address(mToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierMoar(address(mToken), holders[j]);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
}
}
/**
* @notice Transfer MOAR to the user
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param user The address of the user to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
* @return The amount of MOAR which was NOT transferred to the user
*/
function grantMoarInternal(address user, uint amount) internal returns (uint) {
EIP20Interface moar = EIP20Interface(getMoarAddress());
uint moarRemaining = moar.balanceOf(address(this));
if (amount > 0 && amount <= moarRemaining) {
moar.approve(mProxy, amount);
MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount);
return 0;
}
return amount;
}
/*** MOAR Distribution Admin ***/
/**
* @notice Transfer MOAR to the recipient
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
*/
function _grantMoar(address recipient, uint amount) public {
require(adminOrInitializing(), "only admin can grant MOAR");
uint amountLeft = grantMoarInternal(recipient, amount);
require(amountLeft == 0, "insufficient MOAR for grant");
emit MoarGranted(recipient, amount);
}
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function _setMoarSpeed(MToken mToken, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
setMoarSpeedInternal(mToken, moarSpeed);
}
/**
* @notice Set MOAR speed for a single contributor
* @param contributor The contributor whose MOAR speed to update
* @param moarSpeed New MOAR speed for contributor
*/
function _setContributorMoarSpeed(address contributor, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
// note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor
updateContributorRewards(contributor);
if (moarSpeed == 0) {
// release storage
delete lastContributorBlock[contributor];
} else {
lastContributorBlock[contributor] = getBlockNumber();
}
moarContributorSpeeds[contributor] = moarSpeed;
emit ContributorMoarSpeedUpdated(contributor, moarSpeed);
}
/**
* @notice Set liquidity math model implementation
* @param mathModel the math model implementation
*/
function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel;
liquidityMathModel = mathModel;
emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel));
}
/**
* @notice Set liquidation model implementation
* @param newLiquidationModel the liquidation model implementation
*/
function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public {
require(msg.sender == admin, "only admin can set liquidation model implementation");
LiquidationModelInterface oldLiquidationModel = liquidationModel;
liquidationModel = newLiquidationModel;
emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel));
}
function _setMoarToken(address moarTokenAddress) public {
require(msg.sender == admin, "only admin can set MOAR token address");
moarToken = moarTokenAddress;
}
function _setMProxy(address mProxyAddress) public {
require(msg.sender == admin, "only admin can set MProxy address");
mProxy = mProxyAddress;
}
/**
* @notice Add new privileged address
* @param privilegedAddress address to add
*/
function _addPrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
privilegedAddresses[privilegedAddress] = 1;
}
/**
* @notice Remove privileged address
* @param privilegedAddress address to remove
*/
function _removePrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
delete privilegedAddresses[privilegedAddress];
}
/**
* @notice Check if address if privileged
* @param privilegedAddress address to check
*/
function isPrivilegedAddress(address privilegedAddress) public view returns (bool) {
return privilegedAddresses[privilegedAddress] == 1;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (MToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the MOAR token
* @return The address of MOAR
*/
function getMoarAddress() public view returns (address) {
return moarToken;
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/PriceOracle.sol";
import "./CErc20.sol";
/**
* Temporary simple price feed
*/
contract SimplePriceOracle is PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
mapping(address => uint) prices;
event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
function getUnderlyingPrice(MToken mToken) public override view returns (uint) {
if (compareStrings(mToken.symbol(), "mDAI")) {
return 1e18;
} else {
return prices[address(MErc20(address(mToken)).underlying())];
}
}
function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public {
address asset = address(MErc20(address(mToken)).underlying());
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
prices[asset] = underlyingPriceMantissa;
}
function setDirectPrice(address asset, uint price) public {
emit PricePosted(asset, prices[asset], price, price);
prices[asset] = price;
}
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) {
return prices[asset];
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./Interfaces/CopMappingInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Moartroller.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/AssetHelpers.sol";
import "./MToken.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MProtection Contract
* @notice Collateral optimization ERC-721 wrapper
* @author MOAR
*/
contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable {
using Counters for Counters.Counter;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @notice Event emitted when new MProtection token is minted
*/
event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime);
/**
* @notice Event emitted when MProtection token is redeemed
*/
event Redeem(address redeemer, uint tokenId, uint underlyingTokenId);
/**
* @notice Event emitted when MProtection token changes its locked value
*/
event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue);
/**
* @notice Event emitted when maturity window parameter is changed
*/
event MaturityWindowUpdated(uint newMaturityWindow);
Counters.Counter private _tokenIds;
address private _copMappingAddress;
address private _moartrollerAddress;
mapping (uint256 => uint256) private _underlyingProtectionTokensMapping;
mapping (uint256 => uint256) private _underlyingProtectionLockedValue;
mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping;
uint256 public _maturityWindow;
struct ProtectionMappedData{
address pool;
address underlyingAsset;
uint256 amount;
uint256 strike;
uint256 premium;
uint256 lockedValue;
uint256 totalValue;
uint issueTime;
uint expirationTime;
bool isProtectionAlive;
}
/**
* @notice Constructor for MProtection contract
* @param copMappingAddress The address of data mapper for C-OP
* @param moartrollerAddress The address of the Moartroller
*/
function initialize(address copMappingAddress, address moartrollerAddress) public initializer {
__Ownable_init();
__ERC721_init("c-uUNN OC-Protection", "c-uUNN");
_copMappingAddress = copMappingAddress;
_moartrollerAddress = moartrollerAddress;
_setMaturityWindow(10800); // 3 hours default
}
/**
* @notice Returns C-OP mapping contract
*/
function copMapping() private view returns (CopMappingInterface){
return CopMappingInterface(_copMappingAddress);
}
/**
* @notice Mint new MProtection token
* @param underlyingTokenId Id of C-OP token that will be deposited
* @return ID of minted MProtection token
*/
function mint(uint256 underlyingTokenId) public returns (uint256)
{
return mintFor(underlyingTokenId, msg.sender);
}
/**
* @notice Mint new MProtection token for specified address
* @param underlyingTokenId Id of C-OP token that will be deposited
* @param receiver Address that will receive minted Mprotection token
* @return ID of minted MProtection token
*/
function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256)
{
CopMappingInterface copMappingInstance = copMapping();
ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId);
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(receiver, newItemId);
addUProtectionIndexes(receiver, newItemId, underlyingTokenId);
emit Mint(
receiver,
newItemId,
underlyingTokenId,
copMappingInstance.getUnderlyingAsset(underlyingTokenId),
copMappingInstance.getUnderlyingAmount(underlyingTokenId),
copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId),
copMappingInstance.getUnderlyingDeadline(underlyingTokenId)
);
return newItemId;
}
/**
* @notice Redeem C-OP token
* @param tokenId Id of MProtection token that will be withdrawn
* @return ID of redeemed C-OP token
*/
function redeem(uint256 tokenId) external returns (uint256) {
require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved");
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId);
removeProtectionIndexes(tokenId);
_burn(tokenId);
emit Redeem(msg.sender, tokenId, underlyingTokenId);
return underlyingTokenId;
}
/**
* @notice Returns set of C-OP data
* @param tokenId Id of MProtection token
* @return ProtectionMappedData struct filled with C-OP data
*/
function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){
ProtectionMappedData memory data;
(address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId);
data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId));
return data;
}
/**
* @notice Returns underlying token ID
* @param tokenId Id of MProtection token
*/
function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){
return _underlyingProtectionTokensMapping[tokenId];
}
/**
* @notice Returns size of C-OPs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].length();
}
/**
* @notice Returns list of C-OP IDs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].at(index);
}
/**
* @notice Checks if address is owner of MProtection
* @param owner Address of potential owner to check
* @param tokenId ID of MProtection to check
*/
function isUserProtection(address owner, uint256 tokenId) public view returns(bool) {
if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){
return true;
}
return owner == ownerOf(tokenId);
}
/**
* @notice Checks if MProtection is stil alive
* @param tokenId ID of MProtection to check
*/
function isProtectionAlive(uint256 tokenId) public view returns(bool) {
uint256 deadline = getUnderlyingDeadline(tokenId);
return (deadline - _maturityWindow) > now;
}
/**
* @notice Creates appropriate indexes for C-OP
* @param owner C-OP owner address
* @param tokenId ID of MProtection
* @param underlyingTokenId ID of C-OP
*/
function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{
address currency = copMapping().getUnderlyingAsset(underlyingTokenId);
_underlyingProtectionTokensMapping[tokenId] = underlyingTokenId;
_protectionCurrencyMapping[owner][currency].add(tokenId);
}
/**
* @notice Remove indexes for C-OP
* @param tokenId ID of MProtection
*/
function removeProtectionIndexes(uint256 tokenId) private{
address owner = ownerOf(tokenId);
address currency = getUnderlyingAsset(tokenId);
_underlyingProtectionTokensMapping[tokenId] = 0;
_protectionCurrencyMapping[owner][currency].remove(tokenId);
}
/**
* @notice Returns C-OP total value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
return div_(
mul_(
getUnderlyingStrikePrice(tokenId),
getUnderlyingAmount(tokenId)
),
assetDecimalsMantissa
);
}
/**
* @notice Returns C-OP locked value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){
return _underlyingProtectionLockedValue[tokenId];
}
/**
* @notice get the amount of underlying asset that is locked
* @param tokenId CProtection tokenId
* @return amount locked
*/
function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
// calculates total protection value
uint256 protectionValue = div_(
mul_(
getUnderlyingAmount(tokenId),
getUnderlyingStrikePrice(tokenId)
),
assetDecimalsMantissa
);
// return value is lockedValue / totalValue * amount
return div_(
mul_(
getUnderlyingAmount(tokenId),
div_(
mul_(
_underlyingProtectionLockedValue[tokenId],
1e18
),
protectionValue
)
),
1e18
);
}
/**
* @notice Locks the given protection value as collateral optimization
* @param tokenId The MProtection token id
* @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization
* @return locked protection value
* TODO: convert semantic errors to standarized error codes
*/
function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) {
//check if the protection belongs to the caller
require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION");
address currency = getUnderlyingAsset(tokenId);
Moartroller moartroller = Moartroller(_moartrollerAddress);
MToken mToken = moartroller.tokenAddressToMToken(currency);
require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE");
uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId);
uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId));
// add protection locked value if any
uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId);
if ( protectionLockedValue > 0) {
maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue);
}
uint valueToLock;
if (value != 0) {
// check if lock value is at most max optimizable value
require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE");
// check if lock value is at most protection total value
require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE");
valueToLock = value;
} else {
// if we want to lock maximum protection value let's lock the value that is at most max optimizable value
if (protectionTotalValue > maxOptimizableValue) {
valueToLock = maxOptimizableValue;
} else {
valueToLock = protectionTotalValue;
}
}
_underlyingProtectionLockedValue[tokenId] = valueToLock;
emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock);
return valueToLock;
}
function _setCopMapping(address newMapping) public onlyOwner {
_copMappingAddress = newMapping;
}
function _setMoartroller(address newMoartroller) public onlyOwner {
_moartrollerAddress = newMoartroller;
}
function _setMaturityWindow(uint256 maturityWindow) public onlyOwner {
emit MaturityWindowUpdated(maturityWindow);
_maturityWindow = maturityWindow;
}
// MAPPINGS
function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getProtectionData(underlyingTokenId);
}
function getUnderlyingAsset(uint256 tokenId) public view returns (address){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAsset(underlyingTokenId);
}
function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAmount(underlyingTokenId);
}
function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingStrikePrice(underlyingTokenId);
}
function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingDeadline(underlyingTokenId);
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface PriceOracle {
/**
* @notice Get the underlying price of a mToken asset
* @param mToken The mToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(MToken mToken) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @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 success Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool);
/**
* @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 success Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
/**
* @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 success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @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 remaining The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
abstract contract MTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @dev EIP-20 token name for this token
*/
string public name;
/**
* @dev EIP-20 token symbol for this token
*/
string public symbol;
/**
* @dev EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Underlying asset for this MToken
*/
address public underlying;
/**
* @dev Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal borrowRateMaxMantissa;
/**
* @dev Maximum fraction of interest that can be set aside for reserves
*/
uint internal reserveFactorMaxMantissa;
/**
* @dev Administrator for this contract
*/
address payable public admin;
/**
* @dev Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @dev Contract which oversees inter-mToken operations
*/
Moartroller public moartroller;
/**
* @dev Model which tells what the current interest rate should be
*/
AbstractInterestRateModel public interestRateModel;
/**
* @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @dev Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @dev Fraction of reserves currently set aside for other usage
*/
uint public reserveSplitFactorMantissa;
/**
* @dev Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @dev Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @dev Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @dev Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @dev Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000
*/
uint public maxProtectionComposition;
/**
* @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5
*/
uint public maxProtectionCompositionMantissa;
/**
* @dev Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @dev Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
struct ProtectionUsage {
uint256 protectionValueUsed;
}
/**
* @dev Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
mapping (uint256 => ProtectionUsage) protectionsUsed;
}
struct AccrueInterestTempStorage{
uint interestAccumulated;
uint reservesAdded;
uint splitedReserves_1;
uint splitedReserves_2;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
}
/**
* @dev Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) public accountBorrows;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./EIP20Interface.sol";
interface MTokenInterface {
/*** User contract ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function getCash() external view returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
function getUnderlying() external view returns(address);
function sweepToken(EIP20Interface token) external;
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface MProxyInterface {
function proxyClaimReward(address asset, address recipient, uint amount) external;
function proxySplitReserves(address asset, uint amount) external;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/InterestRateModelInterface.sol";
abstract contract AbstractInterestRateModel is InterestRateModelInterface {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Careful Math
* @author MOAR
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../Utils/ExponentialNoError.sol";
interface MoartrollerInterface {
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `mTokenBalance` is the number of mTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint mTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
ExponentialNoError.Exp collateralFactor;
ExponentialNoError.Exp exchangeRate;
ExponentialNoError.Exp oraclePrice;
ExponentialNoError.Exp tokensToDenom;
}
/*** Assets You Are In ***/
function enterMarkets(address[] calldata mTokens) external returns (uint[] memory);
function exitMarket(address mToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint);
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint);
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint);
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeUserTokens(
address mTokenBorrowed,
address mTokenCollateral,
uint repayAmount,
address account) external view returns (uint, uint);
function getUserLockedAmount(MToken asset, address account) external view returns(uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface Versionable {
function getContractVersion() external pure returns (string memory);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "./MProtection.sol";
abstract contract UnitrollerAdminStorage {
/**
* @dev Administrator for this contract
*/
address public admin;
/**
* @dev Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @dev Active brains of Unitroller
*/
address public moartrollerImplementation;
/**
* @dev Pending brains of Unitroller
*/
address public pendingMoartrollerImplementation;
}
contract MoartrollerV1Storage is UnitrollerAdminStorage {
/**
* @dev Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @dev Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @dev Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @dev Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => MToken[]) public accountAssets;
}
contract MoartrollerV2Storage is MoartrollerV1Storage {
struct Market {
// Whether or not this market is listed
bool isListed;
// Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value.
// Must be between 0 and 1, and stored as a mantissa.
uint collateralFactorMantissa;
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
// Whether or not this market receives MOAR
bool isMoared;
}
/**
* @dev Official mapping of mTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @dev The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract MoartrollerV3Storage is MoartrollerV2Storage {
struct MoarMarketState {
// The market's last updated moarBorrowIndex or moarSupplyIndex
uint224 index;
// The block number the index was last updated at
uint32 block;
}
/// @dev A list of all markets
MToken[] public allMarkets;
/// @dev The rate at which the flywheel distributes MOAR, per block
uint public moarRate;
/// @dev The portion of moarRate that each market currently receives
mapping(address => uint) public moarSpeeds;
/// @dev The MOAR market supply state for each market
mapping(address => MoarMarketState) public moarSupplyState;
/// @dev The MOAR market borrow state for each market
mapping(address => MoarMarketState) public moarBorrowState;
/// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarSupplierIndex;
/// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarBorrowerIndex;
/// @dev The MOAR accrued but not yet transferred to each user
mapping(address => uint) public moarAccrued;
}
contract MoartrollerV4Storage is MoartrollerV3Storage {
// @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
}
contract MoartrollerV5Storage is MoartrollerV4Storage {
/// @dev The portion of MOAR that each contributor receives per block
mapping(address => uint) public moarContributorSpeeds;
/// @dev Last block at which a contributor's MOAR rewards have been allocated
mapping(address => uint) public lastContributorBlock;
}
contract MoartrollerV6Storage is MoartrollerV5Storage {
/**
* @dev Moar token address
*/
address public moarToken;
/**
* @dev MProxy address
*/
address public mProxy;
/**
* @dev CProtection contract which can be used for collateral optimisation
*/
MProtection public cprotection;
/**
* @dev Mapping for basic token address to mToken
*/
mapping(address => MToken) public tokenAddressToMToken;
/**
* @dev Math model for liquidity calculation
*/
LiquidityMathModelInterface public liquidityMathModel;
/**
* @dev Liquidation model for liquidation related functions
*/
LiquidationModelInterface public liquidationModel;
/**
* @dev List of addresses with privileged access
*/
mapping(address => uint) public privilegedAddresses;
/**
* @dev Determines if reward claim feature is enabled
*/
bool public rewardClaimEnabled;
}
// Copyright (c) 2020 The UNION Protocol Foundation
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/**
* @title UNION Protocol Governance Token
* @dev Implementation of the basic standard token.
*/
contract UnionGovernanceToken is AccessControl, IERC20 {
using Address for address;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @notice Struct for marking number of votes from a given block
* @member from
* @member votes
*/
struct VotingCheckpoint {
uint256 from;
uint256 votes;
}
/**
* @notice Struct for locked tokens
* @member amount
* @member releaseTime
* @member votable
*/
struct LockedTokens{
uint amount;
uint releaseTime;
bool votable;
}
/**
* @notice Struct for EIP712 Domain
* @member name
* @member version
* @member chainId
* @member verifyingContract
* @member salt
*/
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
bytes32 salt;
}
/**
* @notice Struct for EIP712 VotingDelegate call
* @member owner
* @member delegate
* @member nonce
* @member expirationTime
*/
struct VotingDelegate {
address owner;
address delegate;
uint256 nonce;
uint256 expirationTime;
}
/**
* @notice Struct for EIP712 Permit call
* @member owner
* @member spender
* @member value
* @member nonce
* @member deadline
*/
struct Permit {
address owner;
address spender;
uint256 value;
uint256 nonce;
uint256 deadline;
}
/**
* @notice Vote Delegation Events
*/
event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate);
event VotingDelegateRemoved(address indexed _owner);
/**
* @notice Vote Balance Events
* Emmitted when a delegate account's vote balance changes at the time of a written checkpoint
*/
event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance);
/**
* @notice Transfer/Allocator Events
*/
event TransferStatusChanged(bool _newTransferStatus);
/**
* @notice Reversion Events
*/
event ReversionStatusChanged(bool _newReversionSetting);
/**
* @notice EIP-20 Approval event
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @notice EIP-20 Transfer event
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Burn(address indexed _from, uint256 _value);
event AddressPermitted(address indexed _account);
event AddressRestricted(address indexed _account);
/**
* @dev AccessControl recognized roles
*/
bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE");
bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN");
bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT");
bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK");
bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED");
bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST");
bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
);
bytes32 public constant DELEGATE_TYPEHASH = keccak256(
"DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)"
);
//keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
address private constant BURN_ADDRESS = address(0);
address public UPGT_CONTRACT_ADDRESS;
/**
* @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting.
*/
bytes32 public immutable EIP712DOMAIN_SEPARATOR;
/**
* @dev EIP-20 token name
*/
string public name = "UNION Protocol Governance Token";
/**
* @dev EIP-20 token symbol
*/
string public symbol = "UNN";
/**
* @dev EIP-20 token decimals
*/
uint8 public decimals = 18;
/**
* @dev Contract version
*/
string public constant version = '0.0.1';
/**
* @dev Initial amount of tokens
*/
uint256 private uint256_initialSupply = 100000000000 * 10**18;
/**
* @dev Total amount of tokens
*/
uint256 private uint256_totalSupply;
/**
* @dev Chain id
*/
uint256 private uint256_chain_id;
/**
* @dev general transfer restricted as function of public sale not complete
*/
bool private b_canTransfer = false;
/**
* @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions.
*/
bool private b_revert = false; //false allows false return values
/**
* @dev Locked destinations list
*/
mapping(address => bool) private m_lockedDestinations;
/**
* @dev EIP-20 allowance and balance maps
*/
mapping(address => mapping(address => uint256)) private m_allowances;
mapping(address => uint256) private m_balances;
mapping(address => LockedTokens[]) private m_lockedBalances;
/**
* @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712
*/
mapping(address => uint256) private m_nonces;
/**
* @dev delegated account may for off-line vote delegation
*/
mapping(address => address) private m_delegatedAccounts;
/**
* @dev delegated account inverse map is needed to live calculate voting power
*/
mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap;
/**
* @dev indexed mapping of vote checkpoints for each account
*/
mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints;
/**
* @dev mapping of account addrresses to voting checkpoints
*/
mapping(address => uint256) private m_accountVotingCheckpoints;
/**
* @dev Contructor for the token
* @param _owner address of token contract owner
* @param _initialSupply of tokens generated by this contract
* Sets Transfer the total suppply to the owner.
* Sets default admin role to the owner.
* Sets ROLE_ALLOCATE to the owner.
* Sets ROLE_GOVERN to the owner.
* Sets ROLE_MINT to the owner.
* Sets EIP 712 Domain Separator.
*/
constructor(address _owner, uint256 _initialSupply) public {
//set internal contract references
UPGT_CONTRACT_ADDRESS = address(this);
//setup roles using AccessControl
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(ROLE_ADMIN, _owner);
_setupRole(ROLE_ADMIN, _msgSender());
_setupRole(ROLE_ALLOCATE, _owner);
_setupRole(ROLE_ALLOCATE, _msgSender());
_setupRole(ROLE_TRUSTED, _owner);
_setupRole(ROLE_TRUSTED, _msgSender());
_setupRole(ROLE_GOVERN, _owner);
_setupRole(ROLE_MINT, _owner);
_setupRole(ROLE_LOCK, _owner);
_setupRole(ROLE_TEST, _owner);
m_balances[_owner] = _initialSupply;
uint256_totalSupply = _initialSupply;
b_canTransfer = false;
uint256_chain_id = _getChainId();
EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({
name : name,
version : version,
chainId : uint256_chain_id,
verifyingContract : address(this),
salt : keccak256(abi.encodePacked(name))
}
));
emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply);
}
/**
* @dev Sets transfer status to lock token transfer
* @param _canTransfer value can be true or false.
* disables transfer when set to false and enables transfer when true
* Only a member of ADMIN role can call to change transfer status
*/
function setCanTransfer(bool _canTransfer) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
b_canTransfer = _canTransfer;
emit TransferStatusChanged(_canTransfer);
}
}
/**
* @dev Gets status of token transfer lock
* @return true or false status of whether the token can be transfered
*/
function getCanTransfer() public view returns (bool) {
return b_canTransfer;
}
/**
* @dev Sets transfer reversion status to either return false or throw on error
* @param _reversion value can be true or false.
* disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true
* Only a member of ADMIN role can call to change transfer reversion status
*/
function setReversion(bool _reversion) public {
if(hasRole(ROLE_ADMIN, _msgSender()) ||
hasRole(ROLE_TEST, _msgSender())
) {
b_revert = _reversion;
emit ReversionStatusChanged(_reversion);
}
}
/**
* @dev Gets status of token transfer reversion
* @return true or false status of whether the token transfer failures return false or are reverted
*/
function getReversion() public view returns (bool) {
return b_revert;
}
/**
* @dev retrieve current chain id
* @return chain id
*/
function getChainId() public pure returns (uint256) {
return _getChainId();
}
/**
* @dev Retrieve current chain id
* @return chain id
*/
function _getChainId() internal pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* @dev Retrieve total supply of tokens
* @return uint256 total supply of tokens
*/
function totalSupply() public view override returns (uint256) {
return uint256_totalSupply;
}
/**
* Balance related functions
*/
/**
* @dev Retrieve balance of a specified account
* @param _account address of account holding balance
* @return uint256 balance of the specified account address
*/
function balanceOf(address _account) public view override returns (uint256) {
return m_balances[_account].add(_calculateReleasedBalance(_account));
}
/**
* @dev Retrieve locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function lockedBalanceOf(address _account) public view returns (uint256) {
return _calculateLockedBalance(_account);
}
/**
* @dev Retrieve lenght of locked balance array for specific address
* @param _account address of account holding locked balance
* @return uint256 locked balance array lenght
*/
function getLockedTokensListSize(address _account) public view returns (uint256){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
return m_lockedBalances[_account].length;
}
/**
* @dev Retrieve locked tokens struct from locked balance array for specific address
* @param _account address of account holding locked tokens
* @param _index index in array with locked tokens position
* @return amount of locked tokens
* @return releaseTime descibes time when tokens will be unlocked
* @return votable flag is describing votability of tokens
*/
function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index");
LockedTokens storage lockedTokens = m_lockedBalances[_account][_index];
return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable);
}
/**
* @dev Calculates locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function _calculateLockedBalance(address _account) private view returns (uint256) {
uint256 lockedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime > block.timestamp){
lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedBalance;
}
/**
* @dev Calculates released balance of a specified account
* @param _account address of account holding released balance
* @return uint256 released balance of the specified account address
*/
function _calculateReleasedBalance(address _account) private view returns (uint256) {
uint256 releasedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return releasedBalance;
}
/**
* @dev Calculates locked votable balance of a specified account
* @param _account address of account holding locked votable balance
* @return uint256 locked votable balance of the specified account address
*/
function _calculateLockedVotableBalance(address _account) private view returns (uint256) {
uint256 lockedVotableBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].votable == true){
lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedVotableBalance;
}
/**
* @dev Moves released balance to normal balance for a specified account
* @param _account address of account holding released balance
*/
function _moveReleasedBalance(address _account) internal virtual{
uint256 releasedToMove = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount);
m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1];
m_lockedBalances[_account].pop();
}
}
m_balances[_account] = m_balances[_account].add(releasedToMove);
}
/**
* Allowance related functinons
*/
/**
* @dev Retrieve the spending allowance for a token holder by a specified account
* @param _owner Token account holder
* @param _spender Account given allowance
* @return uint256 allowance value
*/
function allowance(address _owner, address _spender) public override virtual view returns (uint256) {
return m_allowances[_owner][_spender];
}
/**
* @dev Message sender approval to spend for a specified amount
* @param _spender address of party approved to spend
* @param _value amount of the approval
* @return boolean success status
* public wrapper for _approve, _owner is msg.sender
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
bool success = _approveUNN(_msgSender(), _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: APPROVE ERROR");
}
return success;
}
/**
* @dev Token owner approval of amount for specified spender
* @param _owner address of party that owns the tokens being granted approval for spending
* @param _spender address of party that is granted approval for spending
* @param _value amount approved for spending
* @return boolean approval status
* if _spender allownace for a given _owner is greater than 0,
* increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738
*/
function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(m_allowances[_owner][_spender] == 0 || _value == 0)
){
m_allowances[_owner][_spender] = _value;
emit Approval(_owner, _spender, _value);
retval = true;
}
return retval;
}
/**
* @dev Increase spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _addedValue specified incremental increase
* @return boolean increaseAllowance status
* public wrapper for _increaseAllowance, _owner restricted to msg.sender
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue);
if(!success && b_revert){
revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to increase spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _addedValue specified incremental increase
* @return boolean return value status
* increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address.
*/
function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_addedValue > 0
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* @dev Decrease spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _subtractedValue specified incremental decrease
* @return boolean success status
* public wrapper for _decreaseAllowance, _owner restricted to msg.sender
*/
//public wrapper for _decreaseAllowance, _owner restricted to msg.sender
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue);
if(!success && b_revert){
revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to decrease spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _subtractedValue specified incremental decrease
* @return boolean return value status
* decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address.
*/
function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_subtractedValue > 0 &&
m_allowances[_owner][_spender] >= _subtractedValue
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* LockedDestination related functions
*/
/**
* @dev Adds address as a designated destination for tokens when locked for allocation only
* @param _address Address of approved desitnation for movement during lock
* @return success in setting address as eligible for transfer independent of token lock status
*/
function setAsEligibleLockedDestination(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
m_lockedDestinations[_address] = true;
retVal = true;
}
return retVal;
}
/**
* @dev removes desitnation as eligible for transfer
* @param _address address being removed
*/
function removeEligibleLockedDestination(address _address) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
delete(m_lockedDestinations[_address]);
}
}
/**
* @dev checks whether a destination is eligible as recipient of transfer independent of token lock status
* @param _address address being checked
* @return whether desitnation is locked
*/
function checkEligibleLockedDesination(address _address) public view returns (bool) {
return m_lockedDestinations[_address];
}
/**
* @dev Adds address as a designated allocator that can move tokens when they are locked
* @param _address Address receiving the role of ROLE_ALLOCATE
* @return success as true or false
*/
function setAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
grantRole(ROLE_ALLOCATE, _address);
retVal = true;
}
return retVal;
}
/**
* @dev Removes address as a designated allocator that can move tokens when they are locked
* @param _address Address being removed from the ROLE_ALLOCATE
* @return success as true or false
*/
function removeAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
if(hasRole(ROLE_ALLOCATE, _address)){
revokeRole(ROLE_ALLOCATE, _address);
retVal = true;
}
}
return retVal;
}
/**
* @dev Checks to see if an address has the role of being an allocator
* @param _address Address being checked for ROLE_ALLOCATE
* @return true or false whether the address has ROLE_ALLOCATE assigned
*/
function checkAsAllocator(address _address) public view returns (bool) {
return hasRole(ROLE_ALLOCATE, _address);
}
/**
* Transfer related functions
*/
/**
* @dev Public wrapper for transfer function to move tokens of specified value to a given address
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @return status of transfer success
*/
function transfer(address _to, uint256 _value) external override returns (bool) {
bool success = _transferUNN(_msgSender(), _to, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER");
}
return success;
}
/**
* @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required.
* @param _owner The address owner where transfer originates
* @param _to The address to transfer to
* @param _value The amount to be transferred
* @return status of transfer success
*/
function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_to] = m_balances[_to].add(_value);
retval = true;
//need to move voting delegates with transfer of tokens
retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value to a given address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
retval = true;
//need to move voting delegates with transfer of tokens
// retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFrom function
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) {
bool success = _transferFromUNN(_owner, _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM");
}
return success;
}
/**
* @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) {
if(
_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_spender] = m_balances[_spender].add(_value);
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
retval = retval && _moveVotingDelegates(_owner, _spender, _value);
emit Transfer(_owner, _spender, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
// retval = retval && _moveVotingDelegates(_owner, _to, _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public function to burn tokens
* @param _value number of tokens to be burned
* @return whether tokens were burned
* Only ROLE_MINTER may burn tokens
*/
function burn(uint256 _value) external returns (bool) {
bool success = _burn(_value);
if(!success && b_revert){
revert("UPGT_ERROR: FAILED TO BURN");
}
return success;
}
/**
* @dev Private function Burn tokens
* @param _value number of tokens to be burned
* @return bool whether the tokens were burned
* only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet.
*/
function _burn(uint256 _value) internal returns (bool) {
bool retval = false;
if(hasRole(ROLE_MINT, _msgSender()) &&
(m_balances[_msgSender()] >= _value)
){
m_balances[_msgSender()] -= _value;
uint256_totalSupply = uint256_totalSupply.sub(_value);
retval = true;
emit Burn(_msgSender(), _value);
}
return retval;
}
/**
* Voting related functions
*/
/**
* @dev Public wrapper for _calculateVotingPower function which calulates voting power
* @dev voting power = balance + locked votable balance + delegations
* @return uint256 voting power
*/
function calculateVotingPower() public view returns (uint256) {
return _calculateVotingPower(_msgSender());
}
/**
* @dev Calulates voting power of specified address
* @param _account address of token holder
* @return uint256 voting power
*/
function _calculateVotingPower(address _account) private view returns (uint256) {
uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account));
for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) {
if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){
address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i);
votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount));
}
}
return votingPower;
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
* Requires ROLE_TEST
*/
function moveVotingDelegates(
address _source,
address _destination,
uint256 _amount) public returns (bool) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _moveVotingDelegates(_source, _destination, _amount);
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
*/
function _moveVotingDelegates(
address _source,
address _destination,
uint256 _amount
) internal returns (bool) {
if(_source != _destination && _amount > 0) {
if(_source != BURN_ADDRESS) {
uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source];
uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0;
if(sourceNumberOfVotingCheckpointsOriginal >= _amount) {
uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount);
_writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew);
}
}
if(_destination != BURN_ADDRESS) {
uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination];
uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0;
uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount);
_writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew);
}
}
return true;
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Public function for writing voting checkpoint
* Requires ROLE_TEST
*/
function writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) public {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
_writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes);
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Private function for writing voting checkpoint
*/
function _writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) internal {
if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes;
}
else {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes);
_numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1);
}
emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes);
}
/**
* @dev Calculate account votes as of a specific block
* @param _account address whose votes are counted
* @param _blockNumber from which votes are being counted
* @return number of votes counted
*/
function getVoteCountAtBlock(
address _account,
uint256 _blockNumber) public view returns (uint256) {
uint256 voteCount = 0;
if(_blockNumber < block.number) {
if(m_accountVotingCheckpoints[_account] != 0) {
if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) {
voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes;
}
else if(m_votingCheckpoints[_account][0].from > _blockNumber) {
voteCount = 0;
}
else {
uint256 lower = 0;
uint256 upper = m_accountVotingCheckpoints[_account].sub(1);
while(upper > lower) {
uint256 center = upper.sub((upper.sub(lower).div(2)));
VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center];
if(votingCheckpoint.from == _blockNumber) {
voteCount = votingCheckpoint.votes;
break;
}
else if(votingCheckpoint.from < _blockNumber) {
lower = center;
}
else {
upper = center.sub(1);
}
}
}
}
}
return voteCount;
}
/**
* @dev Vote Delegation Functions
* @param _to address where message sender is assigning votes
* @return success of message sender delegating vote
* delegate function does not allow assignment to burn
*/
function delegateVote(address _to) public returns (bool) {
return _delegateVote(_msgSender(), _to);
}
/**
* @dev Delegate votes from token holder to another address
* @param _from Token holder
* @param _toDelegate Address that will be delegated to for purpose of voting
* @return success as to whether delegation has been a success
*/
function _delegateVote(
address _from,
address _toDelegate) internal returns (bool) {
bool retval = false;
if(_toDelegate != BURN_ADDRESS) {
address currentDelegate = m_delegatedAccounts[_from];
uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from));
address oldToDelegate = m_delegatedAccounts[_from];
m_delegatedAccounts[_from] = _toDelegate;
m_delegatedAccountsInverseMap[oldToDelegate].remove(_from);
if(_from != _toDelegate){
m_delegatedAccountsInverseMap[_toDelegate].add(_from);
}
retval = true;
retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance);
if(retval) {
if(_from == _toDelegate){
emit VotingDelegateRemoved(_from);
}
else{
emit VotingDelegateChanged(_from, currentDelegate, _toDelegate);
}
}
}
return retval;
}
/**
* @dev Revert voting delegate control to owner account
* @param _account The account that has delegated its vote
* @return success of reverting delegation to owner
*/
function _revertVotingDelegationToOwner(address _account) internal returns (bool) {
return _delegateVote(_account, _account);
}
/**
* @dev Used by an message sending account to recall its voting delegates
* @return success of reverting delegation to owner
*/
function recallVotingDelegate() public returns (bool) {
return _revertVotingDelegationToOwner(_msgSender());
}
/**
* @dev Retrieve the voting delegate for a specified account
* @param _account The account that has delegated its vote
*/
function getVotingDelegate(address _account) public view returns (address) {
return m_delegatedAccounts[_account];
}
/**
* EIP-712 related functions
*/
/**
* @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit
* @param _owner address of token owner
* @param _spender address of designated spender
* @param _value value permitted for spend
* @param _deadline expiration of signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline))
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _approveUNN(_owner, _spender, _value);
}
/**
* @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote
* @param _owner address of token owner
* @param _delegate address of voting delegate
* @param _expiretimestamp expiration of delegation signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @ @return bool true or false depedening on whether vote was successfully delegated
*/
function delegateVoteBySignature(
address _owner,
address _delegate,
uint256 _expiretimestamp,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
_hash(VotingDelegate(
{
owner : _owner,
delegate : _delegate,
nonce : m_nonces[_owner]++,
expirationTime : _expiretimestamp
})
)
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _delegateVote(_owner, _delegate);
}
/**
* @dev Public hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
* Requires ROLE_TEST
*/
function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_eip712Domain);
}
/**
* @dev Hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
* Requires ROLE_TEST
*/
function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_delegate);
}
/**
* @dev Public hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
* Requires ROLE_TEST
*/
function hashPermit(Permit memory _permit) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_permit);
}
/**
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
* Requires ROLE_TEST
*/
function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _recoverSigner(_digest, _ecv, _ecr, _ecs);
}
/**
* @dev Private hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
*/
function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) {
return keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(_eip712Domain.name)),
keccak256(bytes(_eip712Domain.version)),
_eip712Domain.chainId,
_eip712Domain.verifyingContract,
_eip712Domain.salt
)
);
}
/**
* @dev Private hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
*/
function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) {
return keccak256(
abi.encode(
DELEGATE_TYPEHASH,
_delegate.owner,
_delegate.delegate,
_delegate.nonce,
_delegate.expirationTime
)
);
}
/**
* @dev Private hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
*/
function _hash(Permit memory _permit) internal pure returns (bytes32) {
return keccak256(abi.encode(
PERMIT_TYPEHASH,
_permit.owner,
_permit.spender,
_permit.value,
_permit.nonce,
_permit.deadline
));
}
/**
* @dev Recover signer information from provided digest
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
*/
function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if(_ecv != 27 && _ecv != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(_digest, _ecv, _ecr, _ecs);
require(signer != BURN_ADDRESS, "ECDSA: invalid signature");
return signer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../Interfaces/EIP20Interface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title SafeEIP20
* @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.
* This is a forked version of Openzeppelin's SafeERC20 contract but supporting
* EIP20Interface instead of Openzeppelin's IERC20
* 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 SafeEIP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(EIP20Interface token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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 experimental ABIEncoderV2;
import "./PriceOracle.sol";
import "./MoartrollerInterface.sol";
pragma solidity ^0.6.12;
interface LiquidationModelInterface {
function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
struct LiquidateCalculateSeizeUserTokensArgumentsSet {
PriceOracle oracle;
MoartrollerInterface moartroller;
address mTokenBorrowed;
address mTokenCollateral;
uint actualRepayAmount;
address accountForLiquidation;
uint liquidationIncentiveMantissa;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title MOAR's InterestRateModel Interface
* @author MOAR
*/
interface InterestRateModelInterface {
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/EnumerableSetUpgradeable.sol";
import "../../utils/EnumerableMapUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
// 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* 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
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* 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;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
// 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 virtual 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 virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual 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 virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721Upgradeable.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 _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.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 = ERC721Upgradeable.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[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(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal 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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
uint256[41] private __gap;
}
// 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: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface CopMappingInterface {
function getTokenAddress() external view returns (address);
function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint);
function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address);
function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256);
function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint);
function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* 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;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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 EnumerableMapUpgradeable {
// 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 Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
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(uint160(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(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(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(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @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--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// 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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// 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.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/MErc20Interface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MErc20 Contract
* @notice MTokens which wrap an EIP-20 underlying
*/
contract MErc20 is MToken, MErc20Interface {
using SafeEIP20 for EIP20Interface;
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param moartroller_ The address of the Moartroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function init(address underlying_,
Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// MToken initialize does the bulk of the work
super.init(moartroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives mTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external override returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external override returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems mTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external override returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external override returns (uint) {
return borrowInternal(borrowAmount);
}
function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) {
return borrowForInternal(borrower, borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external override returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower.
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external override returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral);
return err;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20Interface token) override external {
require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(admin, balance);
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external override returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal override view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*`
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal override returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
uint balanceBefore = token.balanceOf(address(this));
token.safeTransferFrom(from, address(this), amount);
// Calculate the amount that was *actually* transferred
uint balanceAfter = token.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal override {
EIP20Interface token = EIP20Interface(underlying);
token.safeTransfer(to, amount);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface MErc20Interface {
/*** User contract ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function borrowFor(address payable borrower, uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
|
Locks the given protection value as collateral optimization tokenId The MProtection token id value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization return locked protection value TODO: convert semantic errors to standarized error codes/check if the protection belongs to the caller add protection locked value if any check if lock value is at most max optimizable value check if lock value is at most protection total value if we want to lock maximum protection value let's lock the value that is at most max optimizable value
|
function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) {
require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION");
address currency = getUnderlyingAsset(tokenId);
Moartroller moartroller = Moartroller(_moartrollerAddress);
MToken mToken = moartroller.tokenAddressToMToken(currency);
require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE");
uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId);
uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId));
uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId);
if ( protectionLockedValue > 0) {
maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue);
}
uint valueToLock;
if (value != 0) {
require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE");
require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE");
valueToLock = value;
if (protectionTotalValue > maxOptimizableValue) {
valueToLock = maxOptimizableValue;
valueToLock = protectionTotalValue;
}
}
_underlyingProtectionLockedValue[tokenId] = valueToLock;
emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock);
return valueToLock;
}
| 11,818,372 |
./partial_match/1/0x8f74c989252B94Fd2d08a668884D303D57c91422/sources/contracts/OutputReceiverProxy.sol
|
Called to claim interest on a given FNFT fnftId the FNFT which is being updated can only be called by someone who owns the FNFT they pass in/
|
function receiveSecondaryCallback(
uint fnftId,
address payable owner,
uint quantity,
IRevest.FNFTConfig memory config,
bytes memory args
function triggerOutputReceiverUpdate(
uint fnftId,
bytes memory
) external override {
require(FNFT_HANDLER.getBalance(msg.sender, fnftId) > 0, 'ER010');
IResonate(resonate).claimInterest(fnftId, msg.sender);
}
| 9,204,952 |
pragma solidity ^0.4.11;
contract boleno {
string public constant name = "Boleno"; // Token name
string public constant symbol = "BLN"; // Boleno token symbol
uint8 public constant decimals = 18; // Number of decimals
uint256 public totalSupply = 10**25; // The initial supply (10 million) in base unit
address public supplier; // Boleno supplier address
uint public blnpereth = 50; // Price of 1 Ether in Bolenos by the supplier
uint public bounty = 15; // Percentage of bounty program. Initiates with 15%
bool public sale = false; // Is there an ongoing sale?
bool public referral = false; // Is the referral program enabled?
// Events
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
mapping (address => uint256) public balances; // Balances
mapping(address => mapping (address => uint256)) allowed;// Record of allowances
// Initialization
function boleno() {
supplier = msg.sender; // Supplier is contract creator
balances[supplier] = totalSupply; // The initial supply goes to supplier
}
// For functions that require only supplier usage
modifier onlySupplier {
if (msg.sender != supplier) throw;
_;
}
// Token transfer
function transfer(address _to, uint256 _value) returns (bool success) {
if (now < 1502755200 && msg.sender != supplier) throw;// Cannot trade until Tuesday, August 15, 2017 12:00:00 AM (End of ICO)
if (balances[msg.sender] < _value) throw; // Does the spender have enough Bolenos to send?
if (balances[_to] + _value < balances[_to]) throw; // Overflow?
balances[msg.sender] -= _value; // Subtract the Bolenos from the sender's balance
balances[_to] += _value; // Add the Bolenos to the recipient's balance
Transfer(msg.sender, _to, _value); // Send Bolenos transfer event
return true; // Return true to client
}
// Token transfer on your behalf (i.e. by contracts)
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (now < 1502755200 && _from != supplier) throw; // Cannot trade until Tuesday, August 15, 2017 12:00:00 AM (End of ICO)
if (balances[_from] < _value) throw; // Does the spender have enough Bolenos to send?
if(allowed[_from][msg.sender] < _value) throw; // Is the sender allowed to spend as much money on behalf of the spender?
if (balances[_to] + _value < balances[_to]) throw; // Overflow?
balances[_from] -= _value; // Subtract the Bolenos from the sender's balance
allowed[_from][msg.sender] -= _value; // Update allowances record
balances[_to] += _value; // Add the Bolenos to the recipient's balance
Transfer(_from, _to, _value); // Send Bolenos transfer event
return true; // Return true to client
}
// Allows someone (i.e a contract) to spend on your behalf multiple times up to a certain value.
// If this function is called again, it overwrites the current allowance with _value.
// Approve 0 to cancel previous approval
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value; // Update allowances record
Approval(msg.sender, _spender, _value); // Send approval event
return true; // Return true to client
}
// Check how much someone approved you to spend on their behalf
function allowance(address _owner, address _spender) returns (uint256 bolenos) {
return allowed[_owner][_spender]; // Check the allowances record
}
// What is the Boleno balance of a particular person?
function balanceOf(address _owner) returns (uint256 bolenos){
return balances[_owner];
}
/*
Crowdsale related functions
*/
// Referral bounty system
function referral(address referrer) payable {
if(sale != true) throw; // Is there an ongoing sale?
if(referral != true) throw; // Is referral bounty allowed by supplier?
if(balances[referrer] < 100**18) throw; // Make sure referrer already has at least 100 Bolenos
uint256 bolenos = msg.value * blnpereth; // Determine amount of equivalent Bolenos to the Ethers received
/*
First give Bolenos to the purchaser
*/
uint256 purchaserBounty = (bolenos / 100) * (100 + bounty);// Add bounty to the purchased amount
if(balances[supplier] < purchaserBounty) throw; // Does the supplier have enough BLN tokens to sell?
if (balances[msg.sender] + purchaserBounty < balances[msg.sender]) throw; // Overflow?
balances[supplier] -= purchaserBounty; // Subtract the Bolenos from the supplier's balance
balances[msg.sender] += purchaserBounty; // Add the Bolenos to the buyer's balance
Transfer(supplier, msg.sender, purchaserBounty); // Send Bolenos transfer event
/*
Then give Bolenos to the referrer
*/
uint256 referrerBounty = (bolenos / 100) * bounty; // Only the bounty percentage is added to the referrer
if(balances[supplier] < referrerBounty) throw; // Does the supplier have enough BLN tokens to sell?
if (balances[referrer] + referrerBounty < balances[referrer]) throw; // Overflow?
balances[supplier] -= referrerBounty; // Subtract the Bolenos from the supplier's balance
balances[referrer] += referrerBounty; // Add the Bolenos to the buyer's balance
Transfer(supplier, referrer, referrerBounty); // Send Bolenos transfer event
}
// Set the number of BLNs sold per ETH (only by the supplier).
function setbounty(uint256 newBounty) onlySupplier {
bounty = newBounty;
}
// Set the number of BLNs sold per ETH (only by the supplier).
function setblnpereth(uint256 newRate) onlySupplier {
blnpereth = newRate;
}
// Trigger Sale (only by the supplier)
function triggerSale(bool newSale) onlySupplier {
sale = newSale;
}
// Transfer both supplier status and all held Boleno tokens supply to a different address (only supplier)
function transferSupply(address newSupplier) onlySupplier {
if (balances[newSupplier] + balances[supplier] < balances[newSupplier]) throw;// Overflow?
uint256 supplyValue = balances[supplier]; // Determine current value of the supply
balances[newSupplier] += supplyValue; // Add supply to new supplier
balances[supplier] -= supplyValue; // Substract supply from old supplier
Transfer(supplier, newSupplier, supplyValue); // Send Bolenos transfer event
supplier = newSupplier; // Transfer supplier status
}
// Claim sale Ethers. Can be executed by anyone.
function claimSale(){
address dao = 0xE6237a036366b8003AeD725E8001BD91890be03F;// Hardcoded address of the Bolenum private DAO
dao.transfer(this.balance); // Send all collected Ethers to the address
}
// Fallback function. Used for buying Bolenos from supplier by simply sending Ethers to contract
function () payable {
if(sale != true) throw; // Is there an ongoing sale?
uint256 bolenos = msg.value * blnpereth; // Determine amount of equivalent Bolenos to the Ethers received
if(balances[supplier] < bolenos) throw; // Does the supplier have enough BLN tokens to sell?
if (balances[msg.sender] + bolenos < balances[msg.sender]) throw; // Overflow?
balances[supplier] -= bolenos; // Subtract the Bolenos the supplier's balance
balances[msg.sender] += bolenos; // Add the Bolenos to the buyer's balance
Transfer(supplier, msg.sender, bolenos); // Send Bolenos transfer event
}
}
|
What is the Boleno balance of a particular person?
|
function balanceOf(address _owner) returns (uint256 bolenos){
return balances[_owner];
}
| 12,918,085 |
./partial_match/1/0xc6CadA314389430d396C7b0C70c6281e99ca7fe8/sources/src/contracts/FraxlendPair.sol
|
The ```setBorrowLimit``` function sets the borrow limit _limit The new borrow limit
|
function setBorrowLimit(uint256 _limit) external {
_requireTimelockOrOwner();
if (isBorrowAccessControlRevoked) revert AccessControlRevoked();
_setBorrowLimit(_limit);
}
| 2,823,037 |
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract SmtVesting is Ownable {
using SafeMath for uint256;
/// @dev ERC20 basic token contract being held
IERC20 public token;
/// @dev Block number where the contract is deployed
uint256 public immutable initialBlock;
uint256 private constant ONE = 10**18;
uint256 private constant DAY = 5760; // 24*60*60/15
uint256 private constant WEEK = 40320; // 7*24*60*60/15
uint256 private constant YEAR = 2102400; // 365*24*60*60/15
uint256 private constant WEEKS_IN_YEAR = 52;
uint256 private constant INITAL_ANUAL_DIST = 62500000 * ONE;
uint256 private constant WEEK_BATCH_DIV = 45890222137623526749; //(0.995^0 + 0.995^1 ... + 0.995^51) = 45,894396603
/// @dev First year comunity batch has been claimed
bool public firstYCBClaimed;
/// @dev Block number where last claim was executed
uint256 public lastClaimedBlock;
/// @dev Emitted when `owner` claims.
event Claim(address indexed owner, uint256 amount);
/**
* @dev Sets the value for {initialBloc}.
*
* Sets ownership to the given `_owner`.
*
*/
constructor() {
initialBlock = block.number;
lastClaimedBlock = block.number;
}
/**
* @dev Sets the value for `token`.
*
* Requirements:
*
* - the caller must be the owner.
* - `_token` can't be zero address
* - `token` should not be already set
*
*/
function setToken(address _token) external onlyOwner {
require(_token != address(0), "token is the zero address");
require(address(token) == address(0), "token is already set");
token = IERC20(_token);
}
/**
* @dev Claims next token batch.
*
* Requirements:
*
* - the caller must be the owner.
*
*/
function claim() external onlyOwner {
uint256 amount = claimableAmount();
lastClaimedBlock = block.number;
firstYCBClaimed = true;
emit Claim(owner(), amount);
token.transfer(_msgSender(), amount);
}
/**
* @dev Gets the next token batch to be claimed since the last claim until current block.
*
*/
function claimableAmount() public view returns (uint256) {
return _claimableAmount(firstYCBClaimed, block.number, lastClaimedBlock);
}
/**
* @dev Gets the next token batch to be claimed since the last claim until current block.
*
*/
function _claimableAmount(
bool isFirstYCBClaimed,
uint256 blockNumber,
uint256 lCBlock
) internal view returns (uint256) {
uint256 total = 0;
uint256 lastClaimedBlockYear = blockYear(lCBlock);
uint256 currentYear = blockYear(blockNumber);
total += accumulateAnualComBatch(isFirstYCBClaimed, blockNumber, lCBlock);
if (lastClaimedBlockYear < currentYear) {
total += accumulateFromPastYears(blockNumber, lCBlock);
} else {
total += accumulateCurrentYear(blockNumber, lCBlock);
}
return total;
}
/**
* @dev Accumulates non claimed Anual Comunity Batches.
*
*/
function accumulateAnualComBatch(
bool isFirstYCBClaimed,
uint256 blockNumber,
uint256 lCBlock
) public view returns (uint256) {
uint256 acc = 0;
uint256 currentYear = blockYear(blockNumber);
uint256 lastClaimedBlockYear = blockYear(lCBlock);
if (!isFirstYCBClaimed || lastClaimedBlockYear < currentYear) {
uint256 from = isFirstYCBClaimed ? lastClaimedBlockYear + 1 : 0;
for (uint256 y = from; y <= currentYear; y++) {
acc += yearAnualCommunityBatch(y);
}
}
return acc;
}
/**
* @dev Accumulates non claimed Weekly Release Batches from a week in a previous year.
*
*/
function accumulateFromPastYears(uint256 blockNumber, uint256 lCBlock) public view returns (uint256) {
uint256 acc = 0;
uint256 lastClaimedBlockYear = blockYear(lCBlock);
uint256 lastClaimedBlockWeek = blockWeek(lCBlock);
uint256 currentYear = blockYear(blockNumber);
uint256 currentWeek = blockWeek(blockNumber);
// add what remains to claim from the claimed week
acc += getWeekPortionFromBlock(lCBlock);
{
uint256 ww;
uint256 yy;
for (ww = lastClaimedBlockWeek + 1; ww < WEEKS_IN_YEAR; ww++) {
acc += yearWeekRelaseBatch(lastClaimedBlockYear, ww);
}
// add complete weeks years until current year
for (yy = lastClaimedBlockYear + 1; yy < currentYear; yy++) {
for (ww = 0; ww < WEEKS_IN_YEAR; ww++) {
acc += yearWeekRelaseBatch(yy, ww);
}
}
// current year until current week
for (ww = 0; ww < currentWeek; ww++) {
acc += yearWeekRelaseBatch(currentYear, ww);
}
}
// portion of current week
acc += getWeekPortionUntilBlock(blockNumber);
return acc;
}
/**
* @dev Accumulates non claimed Weekly Release Batches from a week in the current year.
*
*/
function accumulateCurrentYear(uint256 blockNumber, uint256 lCBlock) public view returns (uint256) {
uint256 acc = 0;
uint256 lastClaimedBlockWeek = blockWeek(lCBlock);
uint256 currentYear = blockYear(blockNumber);
uint256 currentWeek = blockWeek(blockNumber);
if (lastClaimedBlockWeek < currentWeek) {
// add what remains to claim from the claimed week
acc += getWeekPortionFromBlock(lCBlock);
{
uint256 ww;
// add remaining weeks until current
for (ww = lastClaimedBlockWeek + 1; ww < currentWeek; ww++) {
acc += yearWeekRelaseBatch(currentYear, ww);
}
}
}
// portion of current week
acc += getWeekPortionUntilBlock(blockNumber);
return acc;
}
// Utility Functions
/**
* @dev Calculates the portion of Weekly Release Batch from a block to the end of that block's week.
*
*/
function getWeekPortionFromBlock(uint256 blockNumber) internal view returns (uint256) {
uint256 blockNumberYear = blockYear(blockNumber);
uint256 blockNumberWeek = blockWeek(blockNumber);
uint256 blockNumberWeekBatch = yearWeekRelaseBatch(blockNumberYear, blockNumberWeek);
uint256 weekLastBlock = yearWeekLastBlock(blockNumberYear, blockNumberWeek);
return blockNumberWeekBatch.mul(weekLastBlock.sub(blockNumber)).div(WEEK);
}
/**
* @dev Calculates the portion of Weekly Release Batch from the start of a block's week the block.
*
*/
function getWeekPortionUntilBlock(uint256 blockNumber) internal view returns (uint256) {
uint256 blockNumberYear = blockYear(blockNumber);
uint256 blockNumberWeek = blockWeek(blockNumber);
uint256 blockNumberWeekBatch = yearWeekRelaseBatch(blockNumberYear, blockNumberWeek);
uint256 weekFirsBlock = yearWeekFirstBlock(blockNumberYear, blockNumberWeek);
return blockNumberWeekBatch.mul(blockNumber.sub(weekFirsBlock)).div(WEEK);
}
/**
* @dev Calculates the Total Anual Distribution for a given year.
*
* TAD = (62500000) * (1 - 0.25)^y
*
* @param year Year zero based.
*/
function yearAnualDistribution(uint256 year) public pure returns (uint256) {
// 25% of year reduction => (1-0.25) = 0.75 = 3/4
uint256 reductionN = 3**year;
uint256 reductionD = 4**year;
return INITAL_ANUAL_DIST.mul(reductionN).div(reductionD);
}
/**
* @dev Calculates the Anual Comunity Batch for a given year.
*
* 20% * yearAnualDistribution
*
* @param year Year zero based.
*/
function yearAnualCommunityBatch(uint256 year) public pure returns (uint256) {
uint256 totalAnnualDistribution = yearAnualDistribution(year);
return totalAnnualDistribution.mul(200).div(1000);
}
/**
* @dev Calculates the Anual Weekly Batch for a given year.
*
* 80% * yearAnualDistribution
*
* @param year Year zero based.
*/
function yearAnualWeeklyBatch(uint256 year) public pure returns (uint256) {
uint256 yearAC = yearAnualCommunityBatch(year);
return yearAnualDistribution(year).sub(yearAC);
}
/**
* @dev Calculates weekly reduction percentage for a given week.
*
* WRP = (1 - 0.5)^w
*
* @param week Week zero based.
*/
function weeklyRedPerc(uint256 week) internal pure returns (uint256) {
uint256 reductionPerc = ONE;
uint256 nineNineFive = ONE - 5000000000000000; // 1 - 0.5
for (uint256 i = 0; i < week; i++) {
reductionPerc = nineNineFive.mul(reductionPerc).div(ONE);
}
return reductionPerc;
}
/**
* @dev Calculates W1 weekly release batch amount for a given year.
*
* yearAnualWeeklyBatch / (0.995^0 + 0.995^1 ... + 0.995^51)
*
* @param year Year zero based.
*/
function yearFrontWeightedWRB(uint256 year) internal pure returns (uint256) {
uint256 totalWeeklyAnualBatch = yearAnualWeeklyBatch(year);
return totalWeeklyAnualBatch.mul(ONE).div(WEEK_BATCH_DIV);
}
/**
* @dev Calculates the Weekly Release Batch amount for the given year and week.
*
* @param year Year zero based.
* @param week Week zero based.
*/
function yearWeekRelaseBatch(uint256 year, uint256 week) public pure returns (uint256) {
uint256 yearW1 = yearFrontWeightedWRB(year);
uint256 weeklyRedPercentage = weeklyRedPerc(week);
return yearW1.mul(weeklyRedPercentage).div(ONE);
}
/**
* @dev Gets first block of the given year.
*
* @param year Year zero based.
*/
function yearFirstBlock(uint256 year) internal view returns (uint256) {
return initialBlock.add(YEAR.mul(year));
}
/**
* @dev Gets first block of the given year and week.
*
* @param year Year zero based.
* @param week Week zero based.
*/
function yearWeekFirstBlock(uint256 year, uint256 week) internal view returns (uint256) {
uint256 yFB = yearFirstBlock(year);
return yFB.add(WEEK.mul(week));
}
/**
* @dev Gets last block of the given year and week.
*
* @param year Year zero based.
* @param week Week zero based.
*/
function yearWeekLastBlock(uint256 year, uint256 week) internal view returns (uint256) {
return yearWeekFirstBlock(year, week + 1);
}
/**
* @dev Gets the year of a given block.
*
* @param blockNumber Block number.
*/
function blockYear(uint256 blockNumber) internal view returns (uint256) {
return (blockNumber.sub(initialBlock)).div(YEAR);
}
/**
* @dev Gets the week of a given block within the block year.
*
* @param blockNumber Block number.
*/
function blockWeek(uint256 blockNumber) internal view returns (uint256) {
return (blockNumber.sub(yearFirstBlock(blockYear(blockNumber)))).div(WEEK);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @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;
/*
* @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;
}
}
|
Gets first block of the given year and week. year Year zero based. week Week zero based./
|
function yearWeekFirstBlock(uint256 year, uint256 week) internal view returns (uint256) {
uint256 yFB = yearFirstBlock(year);
return yFB.add(WEEK.mul(week));
}
| 1,392,239 |
// SPDX-License-Identifier: AGPL
// File: contracts/interfaces/IITR.sol
pragma solidity ^0.8.0;
interface IITR {
function claim(address to) external;
}
// File: contracts/interfaces/ISRC20.sol
pragma solidity ^0.8.0;
interface ISRC20 {
event RestrictionsAndRulesUpdated(address restrictions, address rules);
function transferToken(address to, uint256 value, uint256 nonce, uint256 expirationTime,
bytes32 msgHash, bytes calldata signature) external returns (bool);
function transferTokenFrom(address from, address to, uint256 value, uint256 nonce,
uint256 expirationTime, bytes32 hash, bytes calldata signature) external returns (bool);
function getTransferNonce() external view returns (uint256);
function getTransferNonce(address account) external view returns (uint256);
function executeTransfer(address from, address to, uint256 value) external returns (bool);
function updateRestrictionsAndRules(address restrictions, address rules) external returns (bool);
// ERC20 part-like interface
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 value) external returns (bool);
function decreaseAllowance(address spender, uint256 value) external returns (bool);
}
// File: contracts/interfaces/ITransferRules.sol
pragma solidity ^0.8.0;
interface ITransferRules {
function setSRC(address src20) external returns (bool);
function doTransfer(address from, address to, uint256 value) external returns (bool);
}
// File: contracts/interfaces/IChain.sol
pragma solidity ^0.8.0;
interface IChain {
function doValidate(address from, address to, uint256 value) external returns (address, address, uint256, bool, string memory);
}
// 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: contracts/restrictions/ChainRuleBase.sol
pragma solidity ^0.8.0;
abstract contract ChainRuleBase is Ownable {
address public _chainRuleAddr;
function clearChain() public onlyOwner() {
_setChain(address(0));
}
function setChain(address chainAddr) public onlyOwner() {
_setChain(chainAddr);
}
//---------------------------------------------------------------------------------
// internal section
//---------------------------------------------------------------------------------
function _doValidate(
address from,
address to,
uint256 value
)
internal
returns (
address _from,
address _to,
uint256 _value,
bool _success,
string memory _msg
)
{
(_from, _to, _value, _success, _msg) = _validate(from, to, value);
if (isChainExists() && _success) {
(_from, _to, _value, _success, _msg) = IChain(_chainRuleAddr).doValidate(msg.sender, to, value);
}
}
function isChainExists() internal view returns(bool) {
return (_chainRuleAddr != address(0) ? true : false);
}
function _setChain(address chainAddr) internal {
_chainRuleAddr = chainAddr;
}
function _validate(address from, address to, uint256 value) internal virtual returns (address, address, uint256, bool, string memory);
}
// 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];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// 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);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// 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));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: contracts/restrictions/TransferRule.sol
pragma solidity ^0.8.0;
contract TransferRule is Ownable, ITransferRules, ChainRuleBase {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
address public _src20;
address public _doTransferCaller;
uint256 internal constant MULTIPLIER = 100000;
address public _tradedToken;
uint256 public _lockupDuration;
uint256 public _lockupFraction;
struct Item {
uint256 untilTime;
uint256 lockedAmount;
}
mapping(address => Item) restrictions;
EnumerableSet.AddressSet _exchangeDepositAddresses;
modifier onlyDoTransferCaller {
require(msg.sender == address(_doTransferCaller));
_;
}
//---------------------------------------------------------------------------------
// public section
//---------------------------------------------------------------------------------
/**
* @param tradedToken tradedToken
* @param lockupDuration duration in sec
* @param lockupFraction fraction in percent to lock. multiplied by MULTIPLIER
*/
constructor(
address tradedToken,
uint256 lockupDuration,
uint256 lockupFraction
)
{
_tradedToken = tradedToken;
_lockupDuration = lockupDuration;
_lockupFraction = lockupFraction;
}
function cleanSRC() public onlyOwner() {
_src20 = address(0);
_doTransferCaller = address(0);
//_setChain(address(0));
}
function addExchangeAddress(address addr) public onlyOwner() {
_exchangeDepositAddresses.add(addr);
}
function removeExchangeAddress(address addr) public onlyOwner() {
_exchangeDepositAddresses.remove(addr);
}
function viewExchangeAddresses() public view returns(address[] memory) {
uint256 len = _exchangeDepositAddresses.length();
address[] memory ret = new address[](len);
for (uint256 i =0; i < len; i++) {
ret[i] = _exchangeDepositAddresses.at(i);
}
return ret;
}
function addRestrictions(
address[] memory addressArray,
uint256[] memory amountArray,
uint256[] memory untilArray
) public onlyOwner {
uint l=addressArray.length;
for (uint i=0; i<l; i++) {
restrictions[ addressArray[i] ] = Item({
lockedAmount: amountArray[i],
untilTime: untilArray[i]
});
}
}
//---------------------------------------------------------------------------------
// external section
//---------------------------------------------------------------------------------
/**
* @dev Set for what contract this rules are.
*
* @param src20 - Address of src20 contract.
*/
function setSRC(address src20) override external returns (bool) {
require(_doTransferCaller == address(0), "external contract already set");
require(address(_src20) == address(0), "external contract already set");
require(src20 != address(0), "src20 can not be zero");
_doTransferCaller = _msgSender();
_src20 = src20;
return true;
}
/**
* @dev Do transfer and checks where funds should go.
* before executeTransfer contract will call chainValidate on chain if exists
*
* @param from The address to transfer from.
* @param to The address to send tokens to.
* @param value The amount of tokens to send.
*/
function doTransfer(address from, address to, uint256 value) override external onlyDoTransferCaller returns (bool) {
bool success;
string memory errmsg;
(from, to, value, success, errmsg) = _doValidate(from, to, value);
require(success, (bytes(errmsg).length == 0) ? "chain validation failed" : errmsg);
// todo: need to check params after chains validation??
require(ISRC20(_src20).executeTransfer(from, to, value), "SRC20 transfer failed");
if (
success && (to == _tradedToken)
) {
IITR(_tradedToken).claim(from);
}
return true;
}
//---------------------------------------------------------------------------------
// internal section
//---------------------------------------------------------------------------------
function _validate(address from, address to, uint256 value) internal virtual override returns (address _from, address _to, uint256 _value, bool _success, string memory _errmsg) {
(_from, _to, _value, _success, _errmsg) = (from, to, value, true, "");
require(
_exchangeDepositAddresses.contains(to) == false,
string(abi.encodePacked("Don't deposit directly to this exchange. Send to the address ITR.ETH first, to obtain the correct token in your wallet."))
);
uint256 balanceFrom = ISRC20(_src20).balanceOf(from);
if (restrictions[from].untilTime > block.timestamp) {
if (to == _tradedToken) {
_success = false;
_errmsg = "you recently claimed new tokens, please wait until duration has elapsed to claim again";
} else if ((restrictions[from].lockedAmount).add(value) > balanceFrom) {
_success = false;
_errmsg = "you recently claimed new tokens, please wait until duration has elapsed to transfer this many tokens";
}
}
if (
_success &&
(to == _tradedToken) &&
(restrictions[from].untilTime > block.timestamp)
) {
restrictions[from].untilTime = (block.timestamp).add(_lockupDuration);
restrictions[from].lockedAmount = (balanceFrom.sub(value)).mul(_lockupFraction).div(MULTIPLIER);
}
}
//---------------------------------------------------------------------------------
// private section
//---------------------------------------------------------------------------------
}
|
Return the entire set in an array WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block./
|
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
| 6,152,348 |
/**
*Submitted for verification at BscScan.com on 2021-08-04
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IOwnable {
function policy() external view returns (address);
function renounceManagement() external;
function pushManagement( address newOwner_ ) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed( address(0), _owner );
}
function policy() public view override returns (address) {
return _owner;
}
modifier onlyPolicy() {
require( _owner == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renounceManagement() public virtual override onlyPolicy() {
emit OwnershipPushed( _owner, address(0) );
_owner = address(0);
}
function pushManagement( address newOwner_ ) public virtual override onlyPolicy() {
require( newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed( _owner, newOwner_ );
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require( msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled( _owner, _newOwner );
_owner = _newOwner;
}
}
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;
}
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
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 {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
interface IERC20 {
function decimals() external view returns (uint8);
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);
}
abstract contract ERC20 is IERC20 {
using SafeMath for uint256;
// TODO comment actual hash value.
bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" );
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
constructor (string memory name_, string memory symbol_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, 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(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][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 ammount_) internal virtual {
require(account_ != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address( this ), account_, ammount_);
_totalSupply = _totalSupply.add(ammount_);
_balances[account_] = _balances[account_].add(ammount_);
emit Transfer(address( this ), account_, ammount_);
}
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 _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { }
}
interface IERC2612Permit {
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
}
library Counters {
using SafeMath for uint256;
struct Counter {
uint256 _value; // default: 0
}
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);
}
}
abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)
)
);
}
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct =
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline));
bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct));
address signer = ecrecover(_hash, v, r, s);
require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
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) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library FullMath {
function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, 'FullMath::mulDiv: overflow');
return fullDiv(l, h, d);
}
}
library FixedPoint {
struct uq112x112 {
uint224 _x;
}
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
return uint(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
}
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,
uint256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
interface ITreasury {
function deposit( uint _amount, address _token, uint _profit ) external returns ( uint send_ );
function valueOf( address _token, uint _amount ) external view returns ( uint value_ );
function mintRewards( address _recipient, uint _amount ) external;
}
interface IStaking {
function stake( uint _amount, address _recipient ) external returns ( bool );
function claim( address _recipient ) external;
}
// interface IStakingHelper {
// function stake( uint _amount, address _recipient ) external;
// }
interface ISSDA {
function gonsForBalance( uint amount ) external view returns ( uint );
function balanceForGons( uint gons ) external view returns ( uint );
}
interface IUniswapV2Pair {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function token0() external view returns ( address );
function token1() external view returns ( address );
}
contract SdaBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMath for uint;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable SDA; // intermediate reward token from treasury
address public immutable sSDA; // token given as payment for bond
address public immutable principle; // token used to create bond
address public immutable treasury; // mints SDA when receives principle
address public immutable DAO; // receives profit share from bond
address public immutable WETH;
AggregatorV3Interface internal priceFeed;
address public staking; // to auto-stake payout
// address public stakingHelper; // to stake and claim if no staking warmup
address public pair;
// bool public useHelper;
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public _bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint public lastDecay; // reference block for debt decay
uint public totalPrinciple; // total principle bonded through this depository
string internal name_; //name of this bond
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint controlVariable; // scaling variable for price
uint vestingTerm; // in blocks
uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15)
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint gonsPayout; // SDA remaining to be paid
uint sdaPayout; // sda amount at the moment of bond
uint vesting; // Blocks left to vest
uint lastBlock; // Last interaction
uint pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint buffer; // minimum length (in blocks) between adjustments
uint lastBlock; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor (
string memory _name,
address _SDA,
address _sSDA,
address _principle,
address _treasury,
address _DAO,
address _feed,
address _pair,
address _weth
) {
require( _SDA != address(0) );
SDA = _SDA;
require( _sSDA != address(0) );
sSDA = _sSDA;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
require( _feed != address(0) );
priceFeed = AggregatorV3Interface( _feed );
require( _pair != address(0) );
pair = _pair; // cake and wBNB pair
WETH = _weth;
name_ = _name;
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(
uint _controlVariable,
uint _vestingTerm,
uint _minimumPrice,
uint _maxPayout,
uint _maxDebt,
uint _initialDebt
) external onlyPolicy() {
// require( currentDebt() == 0, "Debt must be 0 for initialization" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = block.number;
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 10000, "Vesting must be longer than 36 hours" );
terms.vestingTerm = _input;
} else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 3
terms.maxDebt = _input;
} else if ( _parameter == PARAMETER.MINPRICE ) { // 4
terms.minimumPrice = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment (
bool _addition,
uint _increment,
uint _target,
uint _buffer
) external onlyPolicy() {
// require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastBlock: block.number
});
}
/**
* @notice set contract for auto stake
* @param _staking address
*/
function setStaking( address _staking ) external onlyPolicy() {
require( _staking != address(0) );
staking = _staking;
}
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit(
uint _amount,
uint _maxPrice,
address _depositor
) external returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
// uint nativePrice = _bondPrice();
require( _maxPrice >= _bondPrice(), "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOf( principle, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 SDA ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
/**
asset carries risk and is not minted against
asset transfered to treasury and rewards minted as payout
*/
IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount );
ITreasury( treasury ).mintRewards( address(this), payout );
totalPrinciple=totalPrinciple.add(_amount);
// total debt is increased
totalDebt = totalDebt.add( value );
//TODO
//uint stakeAmount = totalBond.sub(fee);
IERC20( SDA ).approve( staking, payout );
IStaking( staking ).stake( payout, address(this) );
IStaking( staking ).claim( address(this) );
uint stakeGons=ISSDA(sSDA).gonsForBalance(payout);
// depositor info is stored
_bondInfo[ _depositor ] = Bond({
gonsPayout: _bondInfo[ _depositor ].gonsPayout.add( stakeGons ),
sdaPayout: _bondInfo[ _depositor ].sdaPayout.add( payout ),
vesting: terms.vestingTerm,
lastBlock: block.number,
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user, keep the parameter bool _stake for compatibility of redeem helper
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem( address _recipient, bool _stake ) external returns ( uint ) {
Bond memory info = _bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)
require ( percentVested >= 10000, "not yet fully vested" ); // if fully vested
delete _bondInfo[ _recipient ]; // delete user info
uint _amount = ISSDA(sSDA).balanceForGons(info.gonsPayout);
emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data
IERC20( sSDA ).transfer( _recipient, _amount ); // pay user everything due
return _amount;
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer );
if( adjustment.rate != 0 && block.number >= blockCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target ) {
adjustment.rate = 0;
}
}
adjustment.lastBlock = block.number;
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = block.number;
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( SDA ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
// return FixedPoint.fraction( _value, bondPrice() ).decode112with18().mul( assetPrice() ).div(1e22) ; // div(14).mul(6).div(14)
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div(1e14);
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice get asset price from chainlink
*/
function assetPrice() public view returns (uint) {
( , uint price, , , ) = priceFeed.latestRoundData();
(uint reserve0, uint reserve1, ) = IUniswapV2Pair( pair ).getReserves();
uint weth_decimal = IERC20(WETH).decimals();
if(IUniswapV2Pair(pair).token0() == WETH) {
uint token_decimal = IERC20(IUniswapV2Pair(pair).token1()).decimals();
if(weth_decimal > token_decimal) {
price = (price * reserve0 / reserve1) / 10 ** (weth_decimal - token_decimal);
}
else {
price = price * reserve0 * 10 ** (token_decimal - weth_decimal) / reserve1;
}
}
else if(IUniswapV2Pair(pair).token1() == WETH) {
uint token_decimal = IERC20(IUniswapV2Pair(pair).token0()).decimals();
if(weth_decimal > token_decimal) {
price = (price * reserve1 / reserve0) / 10 ** (weth_decimal - token_decimal);
}
else {
price = price * reserve1 * 10 ** (token_decimal - weth_decimal) / reserve0;
}
}
return price;
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns ( uint price_ ) {
price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 );
}
/**
* @notice return bond info with latest sSDA balance calculated from gons
* @param _depositor address
* @return payout uint
* @return vesting uint
* @return lastBlock uint
* @return pricePaid uint
*/
function bondInfo(address _depositor) public view returns ( uint payout,uint vesting,uint lastBlock,uint pricePaid ) {
Bond memory info = _bondInfo[ _depositor ];
payout=ISSDA(sSDA).balanceForGons(info.gonsPayout);
vesting=info.vesting;
lastBlock=info.lastBlock;
pricePaid=info.pricePaid;
}
/**
* @notice calculate current ratio of debt to SDA supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( SDA ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice debt ratio in same terms as reserve bonds
* @return uint
*/
function standardizedDebtRatio() external view returns ( uint ) {
return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint blocksSinceLast = block.number.sub( lastDecay );
decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = _bondInfo[ _depositor ];
uint blocksSinceLast = block.number.sub( bond.lastBlock );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of SDA available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = ISSDA(sSDA).balanceForGons(_bondInfo[ _depositor ].gonsPayout);
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = 0;
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or SDA) to the DAO
* @return bool
*/
function recoverLostToken( address _token ) external returns ( bool ) {
require( _token != SDA );
require( _token != sSDA );
require( _token != principle );
IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
return true;
}
}
|
get asset price from chainlink/
|
function assetPrice() public view returns (uint) {
( , uint price, , , ) = priceFeed.latestRoundData();
(uint reserve0, uint reserve1, ) = IUniswapV2Pair( pair ).getReserves();
uint weth_decimal = IERC20(WETH).decimals();
if(IUniswapV2Pair(pair).token0() == WETH) {
uint token_decimal = IERC20(IUniswapV2Pair(pair).token1()).decimals();
if(weth_decimal > token_decimal) {
price = (price * reserve0 / reserve1) / 10 ** (weth_decimal - token_decimal);
}
else {
price = price * reserve0 * 10 ** (token_decimal - weth_decimal) / reserve1;
}
}
if(IUniswapV2Pair(pair).token0() == WETH) {
uint token_decimal = IERC20(IUniswapV2Pair(pair).token1()).decimals();
if(weth_decimal > token_decimal) {
price = (price * reserve0 / reserve1) / 10 ** (weth_decimal - token_decimal);
}
else {
price = price * reserve0 * 10 ** (token_decimal - weth_decimal) / reserve1;
}
}
if(IUniswapV2Pair(pair).token0() == WETH) {
uint token_decimal = IERC20(IUniswapV2Pair(pair).token1()).decimals();
if(weth_decimal > token_decimal) {
price = (price * reserve0 / reserve1) / 10 ** (weth_decimal - token_decimal);
}
else {
price = price * reserve0 * 10 ** (token_decimal - weth_decimal) / reserve1;
}
}
else if(IUniswapV2Pair(pair).token1() == WETH) {
uint token_decimal = IERC20(IUniswapV2Pair(pair).token0()).decimals();
if(weth_decimal > token_decimal) {
price = (price * reserve1 / reserve0) / 10 ** (weth_decimal - token_decimal);
}
else {
price = price * reserve1 * 10 ** (token_decimal - weth_decimal) / reserve0;
}
}
return price;
else if(IUniswapV2Pair(pair).token1() == WETH) {
uint token_decimal = IERC20(IUniswapV2Pair(pair).token0()).decimals();
if(weth_decimal > token_decimal) {
price = (price * reserve1 / reserve0) / 10 ** (weth_decimal - token_decimal);
}
else {
price = price * reserve1 * 10 ** (token_decimal - weth_decimal) / reserve0;
}
}
return price;
else if(IUniswapV2Pair(pair).token1() == WETH) {
uint token_decimal = IERC20(IUniswapV2Pair(pair).token0()).decimals();
if(weth_decimal > token_decimal) {
price = (price * reserve1 / reserve0) / 10 ** (weth_decimal - token_decimal);
}
else {
price = price * reserve1 * 10 ** (token_decimal - weth_decimal) / reserve0;
}
}
return price;
}
| 6,002,483 |
// the azimuth logic contract
// https://azimuth.network
pragma solidity 0.4.24;
////////////////////////////////////////////////////////////////////////////////
// Imports
////////////////////////////////////////////////////////////////////////////////
// OpenZeppelin's 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;
}
}
// Azimuth's SafeMath8.sol
/**
* @title SafeMath8
* @dev Math operations for uint8 with safety checks that throw on error
*/
library SafeMath8 {
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
}
// Azimuth's SafeMath16.sol
/**
* @title SafeMath16
* @dev Math operations for uint16 with safety checks that throw on error
*/
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint16 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
}
// OpenZeppelin's 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;
}
}
// OpenZeppelin's ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// OpenZeppelin's SupportsInterfaceWithLookup.sol
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
// OpenZeppelin's ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// OpenZeppelin's ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// OpenZeppelin's ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// OpenZeppelin's AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// Azimuth's Azimuth.sol
// Azimuth: point state data contract
//
// This contract is used for storing all data related to Azimuth points
// and their ownership. Consider this contract the Azimuth ledger.
//
// It also contains permissions data, which ties in to ERC721
// functionality. Operators of an address are allowed to transfer
// ownership of all points owned by their associated address
// (ERC721's approveAll()). A transfer proxy is allowed to transfer
// ownership of a single point (ERC721's approve()).
// Separate from ERC721 are managers, assigned per point. They are
// allowed to perform "low-impact" operations on the owner's points,
// like configuring public keys and making escape requests.
//
// Since data stores are difficult to upgrade, this contract contains
// as little actual business logic as possible. Instead, the data stored
// herein can only be modified by this contract's owner, which can be
// changed and is thus upgradable/replaceable.
//
// This contract will be owned by the Ecliptic contract.
//
contract Azimuth is Ownable
{
//
// Events
//
// OwnerChanged: :point is now owned by :owner
//
event OwnerChanged(uint32 indexed point, address indexed owner);
// Activated: :point is now active
//
event Activated(uint32 indexed point);
// Spawned: :prefix has spawned :child
//
event Spawned(uint32 indexed prefix, uint32 indexed child);
// EscapeRequested: :point has requested a new :sponsor
//
event EscapeRequested(uint32 indexed point, uint32 indexed sponsor);
// EscapeCanceled: :point's :sponsor request was canceled or rejected
//
event EscapeCanceled(uint32 indexed point, uint32 indexed sponsor);
// EscapeAccepted: :point confirmed with a new :sponsor
//
event EscapeAccepted(uint32 indexed point, uint32 indexed sponsor);
// LostSponsor: :point's :sponsor is now refusing it service
//
event LostSponsor(uint32 indexed point, uint32 indexed sponsor);
// ChangedKeys: :point has new network public keys
//
event ChangedKeys( uint32 indexed point,
bytes32 encryptionKey,
bytes32 authenticationKey,
uint32 cryptoSuiteVersion,
uint32 keyRevisionNumber );
// BrokeContinuity: :point has a new continuity number, :number
//
event BrokeContinuity(uint32 indexed point, uint32 number);
// ChangedSpawnProxy: :spawnProxy can now spawn using :point
//
event ChangedSpawnProxy(uint32 indexed point, address indexed spawnProxy);
// ChangedTransferProxy: :transferProxy can now transfer ownership of :point
//
event ChangedTransferProxy( uint32 indexed point,
address indexed transferProxy );
// ChangedManagementProxy: :managementProxy can now manage :point
//
event ChangedManagementProxy( uint32 indexed point,
address indexed managementProxy );
// ChangedVotingProxy: :votingProxy can now vote using :point
//
event ChangedVotingProxy(uint32 indexed point, address indexed votingProxy);
// ChangedDns: dnsDomains have been updated
//
event ChangedDns(string primary, string secondary, string tertiary);
//
// Structures
//
// Size: kinds of points registered on-chain
//
// NOTE: the order matters, because of Solidity enum numbering
//
enum Size
{
Galaxy, // = 0
Star, // = 1
Planet // = 2
}
// Point: state of a point
//
// While the ordering of the struct members is semantically chaotic,
// they are ordered to tightly pack them into Ethereum's 32-byte storage
// slots, which reduces gas costs for some function calls.
// The comment ticks indicate assumed slot boundaries.
//
struct Point
{
// encryptionKey: (curve25519) encryption public key, or 0 for none
//
bytes32 encryptionKey;
//
// authenticationKey: (ed25519) authentication public key, or 0 for none
//
bytes32 authenticationKey;
//
// spawned: for stars and galaxies, all :active children
//
uint32[] spawned;
//
// hasSponsor: true if the sponsor still supports the point
//
bool hasSponsor;
// active: whether point can be linked
//
// false: point belongs to prefix, cannot be configured or linked
// true: point no longer belongs to prefix, can be configured and linked
//
bool active;
// escapeRequested: true if the point has requested to change sponsors
//
bool escapeRequested;
// sponsor: the point that supports this one on the network, or,
// if :hasSponsor is false, the last point that supported it.
// (by default, the point's half-width prefix)
//
uint32 sponsor;
// escapeRequestedTo: if :escapeRequested is true, new sponsor requested
//
uint32 escapeRequestedTo;
// cryptoSuiteVersion: version of the crypto suite used for the pubkeys
//
uint32 cryptoSuiteVersion;
// keyRevisionNumber: incremented every time the public keys change
//
uint32 keyRevisionNumber;
// continuityNumber: incremented to indicate network-side state loss
//
uint32 continuityNumber;
}
// Deed: permissions for a point
//
struct Deed
{
// owner: address that owns this point
//
address owner;
// managementProxy: 0, or another address with the right to perform
// low-impact, managerial operations on this point
//
address managementProxy;
// spawnProxy: 0, or another address with the right to spawn children
// of this point
//
address spawnProxy;
// votingProxy: 0, or another address with the right to vote as this point
//
address votingProxy;
// transferProxy: 0, or another address with the right to transfer
// ownership of this point
//
address transferProxy;
}
//
// General state
//
// points: per point, general network-relevant point state
//
mapping(uint32 => Point) public points;
// rights: per point, on-chain ownership and permissions
//
mapping(uint32 => Deed) public rights;
// operators: per owner, per address, has the right to transfer ownership
// of all the owner's points (ERC721)
//
mapping(address => mapping(address => bool)) public operators;
// dnsDomains: base domains for contacting galaxies
//
// dnsDomains[0] is primary, the others are used as fallbacks
//
string[3] public dnsDomains;
//
// Lookups
//
// sponsoring: per point, the points they are sponsoring
//
mapping(uint32 => uint32[]) public sponsoring;
// sponsoringIndexes: per point, per point, (index + 1) in
// the sponsoring array
//
mapping(uint32 => mapping(uint32 => uint256)) public sponsoringIndexes;
// escapeRequests: per point, the points they have open escape requests from
//
mapping(uint32 => uint32[]) public escapeRequests;
// escapeRequestsIndexes: per point, per point, (index + 1) in
// the escapeRequests array
//
mapping(uint32 => mapping(uint32 => uint256)) public escapeRequestsIndexes;
// pointsOwnedBy: per address, the points they own
//
mapping(address => uint32[]) public pointsOwnedBy;
// pointOwnerIndexes: per owner, per point, (index + 1) in
// the pointsOwnedBy array
//
// We delete owners by moving the last entry in the array to the
// newly emptied slot, which is (n - 1) where n is the value of
// pointOwnerIndexes[owner][point].
//
mapping(address => mapping(uint32 => uint256)) public pointOwnerIndexes;
// managerFor: per address, the points they are the management proxy for
//
mapping(address => uint32[]) public managerFor;
// managerForIndexes: per address, per point, (index + 1) in
// the managerFor array
//
mapping(address => mapping(uint32 => uint256)) public managerForIndexes;
// spawningFor: per address, the points they can spawn with
//
mapping(address => uint32[]) public spawningFor;
// spawningForIndexes: per address, per point, (index + 1) in
// the spawningFor array
//
mapping(address => mapping(uint32 => uint256)) public spawningForIndexes;
// votingFor: per address, the points they can vote with
//
mapping(address => uint32[]) public votingFor;
// votingForIndexes: per address, per point, (index + 1) in
// the votingFor array
//
mapping(address => mapping(uint32 => uint256)) public votingForIndexes;
// transferringFor: per address, the points they can transfer
//
mapping(address => uint32[]) public transferringFor;
// transferringForIndexes: per address, per point, (index + 1) in
// the transferringFor array
//
mapping(address => mapping(uint32 => uint256)) public transferringForIndexes;
//
// Logic
//
// constructor(): configure default dns domains
//
constructor()
public
{
setDnsDomains("example.com", "example.com", "example.com");
}
// setDnsDomains(): set the base domains used for contacting galaxies
//
// Note: since a string is really just a byte[], and Solidity can't
// work with two-dimensional arrays yet, we pass in the three
// domains as individual strings.
//
function setDnsDomains(string _primary, string _secondary, string _tertiary)
onlyOwner
public
{
dnsDomains[0] = _primary;
dnsDomains[1] = _secondary;
dnsDomains[2] = _tertiary;
emit ChangedDns(_primary, _secondary, _tertiary);
}
//
// Point reading
//
// isActive(): return true if _point is active
//
function isActive(uint32 _point)
view
external
returns (bool equals)
{
return points[_point].active;
}
// getKeys(): returns the public keys and their details, as currently
// registered for _point
//
function getKeys(uint32 _point)
view
external
returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision)
{
Point storage point = points[_point];
return (point.encryptionKey,
point.authenticationKey,
point.cryptoSuiteVersion,
point.keyRevisionNumber);
}
// getKeyRevisionNumber(): gets the revision number of _point's current
// public keys
//
function getKeyRevisionNumber(uint32 _point)
view
external
returns (uint32 revision)
{
return points[_point].keyRevisionNumber;
}
// hasBeenLinked(): returns true if the point has ever been assigned keys
//
function hasBeenLinked(uint32 _point)
view
external
returns (bool result)
{
return ( points[_point].keyRevisionNumber > 0 );
}
// isLive(): returns true if _point currently has keys properly configured
//
function isLive(uint32 _point)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.encryptionKey != 0 &&
point.authenticationKey != 0 &&
point.cryptoSuiteVersion != 0 );
}
// getContinuityNumber(): returns _point's current continuity number
//
function getContinuityNumber(uint32 _point)
view
external
returns (uint32 continuityNumber)
{
return points[_point].continuityNumber;
}
// getSpawnCount(): return the number of children spawned by _point
//
function getSpawnCount(uint32 _point)
view
external
returns (uint32 spawnCount)
{
uint256 len = points[_point].spawned.length;
assert(len < 2**32);
return uint32(len);
}
// getSpawned(): return array of points created under _point
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawned(uint32 _point)
view
external
returns (uint32[] spawned)
{
return points[_point].spawned;
}
// hasSponsor(): returns true if _point's sponsor is providing it service
//
function hasSponsor(uint32 _point)
view
external
returns (bool has)
{
return points[_point].hasSponsor;
}
// getSponsor(): returns _point's current (or most recent) sponsor
//
function getSponsor(uint32 _point)
view
external
returns (uint32 sponsor)
{
return points[_point].sponsor;
}
// isSponsor(): returns true if _sponsor is currently providing service
// to _point
//
function isSponsor(uint32 _point, uint32 _sponsor)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.hasSponsor &&
(point.sponsor == _sponsor) );
}
// getSponsoringCount(): returns the number of points _sponsor is
// providing service to
//
function getSponsoringCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return sponsoring[_sponsor].length;
}
// getSponsoring(): returns a list of points _sponsor is providing
// service to
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSponsoring(uint32 _sponsor)
view
external
returns (uint32[] sponsees)
{
return sponsoring[_sponsor];
}
// escaping
// isEscaping(): returns true if _point has an outstanding escape request
//
function isEscaping(uint32 _point)
view
external
returns (bool escaping)
{
return points[_point].escapeRequested;
}
// getEscapeRequest(): returns _point's current escape request
//
// the returned escape request is only valid as long as isEscaping()
// returns true
//
function getEscapeRequest(uint32 _point)
view
external
returns (uint32 escape)
{
return points[_point].escapeRequestedTo;
}
// isRequestingEscapeTo(): returns true if _point has an outstanding
// escape request targetting _sponsor
//
function isRequestingEscapeTo(uint32 _point, uint32 _sponsor)
view
public
returns (bool equals)
{
Point storage point = points[_point];
return (point.escapeRequested && (point.escapeRequestedTo == _sponsor));
}
// getEscapeRequestsCount(): returns the number of points _sponsor
// is providing service to
//
function getEscapeRequestsCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return escapeRequests[_sponsor].length;
}
// getEscapeRequests(): get the points _sponsor has received escape
// requests from
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getEscapeRequests(uint32 _sponsor)
view
external
returns (uint32[] requests)
{
return escapeRequests[_sponsor];
}
//
// Point writing
//
// activatePoint(): activate a point, register it as spawned by its prefix
//
function activatePoint(uint32 _point)
onlyOwner
external
{
// make a point active, setting its sponsor to its prefix
//
Point storage point = points[_point];
require(!point.active);
point.active = true;
registerSponsor(_point, true, getPrefix(_point));
emit Activated(_point);
}
// setKeys(): set network public keys of _point to _encryptionKey and
// _authenticationKey, with the specified _cryptoSuiteVersion
//
function setKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion)
onlyOwner
external
{
Point storage point = points[_point];
if ( point.encryptionKey == _encryptionKey &&
point.authenticationKey == _authenticationKey &&
point.cryptoSuiteVersion == _cryptoSuiteVersion )
{
return;
}
point.encryptionKey = _encryptionKey;
point.authenticationKey = _authenticationKey;
point.cryptoSuiteVersion = _cryptoSuiteVersion;
point.keyRevisionNumber++;
emit ChangedKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion,
point.keyRevisionNumber);
}
// incrementContinuityNumber(): break continuity for _point
//
function incrementContinuityNumber(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
point.continuityNumber++;
emit BrokeContinuity(_point, point.continuityNumber);
}
// registerSpawn(): add a point to its prefix's list of spawned points
//
function registerSpawned(uint32 _point)
onlyOwner
external
{
// if a point is its own prefix (a galaxy) then don't register it
//
uint32 prefix = getPrefix(_point);
if (prefix == _point)
{
return;
}
// register a new spawned point for the prefix
//
points[prefix].spawned.push(_point);
emit Spawned(prefix, _point);
}
// loseSponsor(): indicates that _point's sponsor is no longer providing
// it service
//
function loseSponsor(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.hasSponsor)
{
return;
}
registerSponsor(_point, false, point.sponsor);
emit LostSponsor(_point, point.sponsor);
}
// setEscapeRequest(): for _point, start an escape request to _sponsor
//
function setEscapeRequest(uint32 _point, uint32 _sponsor)
onlyOwner
external
{
if (isRequestingEscapeTo(_point, _sponsor))
{
return;
}
registerEscapeRequest(_point, true, _sponsor);
emit EscapeRequested(_point, _sponsor);
}
// cancelEscape(): for _point, stop the current escape request, if any
//
function cancelEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.escapeRequested)
{
return;
}
uint32 request = point.escapeRequestedTo;
registerEscapeRequest(_point, false, 0);
emit EscapeCanceled(_point, request);
}
// doEscape(): perform the requested escape
//
function doEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
require(point.escapeRequested);
registerSponsor(_point, true, point.escapeRequestedTo);
registerEscapeRequest(_point, false, 0);
emit EscapeAccepted(_point, point.sponsor);
}
//
// Point utils
//
// getPrefix(): compute prefix ("parent") of _point
//
function getPrefix(uint32 _point)
pure
public
returns (uint16 prefix)
{
if (_point < 0x10000)
{
return uint16(_point % 0x100);
}
return uint16(_point % 0x10000);
}
// getPointSize(): return the size of _point
//
function getPointSize(uint32 _point)
external
pure
returns (Size _size)
{
if (_point < 0x100) return Size.Galaxy;
if (_point < 0x10000) return Size.Star;
return Size.Planet;
}
// internal use
// registerSponsor(): set the sponsorship state of _point and update the
// reverse lookup for sponsors
//
function registerSponsor(uint32 _point, bool _hasSponsor, uint32 _sponsor)
internal
{
Point storage point = points[_point];
bool had = point.hasSponsor;
uint32 prev = point.sponsor;
// if we didn't have a sponsor, and won't get one,
// or if we get the sponsor we already have,
// nothing will change, so jump out early.
//
if ( (!had && !_hasSponsor) ||
(had && _hasSponsor && prev == _sponsor) )
{
return;
}
// if the point used to have a different sponsor, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (had)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = sponsoringIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :sponsoringIndexes reference
//
uint32[] storage prevSponsoring = sponsoring[prev];
uint256 last = prevSponsoring.length - 1;
uint32 moved = prevSponsoring[last];
prevSponsoring[i] = moved;
sponsoringIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSponsoring[last]);
prevSponsoring.length = last;
sponsoringIndexes[prev][_point] = 0;
}
if (_hasSponsor)
{
uint32[] storage newSponsoring = sponsoring[_sponsor];
newSponsoring.push(_point);
sponsoringIndexes[_sponsor][_point] = newSponsoring.length;
}
point.sponsor = _sponsor;
point.hasSponsor = _hasSponsor;
}
// registerEscapeRequest(): set the escape state of _point and update the
// reverse lookup for sponsors
//
function registerEscapeRequest( uint32 _point,
bool _isEscaping, uint32 _sponsor )
internal
{
Point storage point = points[_point];
bool was = point.escapeRequested;
uint32 prev = point.escapeRequestedTo;
// if we weren't escaping, and won't be,
// or if we were escaping, and the new target is the same,
// nothing will change, so jump out early.
//
if ( (!was && !_isEscaping) ||
(was && _isEscaping && prev == _sponsor) )
{
return;
}
// if the point used to have a different request, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (was)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = escapeRequestsIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :escapeRequestsIndexes reference
//
uint32[] storage prevRequests = escapeRequests[prev];
uint256 last = prevRequests.length - 1;
uint32 moved = prevRequests[last];
prevRequests[i] = moved;
escapeRequestsIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevRequests[last]);
prevRequests.length = last;
escapeRequestsIndexes[prev][_point] = 0;
}
if (_isEscaping)
{
uint32[] storage newRequests = escapeRequests[_sponsor];
newRequests.push(_point);
escapeRequestsIndexes[_sponsor][_point] = newRequests.length;
}
point.escapeRequestedTo = _sponsor;
point.escapeRequested = _isEscaping;
}
//
// Deed reading
//
// owner
// getOwner(): return owner of _point
//
function getOwner(uint32 _point)
view
external
returns (address owner)
{
return rights[_point].owner;
}
// isOwner(): true if _point is owned by _address
//
function isOwner(uint32 _point, address _address)
view
external
returns (bool result)
{
return (rights[_point].owner == _address);
}
// getOwnedPointCount(): return length of array of points that _whose owns
//
function getOwnedPointCount(address _whose)
view
external
returns (uint256 count)
{
return pointsOwnedBy[_whose].length;
}
// getOwnedPoints(): return array of points that _whose owns
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getOwnedPoints(address _whose)
view
external
returns (uint32[] ownedPoints)
{
return pointsOwnedBy[_whose];
}
// getOwnedPointAtIndex(): get point at _index from array of points that
// _whose owns
//
function getOwnedPointAtIndex(address _whose, uint256 _index)
view
external
returns (uint32 point)
{
uint32[] storage owned = pointsOwnedBy[_whose];
require(_index < owned.length);
return owned[_index];
}
// management proxy
// getManagementProxy(): returns _point's current management proxy
//
function getManagementProxy(uint32 _point)
view
external
returns (address manager)
{
return rights[_point].managementProxy;
}
// isManagementProxy(): returns true if _proxy is _point's management proxy
//
function isManagementProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].managementProxy == _proxy);
}
// canManage(): true if _who is the owner or manager of _point
//
function canManage(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.managementProxy) ) );
}
// getManagerForCount(): returns the amount of points _proxy can manage
//
function getManagerForCount(address _proxy)
view
external
returns (uint256 count)
{
return managerFor[_proxy].length;
}
// getManagerFor(): returns the points _proxy can manage
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getManagerFor(address _proxy)
view
external
returns (uint32[] mfor)
{
return managerFor[_proxy];
}
// spawn proxy
// getSpawnProxy(): returns _point's current spawn proxy
//
function getSpawnProxy(uint32 _point)
view
external
returns (address spawnProxy)
{
return rights[_point].spawnProxy;
}
// isSpawnProxy(): returns true if _proxy is _point's spawn proxy
//
function isSpawnProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].spawnProxy == _proxy);
}
// canSpawnAs(): true if _who is the owner or spawn proxy of _point
//
function canSpawnAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.spawnProxy) ) );
}
// getSpawningForCount(): returns the amount of points _proxy
// can spawn with
//
function getSpawningForCount(address _proxy)
view
external
returns (uint256 count)
{
return spawningFor[_proxy].length;
}
// getSpawningFor(): get the points _proxy can spawn with
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawningFor(address _proxy)
view
external
returns (uint32[] sfor)
{
return spawningFor[_proxy];
}
// voting proxy
// getVotingProxy(): returns _point's current voting proxy
//
function getVotingProxy(uint32 _point)
view
external
returns (address voter)
{
return rights[_point].votingProxy;
}
// isVotingProxy(): returns true if _proxy is _point's voting proxy
//
function isVotingProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].votingProxy == _proxy);
}
// canVoteAs(): true if _who is the owner of _point,
// or the voting proxy of _point's owner
//
function canVoteAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.votingProxy) ) );
}
// getVotingForCount(): returns the amount of points _proxy can vote as
//
function getVotingForCount(address _proxy)
view
external
returns (uint256 count)
{
return votingFor[_proxy].length;
}
// getVotingFor(): returns the points _proxy can vote as
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getVotingFor(address _proxy)
view
external
returns (uint32[] vfor)
{
return votingFor[_proxy];
}
// transfer proxy
// getTransferProxy(): returns _point's current transfer proxy
//
function getTransferProxy(uint32 _point)
view
external
returns (address transferProxy)
{
return rights[_point].transferProxy;
}
// isTransferProxy(): returns true if _proxy is _point's transfer proxy
//
function isTransferProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].transferProxy == _proxy);
}
// canTransfer(): true if _who is the owner or transfer proxy of _point,
// or is an operator for _point's current owner
//
function canTransfer(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.transferProxy) ||
operators[deed.owner][_who] ) );
}
// getTransferringForCount(): returns the amount of points _proxy
// can transfer
//
function getTransferringForCount(address _proxy)
view
external
returns (uint256 count)
{
return transferringFor[_proxy].length;
}
// getTransferringFor(): get the points _proxy can transfer
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getTransferringFor(address _proxy)
view
external
returns (uint32[] tfor)
{
return transferringFor[_proxy];
}
// isOperator(): returns true if _operator is allowed to transfer
// ownership of _owner's points
//
function isOperator(address _owner, address _operator)
view
external
returns (bool result)
{
return operators[_owner][_operator];
}
//
// Deed writing
//
// setOwner(): set owner of _point to _owner
//
// Note: setOwner() only implements the minimal data storage
// logic for a transfer; the full transfer is implemented in
// Ecliptic.
//
// Note: _owner must not be the zero address.
//
function setOwner(uint32 _point, address _owner)
onlyOwner
external
{
// prevent burning of points by making zero the owner
//
require(0x0 != _owner);
// prev: previous owner, if any
//
address prev = rights[_point].owner;
if (prev == _owner)
{
return;
}
// if the point used to have a different owner, do some gymnastics to
// keep the list of owned points gapless. delete this point from the
// list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous owner's list of owned points
//
uint256 i = pointOwnerIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :pointOwnerIndexes reference
//
uint32[] storage owner = pointsOwnedBy[prev];
uint256 last = owner.length - 1;
uint32 moved = owner[last];
owner[i] = moved;
pointOwnerIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(owner[last]);
owner.length = last;
pointOwnerIndexes[prev][_point] = 0;
}
// update the owner list and the owner's index list
//
rights[_point].owner = _owner;
pointsOwnedBy[_owner].push(_point);
pointOwnerIndexes[_owner][_point] = pointsOwnedBy[_owner].length;
emit OwnerChanged(_point, _owner);
}
// setManagementProxy(): makes _proxy _point's management proxy
//
function setManagementProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.managementProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different manager, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old manager's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous manager's list of managed points
//
uint256 i = managerForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :managerForIndexes reference
//
uint32[] storage prevMfor = managerFor[prev];
uint256 last = prevMfor.length - 1;
uint32 moved = prevMfor[last];
prevMfor[i] = moved;
managerForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevMfor[last]);
prevMfor.length = last;
managerForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage mfor = managerFor[_proxy];
mfor.push(_point);
managerForIndexes[_proxy][_point] = mfor.length;
}
deed.managementProxy = _proxy;
emit ChangedManagementProxy(_point, _proxy);
}
// setSpawnProxy(): makes _proxy _point's spawn proxy
//
function setSpawnProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.spawnProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different spawn proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of spawning points
//
uint256 i = spawningForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :spawningForIndexes reference
//
uint32[] storage prevSfor = spawningFor[prev];
uint256 last = prevSfor.length - 1;
uint32 moved = prevSfor[last];
prevSfor[i] = moved;
spawningForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSfor[last]);
prevSfor.length = last;
spawningForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage sfor = spawningFor[_proxy];
sfor.push(_point);
spawningForIndexes[_proxy][_point] = sfor.length;
}
deed.spawnProxy = _proxy;
emit ChangedSpawnProxy(_point, _proxy);
}
// setVotingProxy(): makes _proxy _point's voting proxy
//
function setVotingProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.votingProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different voter, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old voter's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous voter's list of points it was
// voting for
//
uint256 i = votingForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :votingForIndexes reference
//
uint32[] storage prevVfor = votingFor[prev];
uint256 last = prevVfor.length - 1;
uint32 moved = prevVfor[last];
prevVfor[i] = moved;
votingForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevVfor[last]);
prevVfor.length = last;
votingForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage vfor = votingFor[_proxy];
vfor.push(_point);
votingForIndexes[_proxy][_point] = vfor.length;
}
deed.votingProxy = _proxy;
emit ChangedVotingProxy(_point, _proxy);
}
// setManagementProxy(): makes _proxy _point's transfer proxy
//
function setTransferProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.transferProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different transfer proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of transferable points
//
uint256 i = transferringForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :transferringForIndexes reference
//
uint32[] storage prevTfor = transferringFor[prev];
uint256 last = prevTfor.length - 1;
uint32 moved = prevTfor[last];
prevTfor[i] = moved;
transferringForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevTfor[last]);
prevTfor.length = last;
transferringForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage tfor = transferringFor[_proxy];
tfor.push(_point);
transferringForIndexes[_proxy][_point] = tfor.length;
}
deed.transferProxy = _proxy;
emit ChangedTransferProxy(_point, _proxy);
}
// setOperator(): dis/allow _operator to transfer ownership of all points
// owned by _owner
//
// operators are part of the ERC721 standard
//
function setOperator(address _owner, address _operator, bool _approved)
onlyOwner
external
{
operators[_owner][_operator] = _approved;
}
}
// Azimuth's ReadsAzimuth.sol
// ReadsAzimuth: referring to and testing against the Azimuth
// data contract
//
// To avoid needless repetition, this contract provides common
// checks and operations using the Azimuth contract.
//
contract ReadsAzimuth
{
// azimuth: points data storage contract.
//
Azimuth public azimuth;
// constructor(): set the Azimuth data contract's address
//
constructor(Azimuth _azimuth)
public
{
azimuth = _azimuth;
}
// activePointOwner(): require that :msg.sender is the owner of _point,
// and that _point is active
//
modifier activePointOwner(uint32 _point)
{
require( azimuth.isOwner(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointManager(): require that :msg.sender can manage _point,
// and that _point is active
//
modifier activePointManager(uint32 _point)
{
require( azimuth.canManage(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointSpawner(): require that :msg.sender can spawn as _point,
// and that _point is active
//
modifier activePointSpawner(uint32 _point)
{
require( azimuth.canSpawnAs(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointVoter(): require that :msg.sender can vote as _point,
// and that _point is active
//
modifier activePointVoter(uint32 _point)
{
require( azimuth.canVoteAs(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
}
// Azimuth's Polls.sol
// Polls: proposals & votes data contract
//
// This contract is used for storing all data related to the proposals
// of the senate (galaxy owners) and their votes on those proposals.
// It keeps track of votes and uses them to calculate whether a majority
// is in favor of a proposal.
//
// Every galaxy can only vote on a proposal exactly once. Votes cannot
// be changed. If a proposal fails to achieve majority within its
// duration, it can be restarted after its cooldown period has passed.
//
// The requirements for a proposal to achieve majority are as follows:
// - At least 1/4 of the currently active voters (rounded down) must have
// voted in favor of the proposal,
// - More than half of the votes cast must be in favor of the proposal,
// and this can no longer change, either because
// - the poll duration has passed, or
// - not enough voters remain to take away the in-favor majority.
// As soon as these conditions are met, no further interaction with
// the proposal is possible. Achieving majority is permanent.
//
// Since data stores are difficult to upgrade, all of the logic unrelated
// to the voting itself (that is, determining who is eligible to vote)
// is expected to be implemented by this contract's owner.
//
// This contract will be owned by the Ecliptic contract.
//
contract Polls is Ownable
{
using SafeMath for uint256;
using SafeMath16 for uint16;
using SafeMath8 for uint8;
// UpgradePollStarted: a poll on :proposal has opened
//
event UpgradePollStarted(address proposal);
// DocumentPollStarted: a poll on :proposal has opened
//
event DocumentPollStarted(bytes32 proposal);
// UpgradeMajority: :proposal has achieved majority
//
event UpgradeMajority(address proposal);
// DocumentMajority: :proposal has achieved majority
//
event DocumentMajority(bytes32 proposal);
// Poll: full poll state
//
struct Poll
{
// start: the timestamp at which the poll was started
//
uint256 start;
// voted: per galaxy, whether they have voted on this poll
//
bool[256] voted;
// yesVotes: amount of votes in favor of the proposal
//
uint16 yesVotes;
// noVotes: amount of votes against the proposal
//
uint16 noVotes;
// duration: amount of time during which the poll can be voted on
//
uint256 duration;
// cooldown: amount of time before the (non-majority) poll can be reopened
//
uint256 cooldown;
}
// pollDuration: duration set for new polls. see also Poll.duration above
//
uint256 public pollDuration;
// pollCooldown: cooldown set for new polls. see also Poll.cooldown above
//
uint256 public pollCooldown;
// totalVoters: amount of active galaxies
//
uint16 public totalVoters;
// upgradeProposals: list of all upgrades ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
address[] public upgradeProposals;
// upgradePolls: per address, poll held to determine if that address
// will become the new ecliptic
//
mapping(address => Poll) public upgradePolls;
// upgradeHasAchievedMajority: per address, whether that address
// has ever achieved majority
//
// If we did not store this, we would have to look at old poll data
// to see whether or not a proposal has ever achieved majority.
// Since the outcome of a poll is calculated based on :totalVoters,
// which may not be consistent across time, we need to store outcomes
// explicitly instead of re-calculating them. This allows us to always
// tell with certainty whether or not a majority was achieved,
// regardless of the current :totalVoters.
//
mapping(address => bool) public upgradeHasAchievedMajority;
// documentProposals: list of all documents ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
bytes32[] public documentProposals;
// documentPolls: per hash, poll held to determine if the corresponding
// document is accepted by the galactic senate
//
mapping(bytes32 => Poll) public documentPolls;
// documentHasAchievedMajority: per hash, whether that hash has ever
// achieved majority
//
// the note for upgradeHasAchievedMajority above applies here as well
//
mapping(bytes32 => bool) public documentHasAchievedMajority;
// documentMajorities: all hashes that have achieved majority
//
bytes32[] public documentMajorities;
// constructor(): initial contract configuration
//
constructor(uint256 _pollDuration, uint256 _pollCooldown)
public
{
reconfigure(_pollDuration, _pollCooldown);
}
// reconfigure(): change poll duration and cooldown
//
function reconfigure(uint256 _pollDuration, uint256 _pollCooldown)
public
onlyOwner
{
require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) &&
(5 days <= _pollCooldown) && (_pollCooldown <= 90 days) );
pollDuration = _pollDuration;
pollCooldown = _pollCooldown;
}
// incrementTotalVoters(): increase the amount of registered voters
//
function incrementTotalVoters()
external
onlyOwner
{
require(totalVoters < 256);
totalVoters = totalVoters.add(1);
}
// getAllUpgradeProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getUpgradeProposals()
external
view
returns (address[] proposals)
{
return upgradeProposals;
}
// getUpgradeProposalCount(): get the number of unique proposed upgrades
//
function getUpgradeProposalCount()
external
view
returns (uint256 count)
{
return upgradeProposals.length;
}
// getAllDocumentProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentProposals()
external
view
returns (bytes32[] proposals)
{
return documentProposals;
}
// getDocumentProposalCount(): get the number of unique proposed upgrades
//
function getDocumentProposalCount()
external
view
returns (uint256 count)
{
return documentProposals.length;
}
// getDocumentMajorities(): return array of all document majorities
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentMajorities()
external
view
returns (bytes32[] majorities)
{
return documentMajorities;
}
// hasVotedOnUpgradePoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal)
external
view
returns (bool result)
{
return upgradePolls[_proposal].voted[_galaxy];
}
// hasVotedOnDocumentPoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
view
returns (bool result)
{
return documentPolls[_proposal].voted[_galaxy];
}
// startUpgradePoll(): open a poll on making _proposal the new ecliptic
//
function startUpgradePoll(address _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
Poll storage poll = upgradePolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
upgradeProposals.push(_proposal);
}
startPoll(poll);
emit UpgradePollStarted(_proposal);
}
// startDocumentPoll(): open a poll on accepting the document
// whose hash is _proposal
//
function startDocumentPoll(bytes32 _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
Poll storage poll = documentPolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
documentProposals.push(_proposal);
}
startPoll(poll);
emit DocumentPollStarted(_proposal);
}
// startPoll(): open a new poll, or re-open an old one
//
function startPoll(Poll storage _poll)
internal
{
// check that the poll has cooled down enough to be started again
//
// for completely new polls, the values used will be zero
//
require( block.timestamp > ( _poll.start.add(
_poll.duration.add(
_poll.cooldown )) ) );
// set started poll state
//
_poll.start = block.timestamp;
delete _poll.voted;
_poll.yesVotes = 0;
_poll.noVotes = 0;
_poll.duration = pollDuration;
_poll.cooldown = pollCooldown;
}
// castUpgradeVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castUpgradeVote(uint8 _as, address _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = upgradePolls[_proposal];
processVote(poll, _as, _vote);
return updateUpgradePoll(_proposal);
}
// castDocumentVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _as, bytes32 _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = documentPolls[_proposal];
processVote(poll, _as, _vote);
return updateDocumentPoll(_proposal);
}
// processVote(): record a vote from _as on the _poll
//
function processVote(Poll storage _poll, uint8 _as, bool _vote)
internal
{
// assist symbolic execution tools
//
assert(block.timestamp >= _poll.start);
require( // may only vote once
//
!_poll.voted[_as] &&
//
// may only vote when the poll is open
//
(block.timestamp < _poll.start.add(_poll.duration)) );
// update poll state to account for the new vote
//
_poll.voted[_as] = true;
if (_vote)
{
_poll.yesVotes = _poll.yesVotes.add(1);
}
else
{
_poll.noVotes = _poll.noVotes.add(1);
}
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, updating state, sending an event,
// and returning true if it has
//
function updateUpgradePoll(address _proposal)
public
onlyOwner
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = upgradePolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update the state and send an event
//
if (majority)
{
upgradeHasAchievedMajority[_proposal] = true;
emit UpgradeMajority(_proposal);
}
return majority;
}
// updateDocumentPoll(): check whether the _proposal has achieved majority,
// updating the state and sending an event if it has
//
// this can be called by anyone, because the ecliptic does not
// need to be aware of the result
//
function updateDocumentPoll(bytes32 _proposal)
public
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = documentPolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update state and send an event
//
if (majority)
{
documentHasAchievedMajority[_proposal] = true;
documentMajorities.push(_proposal);
emit DocumentMajority(_proposal);
}
return majority;
}
// checkPollMajority(): returns true if the majority is in favor of
// the subject of the poll
//
function checkPollMajority(Poll _poll)
internal
view
returns (bool majority)
{
return ( // poll must have at least the minimum required yes-votes
//
(_poll.yesVotes >= (totalVoters / 4)) &&
//
// and have a majority...
//
(_poll.yesVotes > _poll.noVotes) &&
//
// ...that is indisputable
//
( // either because the poll has ended
//
(block.timestamp > _poll.start.add(_poll.duration)) ||
//
// or there are more yes votes than there can be no votes
//
( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) );
}
}
// Azimuth's Claims.sol
// Claims: simple identity management
//
// This contract allows points to document claims about their owner.
// Most commonly, these are about identity, with a claim's protocol
// defining the context or platform of the claim, and its dossier
// containing proof of its validity.
// Points are limited to a maximum of 16 claims.
//
// For existing claims, the dossier can be updated, or the claim can
// be removed entirely. It is recommended to remove any claims associated
// with a point when it is about to be transferred to a new owner.
// For convenience, the owner of the Azimuth contract (the Ecliptic)
// is allowed to clear claims for any point, allowing it to do this for
// you on-transfer.
//
contract Claims is ReadsAzimuth
{
// ClaimAdded: a claim was added by :by
//
event ClaimAdded( uint32 indexed by,
string _protocol,
string _claim,
bytes _dossier );
// ClaimRemoved: a claim was removed by :by
//
event ClaimRemoved(uint32 indexed by, string _protocol, string _claim);
// maxClaims: the amount of claims that can be registered per point
//
uint8 constant maxClaims = 16;
// Claim: claim details
//
struct Claim
{
// protocol: context of the claim
//
string protocol;
// claim: the claim itself
//
string claim;
// dossier: data relating to the claim, as proof
//
bytes dossier;
}
// per point, list of claims
//
mapping(uint32 => Claim[maxClaims]) public claims;
// constructor(): register the azimuth contract.
//
constructor(Azimuth _azimuth)
ReadsAzimuth(_azimuth)
public
{
//
}
// addClaim(): register a claim as _point
//
function addClaim(uint32 _point,
string _protocol,
string _claim,
bytes _dossier)
external
activePointManager(_point)
{
// require non-empty protocol and claim fields
//
require( ( 0 < bytes(_protocol).length ) &&
( 0 < bytes(_claim).length ) );
// cur: index + 1 of the claim if it already exists, 0 otherwise
//
uint8 cur = findClaim(_point, _protocol, _claim);
// if the claim doesn't yet exist, store it in state
//
if (cur == 0)
{
// if there are no empty slots left, this throws
//
uint8 empty = findEmptySlot(_point);
claims[_point][empty] = Claim(_protocol, _claim, _dossier);
}
//
// if the claim has been made before, update the version in state
//
else
{
claims[_point][cur-1] = Claim(_protocol, _claim, _dossier);
}
emit ClaimAdded(_point, _protocol, _claim, _dossier);
}
// removeClaim(): unregister a claim as _point
//
function removeClaim(uint32 _point, string _protocol, string _claim)
external
activePointManager(_point)
{
// i: current index + 1 in _point's list of claims
//
uint256 i = findClaim(_point, _protocol, _claim);
// we store index + 1, because 0 is the eth default value
// can only delete an existing claim
//
require(i > 0);
i--;
// clear out the claim
//
delete claims[_point][i];
emit ClaimRemoved(_point, _protocol, _claim);
}
// clearClaims(): unregister all of _point's claims
//
// can also be called by the ecliptic during point transfer
//
function clearClaims(uint32 _point)
external
{
// both point owner and ecliptic may do this
//
// We do not necessarily need to check for _point's active flag here,
// since inactive points cannot have claims set. Doing the check
// anyway would make this function slightly harder to think about due
// to its relation to Ecliptic's transferPoint().
//
require( azimuth.canManage(_point, msg.sender) ||
( msg.sender == azimuth.owner() ) );
Claim[maxClaims] storage currClaims = claims[_point];
// clear out all claims
//
for (uint8 i = 0; i < maxClaims; i++)
{
// only emit the removed event if there was a claim here
//
if ( 0 < bytes(currClaims[i].claim).length )
{
emit ClaimRemoved(_point, currClaims[i].protocol, currClaims[i].claim);
}
delete currClaims[i];
}
}
// findClaim(): find the index of the specified claim
//
// returns 0 if not found, index + 1 otherwise
//
function findClaim(uint32 _whose, string _protocol, string _claim)
public
view
returns (uint8 index)
{
// we use hashes of the string because solidity can't do string
// comparison yet
//
bytes32 protocolHash = keccak256(bytes(_protocol));
bytes32 claimHash = keccak256(bytes(_claim));
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) &&
( claimHash == keccak256(bytes(thisClaim.claim)) ) )
{
return i+1;
}
}
return 0;
}
// findEmptySlot(): find the index of the first empty claim slot
//
// returns the index of the slot, throws if there are no empty slots
//
function findEmptySlot(uint32 _whose)
internal
view
returns (uint8 index)
{
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( (0 == bytes(thisClaim.claim).length) )
{
return i;
}
}
revert();
}
}
// Treasury's ITreasuryProxy
interface ITreasuryProxy {
function upgradeTo(address _impl) external returns (bool);
function freeze() external returns (bool);
}
// Azimuth's EclipticBase.sol
// EclipticBase: upgradable ecliptic
//
// This contract implements the upgrade logic for the Ecliptic.
// Newer versions of the Ecliptic are expected to provide at least
// the onUpgrade() function. If they don't, upgrading to them will
// fail.
//
// Note that even though this contract doesn't specify any required
// interface members aside from upgrade() and onUpgrade(), contracts
// and clients may still rely on the presence of certain functions
// provided by the Ecliptic proper. Keep this in mind when writing
// new versions of it.
//
contract EclipticBase is Ownable, ReadsAzimuth
{
// Upgraded: _to is the new canonical Ecliptic
//
event Upgraded(address to);
// polls: senate voting contract
//
Polls public polls;
// previousEcliptic: address of the previous ecliptic this
// instance expects to upgrade from, stored and
// checked for to prevent unexpected upgrade paths
//
address public previousEcliptic;
constructor( address _previous,
Azimuth _azimuth,
Polls _polls )
ReadsAzimuth(_azimuth)
internal
{
previousEcliptic = _previous;
polls = _polls;
}
// onUpgrade(): called by previous ecliptic when upgrading
//
// in future ecliptics, this might perform more logic than
// just simple checks and verifications.
// when overriding this, make sure to call this original as well.
//
function onUpgrade()
external
{
// make sure this is the expected upgrade path,
// and that we have gotten the ownership we require
//
require( msg.sender == previousEcliptic &&
this == azimuth.owner() &&
this == polls.owner() );
}
// upgrade(): transfer ownership of the ecliptic data to the new
// ecliptic contract, notify it, then self-destruct.
//
// Note: any eth that have somehow ended up in this contract
// are also sent to the new ecliptic.
//
function upgrade(EclipticBase _new)
internal
{
// transfer ownership of the data contracts
//
azimuth.transferOwnership(_new);
polls.transferOwnership(_new);
// trigger upgrade logic on the target contract
//
_new.onUpgrade();
// emit event and destroy this contract
//
emit Upgraded(_new);
selfdestruct(_new);
}
}
////////////////////////////////////////////////////////////////////////////////
// Ecliptic
////////////////////////////////////////////////////////////////////////////////
// Ecliptic: logic for interacting with the Azimuth ledger
//
// This contract is the point of entry for all operations on the Azimuth
// ledger as stored in the Azimuth data contract. The functions herein
// are responsible for performing all necessary business logic.
// Examples of such logic include verifying permissions of the caller
// and ensuring a requested change is actually valid.
// Point owners can always operate on their own points. Ethereum addresses
// can also perform specific operations if they've been given the
// appropriate permissions. (For example, managers for general management,
// spawn proxies for spawning child points, etc.)
//
// This contract uses external contracts (Azimuth, Polls) for data storage
// so that it itself can easily be replaced in case its logic needs to
// be changed. In other words, it can be upgraded. It does this by passing
// ownership of the data contracts to a new Ecliptic contract.
//
// Because of this, it is advised for clients to not store this contract's
// address directly, but rather ask the Azimuth contract for its owner
// attribute to ensure transactions get sent to the latest Ecliptic.
// Alternatively, the ENS name ecliptic.eth will resolve to the latest
// Ecliptic as well.
//
// Upgrading happens based on polls held by the senate (galaxy owners).
// Through this contract, the senate can submit proposals, opening polls
// for the senate to cast votes on. These proposals can be either hashes
// of documents or addresses of new Ecliptics.
// If an ecliptic proposal gains majority, this contract will transfer
// ownership of the data storage contracts to that address, so that it may
// operate on the data they contain. This contract will selfdestruct at
// the end of the upgrade process.
//
// This contract implements the ERC721 interface for non-fungible tokens,
// allowing points to be managed using generic clients that support the
// standard. It also implements ERC165 to allow this to be discovered.
//
contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata
{
using SafeMath for uint256;
using AddressUtils for address;
// Transfer: This emits when ownership of any NFT changes by any mechanism.
// This event emits when NFTs are created (`from` == 0) and
// destroyed (`to` == 0). At the time of any transfer, the
// approved address for that NFT (if any) is reset to none.
//
event Transfer(address indexed _from, address indexed _to,
uint256 indexed _tokenId);
// Approval: This emits when the approved address for an NFT is changed or
// reaffirmed. The zero address indicates there is no approved
// address. When a Transfer event emits, this also indicates that
// the approved address for that NFT (if any) is reset to none.
//
event Approval(address indexed _owner, address indexed _approved,
uint256 indexed _tokenId);
// ApprovalForAll: This emits when an operator is enabled or disabled for an
// owner. The operator can manage all NFTs of the owner.
//
event ApprovalForAll(address indexed _owner, address indexed _operator,
bool _approved);
// erc721Received: equal to:
// bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
// which can be also obtained as:
// ERC721Receiver(0).onERC721Received.selector`
bytes4 constant erc721Received = 0x150b7a02;
// depositAddress: Special address respresenting L2. Ships sent to
// this address are controlled on L2 instead of here.
//
address constant public depositAddress =
0x1111111111111111111111111111111111111111;
ITreasuryProxy public treasuryProxy;
// treasuryUpgradeHash
// hash of the treasury implementation to upgrade to
// Note: stand-in, just hash of no bytes
// could be made immutable and passed in as constructor argument
bytes32 constant public treasuryUpgradeHash = hex"26f3eae628fa1a4d23e34b91a4d412526a47620ced37c80928906f9fa07c0774";
bool public treasuryUpgraded = false;
// claims: contract reference, for clearing claims on-transfer
//
Claims public claims;
// constructor(): set data contract addresses and signal interface support
//
// Note: during first deploy, ownership of these data contracts must
// be manually transferred to this contract.
//
constructor(address _previous,
Azimuth _azimuth,
Polls _polls,
Claims _claims,
ITreasuryProxy _treasuryProxy)
EclipticBase(_previous, _azimuth, _polls)
public
{
claims = _claims;
treasuryProxy = _treasuryProxy;
// register supported interfaces for ERC165
//
_registerInterface(0x80ac58cd); // ERC721
_registerInterface(0x5b5e139f); // ERC721Metadata
_registerInterface(0x7f5828d0); // ERC173 (ownership)
}
//
// ERC721 interface
//
// balanceOf(): get the amount of points owned by _owner
//
function balanceOf(address _owner)
public
view
returns (uint256 balance)
{
require(0x0 != _owner);
return azimuth.getOwnedPointCount(_owner);
}
// ownerOf(): get the current owner of point _tokenId
//
function ownerOf(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address owner)
{
uint32 id = uint32(_tokenId);
// this will throw if the owner is the zero address,
// active points always have a valid owner.
//
require(azimuth.isActive(id));
return azimuth.getOwner(id);
}
// exists(): returns true if point _tokenId is active
//
function exists(uint256 _tokenId)
public
view
returns (bool doesExist)
{
return ( (_tokenId < 0x100000000) &&
azimuth.isActive(uint32(_tokenId)) );
}
// safeTransferFrom(): transfer point _tokenId from _from to _to
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public
{
// transfer with empty data
//
safeTransferFrom(_from, _to, _tokenId, "");
}
// safeTransferFrom(): transfer point _tokenId from _from to _to,
// and call recipient if it's a contract
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId,
bytes _data)
public
{
// perform raw transfer
//
transferFrom(_from, _to, _tokenId);
// do the callback last to avoid re-entrancy
//
if (_to.isContract())
{
bytes4 retval = ERC721Receiver(_to)
.onERC721Received(msg.sender, _from, _tokenId, _data);
//
// standard return idiom to confirm contract semantics
//
require(retval == erc721Received);
}
}
// transferFrom(): transfer point _tokenId from _from to _to,
// WITHOUT notifying recipient contract
//
function transferFrom(address _from, address _to, uint256 _tokenId)
public
validPointId(_tokenId)
{
uint32 id = uint32(_tokenId);
require(azimuth.isOwner(id, _from));
// the ERC721 operator/approved address (if any) is
// accounted for in transferPoint()
//
transferPoint(id, _to, true);
}
// approve(): allow _approved to transfer ownership of point
// _tokenId
//
function approve(address _approved, uint256 _tokenId)
public
validPointId(_tokenId)
{
setTransferProxy(uint32(_tokenId), _approved);
}
// setApprovalForAll(): allow or disallow _operator to
// transfer ownership of ALL points
// owned by :msg.sender
//
function setApprovalForAll(address _operator, bool _approved)
public
{
require(0x0 != _operator);
azimuth.setOperator(msg.sender, _operator, _approved);
emit ApprovalForAll(msg.sender, _operator, _approved);
}
// getApproved(): get the approved address for point _tokenId
//
function getApproved(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address approved)
{
//NOTE redundant, transfer proxy cannot be set for
// inactive points
//
require(azimuth.isActive(uint32(_tokenId)));
return azimuth.getTransferProxy(uint32(_tokenId));
}
// isApprovedForAll(): returns true if _operator is an
// operator for _owner
//
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool result)
{
return azimuth.isOperator(_owner, _operator);
}
//
// ERC721Metadata interface
//
// name(): returns the name of a collection of points
//
function name()
external
view
returns (string)
{
return "Azimuth Points";
}
// symbol(): returns an abbreviates name for points
//
function symbol()
external
view
returns (string)
{
return "AZP";
}
// tokenURI(): returns a URL to an ERC-721 standard JSON file
//
function tokenURI(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (string _tokenURI)
{
_tokenURI = "https://azimuth.network/erc721/0000000000.json";
bytes memory _tokenURIBytes = bytes(_tokenURI);
_tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10);
_tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10);
_tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10);
_tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10);
_tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10);
_tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10);
_tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10);
_tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10);
_tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10);
_tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10);
}
//
// Points interface
//
// configureKeys(): configure _point with network public keys
// _encryptionKey, _authenticationKey,
// and corresponding _cryptoSuiteVersion,
// incrementing the point's continuity number if needed
//
function configureKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion,
bool _discontinuous)
external
activePointManager(_point)
onL1(_point)
{
if (_discontinuous)
{
azimuth.incrementContinuityNumber(_point);
}
azimuth.setKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion);
}
// spawn(): spawn _point, then either give, or allow _target to take,
// ownership of _point
//
// if _target is the :msg.sender, _targets owns the _point right away.
// otherwise, _target becomes the transfer proxy of _point.
//
// Requirements:
// - _point must not be active
// - _point must not be a planet with a galaxy prefix
// - _point's prefix must be linked and under its spawn limit
// - :msg.sender must be either the owner of _point's prefix,
// or an authorized spawn proxy for it
//
function spawn(uint32 _point, address _target)
external
{
// only currently unowned (and thus also inactive) points can be spawned
//
require(azimuth.isOwner(_point, 0x0));
// prefix: half-width prefix of _point
//
uint16 prefix = azimuth.getPrefix(_point);
// can't spawn if we deposited ownership or spawn rights to L2
//
require( depositAddress != azimuth.getOwner(prefix) );
require( depositAddress != azimuth.getSpawnProxy(prefix) );
// only allow spawning of points of the size directly below the prefix
//
// this is possible because of how the address space works,
// but supporting it introduces complexity through broken assumptions.
//
// example:
// 0x0000.0000 - galaxy zero
// 0x0000.0100 - the first star of galaxy zero
// 0x0001.0100 - the first planet of the first star
// 0x0001.0000 - the first planet of galaxy zero
//
require( (uint8(azimuth.getPointSize(prefix)) + 1) ==
uint8(azimuth.getPointSize(_point)) );
// prefix point must be linked and able to spawn
//
require( (azimuth.hasBeenLinked(prefix)) &&
( azimuth.getSpawnCount(prefix) <
getSpawnLimit(prefix, block.timestamp) ) );
// the owner of a prefix can always spawn its children;
// other addresses need explicit permission (the role
// of "spawnProxy" in the Azimuth contract)
//
require( azimuth.canSpawnAs(prefix, msg.sender) );
// if the caller is spawning the point to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_point, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern
// making the _point prefix's owner the _point owner in the mean time
//
else
{
doSpawn(_point, _target, false, azimuth.getOwner(prefix));
}
}
// doSpawn(): actual spawning logic, used in spawn(). creates _point,
// making the _target its owner if _direct, or making the
// _holder the owner and the _target the transfer proxy
// if not _direct.
//
function doSpawn( uint32 _point,
address _target,
bool _direct,
address _holder )
internal
{
// register the spawn for _point's prefix, incrementing spawn count
//
azimuth.registerSpawned(_point);
// if the spawn is _direct, assume _target knows what they're doing
// and resolve right away
//
if (_direct)
{
// make the point active and set its new owner
//
azimuth.activatePoint(_point);
azimuth.setOwner(_point, _target);
emit Transfer(0x0, _target, uint256(_point));
}
//
// when spawning indirectly, enforce a withdraw pattern by approving
// the _target for transfer of the _point instead.
// we make the _holder the owner of this _point in the mean time,
// so that it may cancel the transfer (un-approve) if _target flakes.
// we don't make _point active yet, because it still doesn't really
// belong to anyone.
//
else
{
// have _holder hold on to the _point while _target gets to transfer
// ownership of it
//
azimuth.setOwner(_point, _holder);
azimuth.setTransferProxy(_point, _target);
emit Transfer(0x0, _holder, uint256(_point));
emit Approval(_holder, _target, uint256(_point));
}
}
// transferPoint(): transfer _point to _target, clearing all permissions
// data and keys if _reset is true
//
// Note: the _reset flag is useful when transferring the point to
// a recipient who doesn't trust the previous owner.
//
// We know _point is not on L2, since otherwise its owner would be
// depositAddress (which has no operator) and its transfer proxy
// would be zero.
//
// Requirements:
// - :msg.sender must be either _point's current owner, authorized
// to transfer _point, or authorized to transfer the current
// owner's points (as in ERC721's operator)
// - _target must not be the zero address
//
function transferPoint(uint32 _point, address _target, bool _reset)
public
{
// transfer is legitimate if the caller is the current owner, or
// an operator for the current owner, or the _point's transfer proxy
//
require(azimuth.canTransfer(_point, msg.sender));
// can't deposit galaxy to L2
// can't deposit contract-owned point to L2
//
require( depositAddress != _target ||
( azimuth.getPointSize(_point) != Azimuth.Size.Galaxy &&
!azimuth.getOwner(_point).isContract() ) );
// if the point wasn't active yet, that means transferring it
// is part of the "spawn" flow, so we need to activate it
//
if ( !azimuth.isActive(_point) )
{
azimuth.activatePoint(_point);
}
// if the owner would actually change, change it
//
// the only time this deliberately wouldn't be the case is when a
// prefix owner wants to activate a spawned but untransferred child.
//
if ( !azimuth.isOwner(_point, _target) )
{
// remember the previous owner, to be included in the Transfer event
//
address old = azimuth.getOwner(_point);
azimuth.setOwner(_point, _target);
// according to ERC721, the approved address (here, transfer proxy)
// gets cleared during every Transfer event
//
// we also rely on this so that transfer-related functions don't need
// to verify the point is on L1
//
azimuth.setTransferProxy(_point, 0);
emit Transfer(old, _target, uint256(_point));
}
// if we're depositing to L2, clear L1 data so that no proxies
// can be used
//
if ( depositAddress == _target )
{
azimuth.setKeys(_point, 0, 0, 0);
azimuth.setManagementProxy(_point, 0);
azimuth.setVotingProxy(_point, 0);
azimuth.setTransferProxy(_point, 0);
azimuth.setSpawnProxy(_point, 0);
claims.clearClaims(_point);
azimuth.cancelEscape(_point);
}
// reset sensitive data
// used when transferring the point to a new owner
//
else if ( _reset )
{
// clear the network public keys and break continuity,
// but only if the point has already been linked
//
if ( azimuth.hasBeenLinked(_point) )
{
azimuth.incrementContinuityNumber(_point);
azimuth.setKeys(_point, 0, 0, 0);
}
// clear management proxy
//
azimuth.setManagementProxy(_point, 0);
// clear voting proxy
//
azimuth.setVotingProxy(_point, 0);
// clear transfer proxy
//
// in most cases this is done above, during the ownership transfer,
// but we might not hit that and still be expected to reset the
// transfer proxy.
// doing it a second time is a no-op in Azimuth.
//
azimuth.setTransferProxy(_point, 0);
// clear spawning proxy
//
// don't clear if the spawn rights have been deposited to L2,
//
if ( depositAddress != azimuth.getSpawnProxy(_point) )
{
azimuth.setSpawnProxy(_point, 0);
}
// clear claims
//
claims.clearClaims(_point);
}
}
// escape(): request escape as _point to _sponsor
//
// if an escape request is already active, this overwrites
// the existing request
//
// Requirements:
// - :msg.sender must be the owner or manager of _point,
// - _point must be able to escape to _sponsor as per to canEscapeTo()
//
function escape(uint32 _point, uint32 _sponsor)
external
activePointManager(_point)
onL1(_point)
{
// if the sponsor is on L2, we need to escape using L2
//
require( depositAddress != azimuth.getOwner(_sponsor) );
require(canEscapeTo(_point, _sponsor));
azimuth.setEscapeRequest(_point, _sponsor);
}
// cancelEscape(): cancel the currently set escape for _point
//
function cancelEscape(uint32 _point)
external
activePointManager(_point)
{
azimuth.cancelEscape(_point);
}
// adopt(): as the relevant sponsor, accept the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function adopt(uint32 _point)
external
onL1(_point)
{
uint32 request = azimuth.getEscapeRequest(_point);
require( azimuth.isEscaping(_point) &&
azimuth.canManage( request, msg.sender ) );
require( depositAddress != azimuth.getOwner(request) );
// _sponsor becomes _point's sponsor
// its escape request is reset to "not escaping"
//
azimuth.doEscape(_point);
}
// reject(): as the relevant sponsor, deny the _point's request
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function reject(uint32 _point)
external
{
uint32 request = azimuth.getEscapeRequest(_point);
require( azimuth.isEscaping(_point) &&
azimuth.canManage( request, msg.sender ) );
require( depositAddress != azimuth.getOwner(request) );
// reset the _point's escape request to "not escaping"
//
azimuth.cancelEscape(_point);
}
// detach(): as the _sponsor, stop sponsoring the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's current sponsor
//
// We allow detachment even of points that are on L2. This is
// so that a star controlled by a contract can detach from a
// planet which was on L1 originally but now is on L2. L2 will
// ignore this if this is not the actual sponsor anymore (i.e. if
// they later changed their sponsor on L2).
//
function detach(uint32 _point)
external
{
uint32 sponsor = azimuth.getSponsor(_point);
require( azimuth.hasSponsor(_point) &&
azimuth.canManage(sponsor, msg.sender) );
require( depositAddress != azimuth.getOwner(sponsor) );
// signal that its sponsor no longer supports _point
//
azimuth.loseSponsor(_point);
}
//
// Point rules
//
// getSpawnLimit(): returns the total number of children the _point
// is allowed to spawn at _time.
//
function getSpawnLimit(uint32 _point, uint256 _time)
public
view
returns (uint32 limit)
{
Azimuth.Size size = azimuth.getPointSize(_point);
if ( size == Azimuth.Size.Galaxy )
{
return 255;
}
else if ( size == Azimuth.Size.Star )
{
// in 2019, stars may spawn at most 1024 planets. this limit doubles
// for every subsequent year.
//
// Note: 1546300800 corresponds to 2019-01-01
//
uint256 yearsSince2019 = (_time - 1546300800) / 365 days;
if (yearsSince2019 < 6)
{
limit = uint32( 1024 * (2 ** yearsSince2019) );
}
else
{
limit = 65535;
}
return limit;
}
else // size == Azimuth.Size.Planet
{
// planets can create moons, but moons aren't on the chain
//
return 0;
}
}
// canEscapeTo(): true if _point could try to escape to _sponsor
//
function canEscapeTo(uint32 _point, uint32 _sponsor)
public
view
returns (bool canEscape)
{
// can't escape to a sponsor that hasn't been linked
//
if ( !azimuth.hasBeenLinked(_sponsor) ) return false;
// Can only escape to a point one size higher than ourselves,
// except in the special case where the escaping point hasn't
// been linked yet -- in that case we may escape to points of
// the same size, to support lightweight invitation chains.
//
// The use case for lightweight invitations is that a planet
// owner should be able to invite their friends onto an
// Azimuth network in a two-party transaction, without a new
// star relationship.
// The lightweight invitation process works by escaping your
// own active (but never linked) point to one of your own
// points, then transferring the point to your friend.
//
// These planets can, in turn, sponsor other unlinked planets,
// so the "planet sponsorship chain" can grow to arbitrary
// length. Most users, especially deep down the chain, will
// want to improve their performance by switching to direct
// star sponsors eventually.
//
Azimuth.Size pointSize = azimuth.getPointSize(_point);
Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor);
return ( // normal hierarchical escape structure
//
( (uint8(sponsorSize) + 1) == uint8(pointSize) ) ||
//
// special peer escape
//
( (sponsorSize == pointSize) &&
//
// peer escape is only for points that haven't been linked
// yet, because it's only for lightweight invitation chains
//
!azimuth.hasBeenLinked(_point) ) );
}
//
// Permission management
//
// setManagementProxy(): configure the management proxy for _point
//
// The management proxy may perform "reversible" operations on
// behalf of the owner. This includes public key configuration and
// operations relating to sponsorship.
//
function setManagementProxy(uint32 _point, address _manager)
external
activePointManager(_point)
onL1(_point)
{
azimuth.setManagementProxy(_point, _manager);
}
// setSpawnProxy(): give _spawnProxy the right to spawn points
// with the prefix _prefix
//
// takes a uint16 so that we can't set spawn proxy for a planet
//
// fails if spawn rights have been deposited to L2
//
function setSpawnProxy(uint16 _prefix, address _spawnProxy)
external
activePointSpawner(_prefix)
onL1(_prefix)
{
require( depositAddress != azimuth.getSpawnProxy(_prefix) );
azimuth.setSpawnProxy(_prefix, _spawnProxy);
}
// setVotingProxy(): configure the voting proxy for _galaxy
//
// the voting proxy is allowed to start polls and cast votes
// on the point's behalf.
//
function setVotingProxy(uint8 _galaxy, address _voter)
external
activePointVoter(_galaxy)
{
azimuth.setVotingProxy(_galaxy, _voter);
}
// setTransferProxy(): give _transferProxy the right to transfer _point
//
// Requirements:
// - :msg.sender must be either _point's current owner,
// or be an operator for the current owner
//
function setTransferProxy(uint32 _point, address _transferProxy)
public
onL1(_point)
{
// owner: owner of _point
//
address owner = azimuth.getOwner(_point);
// caller must be :owner, or an operator designated by the owner.
//
require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender));
// set transfer proxy field in Azimuth contract
//
azimuth.setTransferProxy(_point, _transferProxy);
// emit Approval event
//
emit Approval(owner, _transferProxy, uint256(_point));
}
//
// Poll actions
//
// startUpgradePoll(): as _galaxy, start a poll for the ecliptic
// upgrade _proposal
//
// Requirements:
// - :msg.sender must be the owner or voting proxy of _galaxy,
// - the _proposal must expect to be upgraded from this specific
// contract, as indicated by its previousEcliptic attribute
//
function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal)
external
activePointVoter(_galaxy)
{
// ensure that the upgrade target expects this contract as the source
//
require(_proposal.previousEcliptic() == address(this));
polls.startUpgradePoll(_proposal);
}
// startDocumentPoll(): as _galaxy, start a poll for the _proposal
//
// the _proposal argument is the keccak-256 hash of any arbitrary
// document or string of text
//
function startDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
activePointVoter(_galaxy)
{
polls.startDocumentPoll(_proposal);
}
// castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic
// upgrade _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
// If this vote results in a majority for the _proposal, it will
// be upgraded to immediately.
//
function castUpgradeVote(uint8 _galaxy,
EclipticBase _proposal,
bool _vote)
external
activePointVoter(_galaxy)
{
// majority: true if the vote resulted in a majority, false otherwise
//
bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// castDocumentVote(): as _galaxy, cast a _vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote)
external
activePointVoter(_galaxy)
{
polls.castDocumentVote(_galaxy, _proposal, _vote);
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, upgrading to it if it has
//
function updateUpgradePoll(EclipticBase _proposal)
external
{
// majority: true if the poll ended in a majority, false otherwise
//
bool majority = polls.updateUpgradePoll(_proposal);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// updateDocumentPoll(): check whether the _proposal has achieved majority
//
// Note: the polls contract publicly exposes the function this calls,
// but we offer it in the ecliptic interface as a convenience
//
function updateDocumentPoll(bytes32 _proposal)
external
{
polls.updateDocumentPoll(_proposal);
}
// upgradeTreasury: upgrade implementation for treasury
//
// Note: we specify when deploying Ecliptic the keccak hash
// of the implementation we're upgrading to
//
function upgradeTreasury(address _treasuryImpl) external {
require(!treasuryUpgraded);
require(keccak256(_treasuryImpl) == treasuryUpgradeHash);
treasuryProxy.upgradeTo(_treasuryImpl);
treasuryUpgraded = true;
}
//
// Contract owner operations
//
// createGalaxy(): grant _target ownership of the _galaxy and register
// it for voting
//
function createGalaxy(uint8 _galaxy, address _target)
external
onlyOwner
{
// only currently unowned (and thus also inactive) galaxies can be
// created, and only to non-zero addresses
//
require( azimuth.isOwner(_galaxy, 0x0) &&
0x0 != _target );
// new galaxy means a new registered voter
//
polls.incrementTotalVoters();
// if the caller is sending the galaxy to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_galaxy, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern,
// making the caller the owner in the mean time
//
else
{
doSpawn(_galaxy, _target, false, msg.sender);
}
}
function setDnsDomains(string _primary, string _secondary, string _tertiary)
external
onlyOwner
{
azimuth.setDnsDomains(_primary, _secondary, _tertiary);
}
//
// Function modifiers for this contract
//
// validPointId(): require that _id is a valid point
//
modifier validPointId(uint256 _id)
{
require(_id < 0x100000000);
_;
}
// onL1(): require that ship is not deposited
modifier onL1(uint32 _point)
{
require( depositAddress != azimuth.getOwner(_point) );
_;
}
}
|
safeTransferFrom(): transfer point _tokenId from _from to _to, and call recipient if it's a contract perform raw transfer do the callback last to avoid re-entrancy standard return idiom to confirm contract semantics
|
function safeTransferFrom(address _from, address _to, uint256 _tokenId,
bytes _data)
public
{
transferFrom(_from, _to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721Receiver(_to)
.onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == erc721Received);
}
}
| 1,053,713 |
./full_match/1/0x9af7612b0706FA299B575699177370515731b412/sources/src/core/Registry.sol
|
Set admini permissions _admin The address of the administrator _isAuthorized A boolean to indicate if the administrator is authorized/
|
function setAdmin(address _admin, bool _isAuthorized) public onlyAdmins {
adminPermissions[_admin] = _isAuthorized;
emit AdminPermissionChanged(_admin, _isAuthorized);
}
| 3,143,242 |
pragma solidity ^0.4.25;
/**
* @author wpzczbyqy <[email protected]>
* @title bytes32类型集合操作
* 提供bytes32集合类型操作,包括新增元素,删除元素,获取元素等
**/
library LibBytes32Set {
struct Bytes32Set {
bytes32[] values;
mapping(bytes32 => uint256) indexes;
}
/**
*@dev byte32集合是否包含某个元素
*@param set bytes32类型集合
*@param val 待验证的值
*@return bool 是否包含该元素,true 包含;false 不包含
**/
function contains(Bytes32Set storage set, bytes32 val) internal view returns (bool) {
return set.indexes[val] != 0;
}
/**
*@dev byte32集合,增加一个元素
*@param set bytes32类型集合
*@param val 待增加的值
*@return bool 是否成功添加了元素
**/
function add(Bytes32Set storage set, bytes32 val) internal view returns (bool) {
if(!contains(set, val)){
set.values.push(val);
set.indexes[val] = set.values.length;
return true;
}
return false;
}
/**
*@dev byte32集合,删除一个元素
*@param set bytes32类型集合
*@param val 待删除的值
*@return bool 是否成功删除了元素
**/
function remove(Bytes32Set storage set, bytes32 val) internal view returns (bool) {
uint256 valueIndex = set.indexes[val];
if(contains(set,val)){
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set.values.length - 1;
if(toDeleteIndex != lastIndex){
bytes32 lastValue = set.values[lastIndex];
set.values[toDeleteIndex] = lastValue;
set.indexes[lastValue] = valueIndex;
}
delete set.values[lastIndex];
delete set.indexes[val];
set.values.length--;
return true;
}
return false;
}
/**
*@dev 获取集合中的所有元素
*@param set bytes32类型集合
*@return bytes32[] 返回集合中的所有元素
**/
function getAll(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return set.values;
}
/**
*@dev 获取集合中元素的数量
*@param set bytes32类型集合
*@return uint256 集合中元素数量
**/
function getSize(Bytes32Set storage set) internal view returns (uint256) {
return set.values.length;
}
/**
*@dev 某个元素在集合中的位置
*@param set bytes32类型集合
*@param val 待查找的值
*@return bool,uint256 是否存在此元素与该元素的位置
**/
function atPosition (Bytes32Set storage set, bytes32 val) internal view returns (bool, uint256) {
if(contains(set, val)){
return (true, set.indexes[val]-1);
}
return (false, 0);
}
/**
*@dev 根据索引获取集合中的元素
*@param set bytes32类型集合
*@param index 索引
*@return bytes32 查找到的元素
**/
function getByIndex(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
require(index < set.values.length,"Index: index out of bounds");
return set.values[index];
}
/**
*@dev 求两个集合的并集 a ∪ b
*@param set a bytes32类型集合
*@param set b bytes32类型集合
*@return bytes32[] 并集元素
**/
function union(Bytes32Set storage a, Bytes32Set storage b) internal view returns (bytes32[]){
if(b.values.length == 0){
return a.values;
}
bool isIn;
for(uint i = 0; i < b.values.length; i++){
isIn = contains(a, b.values[i]);
if(!isIn){
add(a, b.values[i]);
}
}
return a.values;
}
/**
*@dev 求两个集合的差 a - b
*@param set a bytes32类型集合
*@param set b bytes32类型集合
*@return bytes32[] 差集元素
**/
function relative(Bytes32Set storage a, Bytes32Set storage b) internal view returns (bytes32[]){
if(b.values.length == 0){
return a.values;
}
bool isIn;
for(uint i = 0; i < b.values.length; i++){
isIn = contains(a, b.values[i]);
if(isIn){
remove(a,b.values[i]);
}
}
return a.values;
}
/**
*@dev 求两个集合的交集 a ∩ b
*@param set a bytes32类型集合
*@param set b bytes32类型集合
*@return bytes32[] 交集元素
**/
function intersect(Bytes32Set storage a, Bytes32Set storage b) internal view returns (bytes32[]){
if(b.values.length == 0){
return ;
}
bool isIn;
for(uint i = 0; i < a.values.length; i++){
isIn = contains(b, a.values[i]);
if(!isIn){
remove(a,a.values[i]);
}
}
return a.values;
}
}
|
某个元素在集合中的位置 set bytes32类型集合 val 待查找的值return bool,uint256 是否存在此元素与该元素的位置/
|
function atPosition (Bytes32Set storage set, bytes32 val) internal view returns (bool, uint256) {
if(contains(set, val)){
return (true, set.indexes[val]-1);
}
return (false, 0);
}
| 12,743,636 |
./partial_match/1/0x9Ef74F01C70c80f008b51ae434e56EE79B6f4016/sources/MultiChanger.sol
|
solium-disable-next-line security/no-call-value
|
function sendEthProportion(address target, uint256 mul, uint256 div) external {
uint256 value = address(this).balance.mul(mul).div(div);
require(target.call.value(value)());
}
| 9,353,539 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.6;
import "@yield-protocol/vault-interfaces/IJoin.sol";
import "@yield-protocol/utils-v2/contracts/token/IERC20.sol";
import "@yield-protocol/utils-v2/contracts/token/MinimalTransferHelper.sol";
import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol";
import "@yield-protocol/utils-v2/contracts/math/WMul.sol";
import "@yield-protocol/utils-v2/contracts/math/WDiv.sol";
import "@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol";
import "./IBatchAction.sol";
import "./ERC1155.sol";
contract NotionalJoin is IJoin, ERC1155TokenReceiver, AccessControl() {
using WMul for uint256;
using WDiv for uint256;
using CastU256U128 for uint256;
event FlashFeeFactorSet(uint256 indexed fee);
event Redeemed(uint256 fCash, uint256 underlying, uint256 accrual);
bytes32 constant internal FLASH_LOAN_RETURN = keccak256("ERC3156FlashBorrower.onFlashLoan");
uint256 constant public FLASH_LOANS_DISABLED = type(uint256).max;
address public immutable override asset;
address public immutable underlying;
uint40 public immutable maturity; // Maturity date for fCash
uint16 public immutable currencyId; // Notional currency id for the underlying
uint256 public immutable id; // This ERC1155 Join only accepts one id from the ERC1155 token
uint256 public storedBalance; // After maturity, this is reused as the balance for underlying
uint256 public accrual; // fCash to underlying factor, with 18 decimals
uint256 public flashFeeFactor = FLASH_LOANS_DISABLED; // Fee on flash loans, as a percentage in fixed point with 18 decimals. Flash loans disabled by default.
constructor(address asset_, address underlying_, uint40 maturity_, uint16 currencyId_) {
asset = asset_;
underlying = underlying_;
maturity = maturity_;
currencyId = currencyId_;
// TransferAssets.encodeAssetId
id = uint256(
(bytes32(uint256(currencyId_)) << 48) |
(bytes32(uint256(maturity_)) << 8) |
bytes32(uint256(1))
);
}
modifier afterMaturity() {
require(
block.timestamp >= maturity,
"Only after maturity"
);
_;
}
modifier beforeMaturity() {
require(
block.timestamp < maturity,
"Only before maturity"
);
_;
}
/// @dev Advertising through ERC165 the available functions
function supportsInterface(bytes4 interfaceID) external view returns (bool) {
// ERC-165 support = `bytes4(keccak256('supportsInterface(bytes4)'))`.
// ERC-1155 `ERC1155TokenReceiver` support = `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`.
return interfaceID == NotionalJoin.supportsInterface.selector ||
interfaceID == ERC1155TokenReceiver.onERC1155Received.selector ^ ERC1155TokenReceiver.onERC1155BatchReceived.selector;
}
/// @dev Called by the sender after a transfer to verify it was received. Ensures only `id` tokens are received.
function onERC1155Received(
address,
address,
uint256 _id,
uint256,
bytes calldata
) external override returns(bytes4) {
require (_id == id, "Token id not accepted");
return ERC1155TokenReceiver.onERC1155Received.selector;
}
/// @dev Called by the sender after a batch transfer to verify it was received. Ensures only `id` tokens are received.
function onERC1155BatchReceived(
address,
address,
uint256[] calldata _ids,
uint256[] calldata,
bytes calldata
) external override returns(bytes4) {
uint256 length = _ids.length;
for (uint256 i; i < length; ++i)
require (_ids[i] == id, "Token id not accepted");
return ERC1155TokenReceiver.onERC1155BatchReceived.selector;
}
/// @dev Take `amount` `asset` from `user` using `transferFrom`, minus any unaccounted `asset` in this contract.
function join(address user, uint128 amount)
external override
auth
returns (uint128)
{
return _join(user, amount);
}
/// @dev Take `amount` `asset` from `user` using `transferFrom`, minus any unaccounted `asset` in this contract.
function _join(address user, uint128 amount)
internal
beforeMaturity
returns (uint128)
{
ERC1155 token = ERC1155(asset);
uint256 _storedBalance = storedBalance;
uint256 available = token.balanceOf(address(this), id) - _storedBalance; // Fine to panic if this underflows
unchecked {
storedBalance = _storedBalance + amount; // Unlikely that a uint128 added to the stored balance will make it overflow
if (available < amount) token.safeTransferFrom(user, address(this), id, amount - available, "");
}
return amount;
}
/// @dev Before maturity, transfer `amount` `asset` to `user`.
/// After maturity, withdraw if necessary, then transfer `amount.wmul(accrual)` `underlying` to `user`.
function exit(address user, uint128 amount)
external override
auth
returns (uint128)
{
if (block.timestamp < maturity) {
return _exit(user, amount);
} else {
if (accrual == 0) redeem(); // Redeem all fCash, switch to underlying join, set accrual.
return _exitUnderlying(user, uint256(amount).wmul(accrual).u128());
}
}
/// @dev Transfer `amount` `asset` to `user`
function _exit(address user, uint128 amount)
internal
beforeMaturity
returns (uint128)
{
storedBalance -= amount;
ERC1155(asset).safeTransferFrom(address(this), user, id, amount, "");
return amount;
}
/// @dev Transfer `amount` `underlying` to `user`
function _exitUnderlying(address user, uint128 amount)
internal
afterMaturity
returns (uint128)
{
storedBalance -= amount;
MinimalTransferHelper.safeTransfer(IERC20(underlying), user, amount);
return amount;
}
/// @dev Switch to an exit-only underlying Join, converting all fCash holdings to underlying in the process.
function redeem()
public
afterMaturity
{
require (accrual == 0, "Already redeemed");
// Build an action to withdraw all mature fCash into underlying, then withdraw.
IBatchAction.BalanceAction[] memory withdrawActions = new IBatchAction.BalanceAction[](1);
withdrawActions[0] = IBatchAction.BalanceAction({
actionType: IBatchAction.DepositActionType.None,
currencyId: currencyId,
depositActionAmount: 0,
withdrawAmountInternalPrecision: 0,
withdrawEntireCashBalance: true,
redeemToUnderlying: true
});
IBatchAction(asset).batchBalanceAction(address(this), withdrawActions);
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
uint256 storedBalance_ = storedBalance;
accrual = underlyingBalance.wdiv(storedBalance_); // There is a rounding loss here. Some wei will be forever locked in the join.
// This becomes now to an exit-only underlying Join.
storedBalance = underlyingBalance;
emit Redeemed(storedBalance_, underlyingBalance, accrual);
}
/// @dev Retrieve any ERC20 tokens. Useful for airdropped tokens.
function retrieve(IERC20 token, address to)
external
auth
{
require(address(token) != address(underlying), "Use exit for underlying");
MinimalTransferHelper.safeTransfer(token, to, token.balanceOf(address(this)));
}
/// @dev Retrieve any ERC1155 tokens other than the `asset`. Useful for airdropped tokens.
function retrieveERC1155(ERC1155 token, uint256 id_, address to)
external
auth
{
require(address(token) != address(asset) || id_ != id, "Use exit for asset");
token.safeTransferFrom(address(this), to, id_, token.balanceOf(address(this), id_), "");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@yield-protocol/utils-v2/contracts/token/IERC20.sol";
interface IJoin {
/// @dev asset managed by this contract
function asset() external view returns (address);
/// @dev Add tokens to this contract.
function join(address user, uint128 wad) external returns (uint128);
/// @dev Remove tokens to this contract.
function exit(address user, uint128 wad) external returns (uint128);
}
// 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
// Taken from https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
import "./IERC20.sol";
import "../utils/RevertMsgExtractor.sol";
// helper methods for transferring ERC20 tokens that do not consistently return true/false
library MinimalTransferHelper {
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with the underlying revert message if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
if (!(success && (data.length == 0 || abi.decode(data, (bool))))) revert(RevertMsgExtractor.getRevertMsg(data));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes4` identifier. These are expected to be the
* signatures for all the functions in the contract. Special roles should be exposed
* in the external API and be unique:
*
* ```
* bytes4 public constant ROOT = 0x00000000;
* ```
*
* Roles represent restricted access to a function call. For that purpose, use {auth}:
*
* ```
* function foo() public auth {
* ...
* }
* ```
*
* 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 `ROOT`, 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 `ROOT` 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.
*/
contract AccessControl {
struct RoleData {
mapping (address => bool) members;
bytes4 adminRole;
}
mapping (bytes4 => RoleData) private _roles;
bytes4 public constant ROOT = 0x00000000;
bytes4 public constant ROOT4146650865 = 0x00000000; // Collision protection for ROOT, test with ROOT12007226833()
bytes4 public constant LOCK = 0xFFFFFFFF; // Used to disable further permissioning of a function
bytes4 public constant LOCK8605463013 = 0xFFFFFFFF; // Collision protection for LOCK, test with LOCK10462387368()
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role
*
* `ROOT` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call.
*/
event RoleGranted(bytes4 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(bytes4 indexed role, address indexed account, address indexed sender);
/**
* @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members.
* Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore.
*/
constructor () {
_grantRole(ROOT, msg.sender); // Grant ROOT to msg.sender
_setRoleAdmin(LOCK, LOCK); // Create the LOCK role by setting itself as its own admin, creating an independent role tree
}
/**
* @dev Each function in the contract has its own role, identified by their msg.sig signature.
* ROOT can give and remove access to each function, lock any further access being granted to
* a specific action, or even create other roles to delegate admin control over a function.
*/
modifier auth() {
require (_hasRole(msg.sig, msg.sender), "Access denied");
_;
}
/**
* @dev Allow only if the caller has been granted the admin role of `role`.
*/
modifier admin(bytes4 role) {
require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin");
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes4 role, address account) external view returns (bool) {
return _hasRole(role, account);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes4 role) external view returns (bytes4) {
return _getRoleAdmin(role);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
* If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) {
_setRoleAdmin(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(bytes4 role, address account) external virtual admin(role) {
_grantRole(role, account);
}
/**
* @dev Grants all of `role` in `roles` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - For each `role` in `roles`, the caller must have ``role``'s admin role.
*/
function grantRoles(bytes4[] memory roles, address account) external virtual {
for (uint256 i = 0; i < roles.length; i++) {
require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin");
_grantRole(roles[i], account);
}
}
/**
* @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``.
* Emits a {RoleAdminChanged} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function lockRole(bytes4 role) external virtual admin(role) {
_setRoleAdmin(role, LOCK);
}
/**
* @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(bytes4 role, address account) external virtual admin(role) {
_revokeRole(role, account);
}
/**
* @dev Revokes all of `role` in `roles` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - For each `role` in `roles`, the caller must have ``role``'s admin role.
*/
function revokeRoles(bytes4[] memory roles, address account) external virtual {
for (uint256 i = 0; i < roles.length; i++) {
require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin");
_revokeRole(roles[i], account);
}
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes4 role, address account) external virtual {
require(account == msg.sender, "Renounce only for self");
_revokeRole(role, account);
}
function _hasRole(bytes4 role, address account) internal view returns (bool) {
return _roles[role].members[account];
}
function _getRoleAdmin(bytes4 role) internal view returns (bytes4) {
return _roles[role].adminRole;
}
function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual {
if (_getRoleAdmin(role) != adminRole) {
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, adminRole);
}
}
function _grantRole(bytes4 role, address account) internal {
if (!_hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
function _revokeRole(bytes4 role, address account) internal {
if (_hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
library WMul {
// Taken from https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol
/// @dev Multiply an amount by a fixed point factor with 18 decimals, rounds down.
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x * y;
unchecked { z /= 1e18; }
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
library WDiv { // Fixed point arithmetic in 18 decimal units
// Taken from https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol
/// @dev Divide an amount by a fixed point factor with 18 decimals
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = (x * 1e18) / y;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
library CastU256U128 {
/// @dev Safely cast an uint256 to an uint128
function u128(uint256 x) internal pure returns (uint128 y) {
require (x <= type(uint128).max, "Cast overflow");
y = uint128(x);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.6;
interface IBatchAction {
/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades
enum DepositActionType {
// No deposit action
None,
// Deposit asset cash, depositActionAmount is specified in asset cash external precision
DepositAsset,
// Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token
// external precision
DepositUnderlying,
// Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of
// nTokens into the account
DepositAssetAndMintNToken,
// Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens
DepositUnderlyingAndMintNToken,
// Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action
// because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.
RedeemNToken,
// Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in
// Notional internal 8 decimal precision.
ConvertCashToNToken
}
/// @notice Defines a balance action for batchAction
struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
/// @notice Executes a batch of balance transfers including minting and redeeming nTokens.
/// @param account the account for the action
/// @param actions array of balance actions to take, must be sorted by currency id
function batchBalanceAction(address account, BalanceAction[] calldata actions) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Minimalist and gas efficient standard ERC1155 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC1155.sol)
abstract contract ERC1155 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 amount
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] amounts
);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
event URI(string value, uint256 indexed id);
/*///////////////////////////////////////////////////////////////
ERC1155 STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => mapping(uint256 => uint256)) public balanceOf;
mapping(address => mapping(address => bool)) public isApprovedForAll;
/*///////////////////////////////////////////////////////////////
METADATA LOGIC
//////////////////////////////////////////////////////////////*/
function uri(uint256 id) public view virtual returns (string memory);
/*///////////////////////////////////////////////////////////////
ERC1155 LOGIC
//////////////////////////////////////////////////////////////*/
function setApprovalForAll(address operator, bool approved) public virtual {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
require(msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED");
balanceOf[from][id] -= amount;
balanceOf[to][id] += amount;
emit TransferSingle(msg.sender, from, to, id, amount);
require(
to.code.length == 0
? to != address(0)
: ERC1155TokenReceiver(to).onERC1155Received(msg.sender, from, id, amount, data) ==
ERC1155TokenReceiver.onERC1155Received.selector,
"UNSAFE_RECIPIENT"
);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual {
uint256 idsLength = ids.length; // Saves MLOADs.
require(idsLength == amounts.length, "LENGTH_MISMATCH");
require(msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED");
for (uint256 i = 0; i < idsLength; ) {
uint256 id = ids[i];
uint256 amount = amounts[i];
balanceOf[from][id] -= amount;
balanceOf[to][id] += amount;
// An array can't have a total length
// larger than the max uint256 value.
unchecked {
i++;
}
}
emit TransferBatch(msg.sender, from, to, ids, amounts);
require(
to.code.length == 0
? to != address(0)
: ERC1155TokenReceiver(to).onERC1155BatchReceived(msg.sender, from, ids, amounts, data) ==
ERC1155TokenReceiver.onERC1155BatchReceived.selector,
"UNSAFE_RECIPIENT"
);
}
function balanceOfBatch(address[] memory owners, uint256[] memory ids)
public
view
virtual
returns (uint256[] memory balances)
{
uint256 ownersLength = owners.length; // Saves MLOADs.
require(ownersLength == ids.length, "LENGTH_MISMATCH");
balances = new uint256[](owners.length);
// Unchecked because the only math done is incrementing
// the array index counter which cannot possibly overflow.
unchecked {
for (uint256 i = 0; i < ownersLength; i++) {
balances[i] = balanceOf[owners[i]][ids[i]];
}
}
}
/*///////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) {
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155
interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal {
balanceOf[to][id] += amount;
emit TransferSingle(msg.sender, address(0), to, id, amount);
require(
to.code.length == 0
? to != address(0)
: ERC1155TokenReceiver(to).onERC1155Received(msg.sender, address(0), id, amount, data) ==
ERC1155TokenReceiver.onERC1155Received.selector,
"UNSAFE_RECIPIENT"
);
}
function _batchMint(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
uint256 idsLength = ids.length; // Saves MLOADs.
require(idsLength == amounts.length, "LENGTH_MISMATCH");
for (uint256 i = 0; i < idsLength; ) {
balanceOf[to][ids[i]] += amounts[i];
// An array can't have a total length
// larger than the max uint256 value.
unchecked {
i++;
}
}
emit TransferBatch(msg.sender, address(0), to, ids, amounts);
require(
to.code.length == 0
? to != address(0)
: ERC1155TokenReceiver(to).onERC1155BatchReceived(msg.sender, address(0), ids, amounts, data) ==
ERC1155TokenReceiver.onERC1155BatchReceived.selector,
"UNSAFE_RECIPIENT"
);
}
function _batchBurn(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal {
uint256 idsLength = ids.length; // Saves MLOADs.
require(idsLength == amounts.length, "LENGTH_MISMATCH");
for (uint256 i = 0; i < idsLength; ) {
balanceOf[from][ids[i]] -= amounts[i];
// An array can't have a total length
// larger than the max uint256 value.
unchecked {
i++;
}
}
emit TransferBatch(msg.sender, from, address(0), ids, amounts);
}
function _burn(
address from,
uint256 id,
uint256 amount
) internal {
balanceOf[from][id] -= amount;
emit TransferSingle(msg.sender, from, address(0), id, amount);
}
}
/// @notice A generic interface for a contract which properly accepts ERC1155 tokens.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC1155.sol)
interface ERC1155TokenReceiver {
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 amount,
bytes calldata data
) external returns (bytes4);
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/sushiswap/BoringSolidity/blob/441e51c0544cf2451e6116fe00515e71d7c42e2c/contracts/BoringBatchable.sol
pragma solidity >=0.6.0;
library RevertMsgExtractor {
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function getRevertMsg(bytes memory returnData)
internal pure
returns (string memory)
{
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
returnData := add(returnData, 0x04)
}
return abi.decode(returnData, (string)); // All that remains is the revert string
}
}
|
Retrieve any ERC1155 tokens other than the `asset`. Useful for airdropped tokens.
|
function retrieveERC1155(ERC1155 token, uint256 id_, address to)
external
auth
{
require(address(token) != address(asset) || id_ != id, "Use exit for asset");
token.safeTransferFrom(address(this), to, id_, token.balanceOf(address(this), id_), "");
}
| 589,859 |
// SPDX-License-Identifier: MIT
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 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 {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) 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 granted `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}.
* ====
*/
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);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
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
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
//SPDX-License-Identifier: MIT
/**
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./interfaces/IVestedNil.sol";
import "./interfaces/INOwnerResolver.sol";
import "./interfaces/INilPass.sol";
import "./interfaces/IArtistMiningCalculator.sol";
/**
* @title MasterMint contract
* @author Nil DAO
* @notice This contract wraps actual minting contracts and performs administrative functions
*/
contract MasterMint is ReentrancyGuard, AccessControl, INOwnerResolver {
using SafeCast for uint256;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR");
enum MintStatus {
NONE,
PENDING,
OPEN,
PAUSED
}
struct MintState {
uint128 nMinted;
uint128 totalPaidInWei;
uint128 artistMiningWithdrawn;
uint128 paymentWithdrawn;
uint32 artistMiningThreshold;
uint16 protocolFeesInBPS;
INilPass nilPass;
MintStatus status;
address creator;
IArtistMiningCalculator calculator;
}
struct MintPaymentState {
uint32 nMinted;
uint112 nPaid;
uint112 totalPaidInWei;
}
struct MintWithdrawalState {
uint128 artistMiningWithdrawn;
uint128 paymentWithdrawn;
}
struct MintMetadata {
uint32 artistMiningThreshold;
uint16 artistMiningPaymentThresholdInETH;
uint16 protocolFeesInBPS;
uint16 curationFeesInBPS;
INilPass nilPass;
MintStatus status;
address creator;
IArtistMiningCalculator calculator;
}
struct ProtocolConfiguration {
uint16 protocolFeesInBPS;
uint16 curationFeesInBPS;
uint16 artistMiningHighWatermark;
uint16 artistMiningThresholdInBPS;
uint16 artistMiningPaymentThresholdInETH;
uint128 maxNilMintable;
}
MintMetadata[] public mintsMetadata;
MintPaymentState[] public payments;
MintWithdrawalState[] public withdrawals;
IVestedNil public immutable vNil;
INOwnerResolver public immutable nOwnerResolver;
IArtistMiningCalculator public calculator;
address public protocolFeesPayoutAccount;
address public curationFeesPayoutAccount;
ProtocolConfiguration public configuration;
uint128 public totalNilMinted;
uint256 public feesCollectable;
uint128 public nilCollectable;
event MintAdded(uint256 mintId, MintMetadata metadata);
event MintReplaced(uint256 mintId, MintMetadata metadata);
constructor(
IVestedNil vNil_,
INOwnerResolver nOwnerResolver_,
IArtistMiningCalculator calculator_,
ProtocolConfiguration memory configuration_,
address dao
) {
require(address(vNil_) != address(0), "MasterMint:ILLEGAL_NIL_ADDRESS");
require(address(dao) != address(0), "MasterMint:ILLEGAL_DAO_ADDRESS");
_setupRole(OPERATOR_ROLE, dao);
_setupRole(ADMIN_ROLE, dao);
_setRoleAdmin(OPERATOR_ROLE, ADMIN_ROLE);
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_setupRole(OPERATOR_ROLE, msg.sender);
_setupRole(ADMIN_ROLE, msg.sender); // This will be surrendered after deployment
vNil = vNil_;
nOwnerResolver = nOwnerResolver_;
setCalculator(calculator_);
setConfiguration(configuration_);
}
modifier onlyOperator() {
require(hasRole(OPERATOR_ROLE, msg.sender), "MasterMint:ACCESS_DENIED");
_;
}
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, msg.sender), "MasterMint:ACCESS_DENIED");
_;
}
/**
* @notice Adds a mint
* @param nilPass NFT to mint
* @param creator Creator of the NFT
*/
function addMint(INilPass nilPass, address creator) external onlyOperator {
MintMetadata memory metadata = _createMint(nilPass, creator);
mintsMetadata.push(metadata);
payments.push(MintPaymentState(0, 0, 0));
withdrawals.push(MintWithdrawalState(0, 0));
emit MintAdded(mintsMetadata.length - 1, metadata);
}
/**
* @notice Edit a mint
* @param nilPass NFT to mint
* @param creator Creator of the NFT
*/
function replaceMint(
uint256 mintId,
INilPass nilPass,
address creator
) external onlyOperator {
require(mintId < mintsMetadata.length, "MasterMint:ILLEGAL_MINT_ID");
MintMetadata memory metadata = mintsMetadata[mintId];
require(metadata.status == MintStatus.PENDING, "MasterMint:ILLEGAL_STATUS");
metadata = _createMint(nilPass, creator);
mintsMetadata[mintId] = metadata;
emit MintReplaced(mintId, metadata);
}
function _createMint(INilPass nilPass, address creator) internal view returns (MintMetadata memory) {
require(address(nilPass) != address(0), "MasterMint:INVALID_DROP");
require(creator != address(0), "MasterMint:INVALID_CREATOR");
return
MintMetadata({
artistMiningThreshold: calculateThreshold(nilPass).toUint32(),
artistMiningPaymentThresholdInETH: configuration.artistMiningPaymentThresholdInETH,
protocolFeesInBPS: configuration.protocolFeesInBPS,
curationFeesInBPS: configuration.curationFeesInBPS,
nilPass: nilPass,
creator: creator,
status: MintStatus.PENDING,
calculator: calculator
});
}
function calculateThreshold(INilPass nilPass) public view returns (uint256 artistMiningThreshold) {
artistMiningThreshold = (configuration.artistMiningThresholdInBPS * nilPass.maxTotalSupply()) / 10000;
artistMiningThreshold = Math.min(artistMiningThreshold, configuration.artistMiningHighWatermark);
}
function setMintCreator(uint256 mintId, address newCreator) external {
MintMetadata storage metadata = mintsMetadata[mintId];
require(msg.sender == metadata.creator, "MasterMint:ACCESS_DENIED");
require(newCreator != address(0), "MasterMint:ILLEGAL_ADDRESS");
metadata.creator = newCreator;
}
function setMintStatus(uint256 mintId, MintStatus status) external onlyOperator {
require(mintId < mintsMetadata.length, "MasterMint:ILLEGAL_MINT_ID");
MintMetadata storage metadata = mintsMetadata[mintId];
require(status > MintStatus.PENDING, "MasterMint:ILLEGAL_STATUS");
metadata.status = status;
}
function mintWithN(uint256 mintId, uint256[] calldata tokenIds) external payable virtual nonReentrant {
MintMetadata storage metadata = mintsMetadata[mintId];
MintPaymentState memory payment = payments[mintId];
require(metadata.status == MintStatus.OPEN, "MasterMint:MINT_NOT_ACTIVE");
for (uint256 i = 0; i < tokenIds.length; i++) {
require(nOwnerResolver.ownerOf(tokenIds[i]) == msg.sender, "MasterMint:NOT_N_OWNER");
}
payment.totalPaidInWei += toUint112(msg.value);
payment.nPaid += toUint112(msg.value);
payment.nMinted += tokenIds.length.toUint32();
payments[mintId] = payment;
metadata.nilPass.mintWithN(msg.sender, tokenIds, msg.value);
}
function mint(uint256 mintId, uint8 amount) external payable virtual nonReentrant {
MintMetadata storage metadata = mintsMetadata[mintId];
require(metadata.status == MintStatus.OPEN, "MasterMint:MINT_NOT_ACTIVE");
payments[mintId].totalPaidInWei += toUint112(msg.value);
metadata.nilPass.mint(msg.sender, amount, msg.value);
}
function mintTokenIds(uint256 mintId, uint256[] calldata tokenIds) external payable virtual nonReentrant {
MintMetadata storage metadata = mintsMetadata[mintId];
require(metadata.status == MintStatus.OPEN, "MasterMint:MINT_NOT_ACTIVE");
payments[mintId].totalPaidInWei += toUint112(msg.value);
metadata.nilPass.mintTokenId(msg.sender, tokenIds, msg.value);
}
function mints(uint256 mintId) external view returns (MintState memory) {
MintMetadata memory metadata = mintsMetadata[mintId];
MintPaymentState memory paymentData = payments[mintId];
MintWithdrawalState memory withdrawal = withdrawals[mintId];
return
MintState({
nMinted: paymentData.nMinted,
totalPaidInWei: paymentData.totalPaidInWei,
artistMiningWithdrawn: withdrawal.artistMiningWithdrawn,
paymentWithdrawn: withdrawal.paymentWithdrawn,
artistMiningThreshold: metadata.artistMiningThreshold,
protocolFeesInBPS: metadata.protocolFeesInBPS,
nilPass: metadata.nilPass,
status: metadata.status,
creator: metadata.creator,
calculator: metadata.calculator
});
}
function creatorWithdraw(uint256 mintId, bool withNil) external nonReentrant {
MintPaymentState memory paymentState = payments[mintId];
MintMetadata memory metadata = mintsMetadata[mintId];
MintWithdrawalState memory withdrawal = withdrawals[mintId];
require(msg.sender == metadata.creator || hasRole(OPERATOR_ROLE, msg.sender), "MasterMint:ACCESS_DENIED");
require(metadata.status == MintStatus.OPEN, "MasterMint:ILLEGAL_STATE");
if (withNil) {
_mintNil(mintId, metadata);
}
uint128 newSalesProceeds = paymentState.totalPaidInWei - withdrawal.paymentWithdrawn;
if (newSalesProceeds > 0) {
uint256 fees = (metadata.protocolFeesInBPS * newSalesProceeds) / 10000;
feesCollectable += fees;
withdrawals[mintId].paymentWithdrawn += newSalesProceeds;
payable(metadata.creator).transfer((newSalesProceeds - fees));
}
}
function protocolWithdraw(bool withNil) external nonReentrant onlyOperator {
if (nilCollectable > 0 && withNil) {
require(curationFeesPayoutAccount != address(0), "MasterMint:INVALID_CURATION_ADDRESS");
vNil.mint(curationFeesPayoutAccount, nilCollectable);
nilCollectable = 0;
}
if (feesCollectable > 0) {
require(protocolFeesPayoutAccount != address(0), "MasterMint:INVALID_PROTOCOL_ADDRESS");
uint256 toCollect = feesCollectable;
feesCollectable = 0;
payable(protocolFeesPayoutAccount).transfer(toCollect);
}
}
function _mintNil(uint256 mintId, MintMetadata memory metadata) internal {
MintPaymentState memory paymentState = payments[mintId];
MintWithdrawalState memory withdrawal = withdrawals[mintId];
if (
paymentState.nMinted > metadata.artistMiningThreshold &&
paymentState.nPaid > (metadata.artistMiningPaymentThresholdInETH * 1 ether)
) {
uint128 artistMining = Math
.min(
metadata.calculator.calculateArtistMining(mintId, paymentState.totalPaidInWei),
configuration.maxNilMintable - totalNilMinted
)
.toUint128();
// At the end of the AM programme there might be a case where the artist mining amount is actually
// less than what has been already withdrawn, because we have a global cap on the total AM amount
uint128 nilToMint = artistMining > withdrawal.artistMiningWithdrawn
? artistMining - withdrawal.artistMiningWithdrawn
: 0;
if (nilToMint > 0) {
totalNilMinted += nilToMint;
withdrawals[mintId].artistMiningWithdrawn += nilToMint;
uint128 fees = (metadata.curationFeesInBPS * nilToMint) / 10000;
nilCollectable += fees;
vNil.mint(metadata.creator, (nilToMint - fees));
}
}
}
function setProtocolFeesPayoutAccount(address newProtocolFeesPayoutAccount) external onlyAdmin {
protocolFeesPayoutAccount = newProtocolFeesPayoutAccount;
}
function setCurationFeesPayoutAccount(address newCurationFeesPayoutAccount) external onlyAdmin {
curationFeesPayoutAccount = newCurationFeesPayoutAccount;
}
function setCalculator(IArtistMiningCalculator calculator_) public onlyAdmin {
require(address(calculator_) != address(0), "MasterMint:INVALID_ADDRESS");
calculator = calculator_;
}
function setConfiguration(ProtocolConfiguration memory configuration_) public onlyAdmin {
require(configuration_.protocolFeesInBPS < 2000, "MasterMint:INVALID_PROTOCOL_FEES");
require(configuration_.curationFeesInBPS < 2000, "MasterMint:INVALID_CURATION_FEES");
require(configuration_.artistMiningHighWatermark < 8888, "MasterMint:INVALID_HIGH_WM_H");
require(configuration_.artistMiningHighWatermark > 0, "MasterMint:INVALID_HIGH_WM_L");
require(configuration_.artistMiningThresholdInBPS < 10000, "MasterMint:INVALID_THRESHOLD_H");
require(configuration_.artistMiningThresholdInBPS > 0, "MasterMint:INVALID_THRESHOLD_L");
require(configuration_.artistMiningPaymentThresholdInETH < 100, "MasterMint:INVALID_ETH_THRESHOLD");
configuration = configuration_;
}
function getNumberOfMints() external view returns (uint256) {
return mintsMetadata.length;
}
function ownerOf(uint256 nid) external view override returns (address) {
return nOwnerResolver.ownerOf(nid);
}
function balanceOf(address account) external view override returns (uint256) {
return nOwnerResolver.balanceOf(account);
}
function nOwned(address owner) external view override returns (uint256[] memory) {
return nOwnerResolver.nOwned(owner);
}
function tokenExists(uint256 mintId, uint256 tokenId) external view returns (bool) {
MintMetadata storage metadata = mintsMetadata[mintId];
if (address(metadata.nilPass) == address(0)) return false;
return metadata.nilPass.tokenExists(tokenId);
}
function tokensExist(uint256 mintId, uint256[] calldata tokenIds) external view returns (bool[] memory) {
bool[] memory result = new bool[](tokenIds.length);
MintMetadata storage metadata = mintsMetadata[mintId];
if (address(metadata.nilPass) == address(0)) return result;
for (uint256 i = 0; i < tokenIds.length; i++) {
result[i] = metadata.nilPass.tokenExists(tokenIds[i]);
}
return result;
}
function tokensOwned(uint256 mintId, address owner) external view returns (uint256[] memory) {
MintMetadata storage metadata = mintsMetadata[mintId];
if (address(metadata.nilPass) == address(0)) return new uint256[](0);
INilPass nilPass = metadata.nilPass;
uint256 balance = nilPass.balanceOf(owner);
uint256[] memory result = new uint256[](balance);
for (uint256 i = 0; i < balance; i++) {
result[i] = nilPass.tokenOfOwnerByIndex(owner, i);
}
return result;
}
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
receive() external payable virtual {
feesCollectable += msg.value;
}
}
// SPDX-License-Identifier: MIT
/**
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
pragma solidity 0.8.6;
interface IArtistMiningCalculator {
function calculateArtistMining(uint256 mintNumber, uint128 proceedsInWei) external returns (uint256);
}
// SPDX-License-Identifier: MIT
/**
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
pragma solidity 0.8.6;
interface INOwnerResolver {
function ownerOf(uint256 nid) external view returns (address);
function balanceOf(address account) external view returns (uint256);
function nOwned(address owner) external view returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT
/**
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "./IPricingStrategy.sol";
interface INilPass is IERC721Enumerable, IERC721Metadata, IPricingStrategy {
struct MintParams {
uint256 reservedAllowance;
uint256 maxTotalSupply;
uint256 nHoldersMintsAvailable;
uint256 openMintsAvailable;
uint256 totalMintsAvailable;
uint256 nHolderPriceInWei;
uint256 openPriceInWei;
uint256 totalSupply;
uint256 maxMintAllowance;
bool onlyNHolders;
bool supportsTokenId;
}
function mint(
address recipient,
uint8 amount,
uint256 paid
) external;
function mintTokenId(
address recipient,
uint256[] calldata tokenIds,
uint256 paid
) external;
function mintWithN(
address recipient,
uint256[] calldata tokenIds,
uint256 paid
) external;
function maxTotalSupply() external view returns (uint256);
function mintParameters() external view returns (MintParams memory);
function tokenExists(uint256 tokenId) external view returns (bool);
function canMint(address account) external view returns (bool);
}
// SPDX-License-Identifier: MIT
/**
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
pragma solidity 0.8.6;
interface IPricingStrategy {
/**
* @notice Returns the next price for an N mint
*/
function getNextPriceForNHoldersInWei(uint256 numberOfMints) external view returns (uint256);
/**
* @notice Returns the next price for an open mint
*/
function getNextPriceForOpenMintInWei(uint256 numberOfMints) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
/**
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVestedNil is IERC20 {
function multiMint(address[] calldata accounts, uint256[] calldata amounts) external;
function mint(address account, uint256 amount) external;
function claim(address account) external;
function claimAndStake() external;
function vestedOf(address account) external view returns (uint256);
function claimableOf(address account) external view returns (uint256);
}
|
Adds a mint nilPass NFT to mint creator Creator of the NFT/
|
function addMint(INilPass nilPass, address creator) external onlyOperator {
MintMetadata memory metadata = _createMint(nilPass, creator);
mintsMetadata.push(metadata);
payments.push(MintPaymentState(0, 0, 0));
withdrawals.push(MintWithdrawalState(0, 0));
emit MintAdded(mintsMetadata.length - 1, metadata);
}
| 5,877,907 |
pragma solidity 0.6.12;
import "./base/Address.sol";
import "./base/Controller.sol";
import "./base/EternalStorage.sol";
import './base/IERC20.sol';
import "./base/IDiamondFacet.sol";
import "./base/AccessControl.sol";
import "./base/IPolicyTreasuryConstants.sol";
import "./base/IPolicyCoreFacet.sol";
import "./base/IPolicyTranchTokensFacet.sol";
import ".//PolicyFacetBase.sol";
import "./base/SafeMath.sol";
import "./TranchToken.sol";
import "./base/ReentrancyGuard.sol";
/**
* @dev Core policy logic
*/
contract PolicyCoreFacet is EternalStorage, Controller, IDiamondFacet, IPolicyCoreFacet, PolicyFacetBase, IPolicyTreasuryConstants, ReentrancyGuard {
using SafeMath for uint;
using Address for address;
// Modifiers //
modifier assertIsOwner () {
require(inRoleGroup(msg.sender, ROLEGROUP_POLICY_OWNERS), 'must be policy owner');
_;
}
modifier assertCreatedState () {
require(dataUint256["state"] == POLICY_STATE_CREATED, 'must be in created state');
_;
}
/**
* Constructor
*/
constructor (address _settings) Controller(_settings) public {
// nothing
}
// IDiamondFacet
function getSelectors () public pure override returns (bytes memory) {
return abi.encodePacked(
IPolicyCoreFacet.createTranch.selector,
IPolicyCoreFacet.markAsReadyForApproval.selector,
IPolicyCoreFacet.getInfo.selector,
IPolicyCoreFacet.getTranchInfo.selector,
IPolicyCoreFacet.calculateMaxNumOfPremiums.selector,
IPolicyCoreFacet.initiationDateHasPassed.selector,
IPolicyCoreFacet.startDateHasPassed.selector,
IPolicyCoreFacet.maturationDateHasPassed.selector,
IPolicyCoreFacet.checkAndUpdateState.selector
);
}
// IPolicyCore //
function createTranch (
uint256 _numShares,
uint256 _pricePerShareAmount,
uint256[] calldata _premiums
)
external
override
assertIsOwner
assertCreatedState
{
require(_numShares > 0, 'invalid num of shares');
require(_pricePerShareAmount > 0, 'invalid price');
// tranch count
uint256 i = dataUint256["numTranches"];
dataUint256["numTranches"] = i + 1;
require(dataUint256["numTranches"] <= 99, 'max tranches reached');
// setup initial data for tranch
dataUint256[__i(i, "numShares")] = _numShares;
dataUint256[__i(i, "pricePerShareAmount")] = _pricePerShareAmount;
// iterate through premiums and figure out what needs to paid and when
uint256 nextPayTime = dataUint256["initiationDate"];
uint256 numPremiums = 0;
for (uint256 p = 0; _premiums.length > p; p += 1) {
// we only care about premiums > 0
if (_premiums[p] > 0) {
dataUint256[__ii(i, numPremiums, "premiumAmount")] = _premiums[p];
dataUint256[__ii(i, numPremiums, "premiumDueAt")] = nextPayTime;
numPremiums += 1;
}
// the premium interval still counts
nextPayTime += dataUint256["premiumIntervalSeconds"];
}
// save total premiums
require(numPremiums <= calculateMaxNumOfPremiums(), 'too many premiums');
dataUint256[__i(i, "numPremiums")] = numPremiums;
// deploy token contract
TranchToken t = new TranchToken(address(this), i);
// initial holder
address holder = dataAddress["treasury"];
string memory initialHolderKey = __i(i, "initialHolder");
dataAddress[initialHolderKey] = holder;
// set initial holder balance
string memory contractBalanceKey = __ia(i, dataAddress[initialHolderKey], "balance");
dataUint256[contractBalanceKey] = _numShares;
// save reference
string memory addressKey = __i(i, "address");
dataAddress[addressKey] = address(t);
emit CreateTranch(address(t), dataAddress[initialHolderKey], i);
}
function markAsReadyForApproval()
external
override
assertCreatedState
assertIsOwner
{
_setPolicyState(POLICY_STATE_READY_FOR_APPROVAL);
}
function getInfo () public view override returns (
address treasury_,
uint256 initiationDate_,
uint256 startDate_,
uint256 maturationDate_,
address unit_,
uint256 premiumIntervalSeconds_,
uint256 brokerCommissionBP_,
uint256 claimsAdminCommissionBP_,
uint256 naymsCommissionBP_,
uint256 numTranches_,
uint256 state_
) {
treasury_ = dataAddress["treasury"];
initiationDate_ = dataUint256["initiationDate"];
startDate_ = dataUint256["startDate"];
maturationDate_ = dataUint256["maturationDate"];
unit_ = dataAddress["unit"];
premiumIntervalSeconds_ = dataUint256["premiumIntervalSeconds"];
brokerCommissionBP_ = dataUint256["brokerCommissionBP"];
claimsAdminCommissionBP_ = dataUint256["claimsAdminCommissionBP"];
naymsCommissionBP_ = dataUint256["naymsCommissionBP"];
numTranches_ = dataUint256["numTranches"];
state_ = dataUint256["state"];
}
function getTranchInfo (uint256 _index) public view override returns (
address token_,
uint256 state_,
uint256 numShares_,
uint256 initialPricePerShare_,
uint256 balance_,
uint256 sharesSold_,
uint256 initialSaleOfferId_,
uint256 finalBuybackofferId_
) {
token_ = dataAddress[__i(_index, "address")];
state_ = dataUint256[__i(_index, "state")];
numShares_ = dataUint256[__i(_index, "numShares")];
initialPricePerShare_ = dataUint256[__i(_index, "pricePerShareAmount")];
balance_ = dataUint256[__i(_index, "balance")];
sharesSold_ = dataUint256[__i(_index, "sharesSold")];
initialSaleOfferId_ = dataUint256[__i(_index, "initialSaleOfferId")];
finalBuybackofferId_ = dataUint256[__i(_index, "finalBuybackOfferId")];
}
function initiationDateHasPassed () public view override returns (bool) {
return block.timestamp >= dataUint256["initiationDate"];
}
function startDateHasPassed () public view override returns (bool) {
return block.timestamp >= dataUint256["startDate"];
}
function maturationDateHasPassed () public view override returns (bool) {
return block.timestamp >= dataUint256["maturationDate"];
}
// heartbeat function!
function checkAndUpdateState() public override nonReentrant {
// past the initiation date
if (initiationDateHasPassed()) {
// past the start date
if (startDateHasPassed()) {
_ensureTranchesAreUpToDate();
_activatePolicyIfPending();
// if past the maturation date
if (maturationDateHasPassed()) {
_maturePolicy();
}
}
// not yet past start date
else {
_cancelPolicyIfNotFullyApproved();
_beginPolicySaleIfNotYetStarted();
}
}
}
function calculateMaxNumOfPremiums() public view override returns (uint256) {
return (dataUint256["maturationDate"] - dataUint256["initiationDate"]) / dataUint256["premiumIntervalSeconds"] + 1;
}
// Internal methods
function _cancelTranchMarketOffer(uint _index) private {
uint256 initialSaleOfferId = dataUint256[__i(_index, "initialSaleOfferId")];
_getTreasury().cancelOrder(initialSaleOfferId);
}
function _cancelPolicyIfNotFullyApproved() private {
if (dataUint256["state"] == POLICY_STATE_CREATED || dataUint256["state"] == POLICY_STATE_IN_APPROVAL) {
_setPolicyState(POLICY_STATE_CANCELLED);
}
}
function _beginPolicySaleIfNotYetStarted() private {
if (dataUint256["state"] == POLICY_STATE_APPROVED) {
bool allReady = true;
// check every tranch
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
allReady = allReady && (0 >= _getNumberOfTranchPaymentsMissed(i));
}
// stop processing if some tranch payments have been missed
if (!allReady) {
return;
}
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
// tranch/token address
address tranchAddress = dataAddress[__i(i, "address")];
// get supply
uint256 totalSupply = IPolicyTranchTokensFacet(address(this)).tknTotalSupply(i);
// calculate sale values
uint256 pricePerShare = dataUint256[__i(i, "pricePerShareAmount")];
uint256 totalPrice = totalSupply.mul(pricePerShare);
// set tranch state
_setTranchState(i, TRANCH_STATE_SELLING);
// offer tokens in initial sale
dataUint256[__i(i, "initialSaleOfferId")] = _getTreasury().createOrder(
ORDER_TYPE_TOKEN_SALE,
tranchAddress,
totalSupply,
dataAddress["unit"],
totalPrice
);
}
// set policy state to selling
_setPolicyState(POLICY_STATE_INITIATED);
}
}
function _activatePolicyIfPending() private {
// make policy active if necessary
if (dataUint256["state"] == POLICY_STATE_INITIATED) {
// calculate total collateral requried
uint256 minPolicyCollateral = 0;
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
if (dataUint256[__i(i, "state")] == TRANCH_STATE_ACTIVE) {
minPolicyCollateral += dataUint256[__i(i, "sharesSold")] * dataUint256[__i(i, "pricePerShareAmount")];
}
}
// set min. collateral balance to treasury
_getTreasury().setMinPolicyBalance(minPolicyCollateral);
// update policy state
_setPolicyState(POLICY_STATE_ACTIVE);
}
}
function _ensureTranchesAreUpToDate() private {
// check state of each tranch
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
uint256 state = dataUint256[__i(i, "state")];
// if tranch not yet fully sold OR if a payment has been missed
if (state == TRANCH_STATE_SELLING || 0 < _getNumberOfTranchPaymentsMissed(i)) {
// set state to cancelled
// (do this before cancelling market order otherwise _transfer() logic goes haywire)
_setTranchState(i, TRANCH_STATE_CANCELLED);
// cancel any outstanding market order
_cancelTranchMarketOffer(i);
}
}
}
function _maturePolicy () private {
// if no pending claims
if (0 == dataUint256["claimsPendingCount"] && _getTreasury().isPolicyCollateralized(address(this))) {
// if we haven't yet initiated tranch buyback
if (!dataBool["buybackInitiated"]) {
_setPolicyState(POLICY_STATE_BUYBACK);
dataBool["buybackInitiated"] = true;
// buy back all tranch tokens
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
if (dataUint256[__i(i, "state")] == TRANCH_STATE_ACTIVE) {
_setTranchState(i, TRANCH_STATE_MATURED);
}
address unitAddress = dataAddress["unit"];
uint256 tranchBalance = dataUint256[__i(i, "balance")];
// buy back all sold tokens
dataUint256[__i(i, "finalBuybackOfferId")] = _getTreasury().createOrder(
ORDER_TYPE_TOKEN_BUYBACK,
unitAddress,
tranchBalance,
dataAddress[__i(i, "address")],
dataUint256[__i(i, "sharesSold")]
);
}
}
}
// if there are pending claims
else {
_setPolicyState(POLICY_STATE_MATURED);
}
}
}
|
if no pending claims if we haven't yet initiated tranch buyback buy back all tranch tokens if there are pending claims
|
function _maturePolicy () private {
if (0 == dataUint256["claimsPendingCount"] && _getTreasury().isPolicyCollateralized(address(this))) {
if (!dataBool["buybackInitiated"]) {
_setPolicyState(POLICY_STATE_BUYBACK);
dataBool["buybackInitiated"] = true;
for (uint256 i = 0; dataUint256["numTranches"] > i; i += 1) {
if (dataUint256[__i(i, "state")] == TRANCH_STATE_ACTIVE) {
_setTranchState(i, TRANCH_STATE_MATURED);
}
address unitAddress = dataAddress["unit"];
uint256 tranchBalance = dataUint256[__i(i, "balance")];
ORDER_TYPE_TOKEN_BUYBACK,
unitAddress,
tranchBalance,
dataAddress[__i(i, "address")],
dataUint256[__i(i, "sharesSold")]
);
}
}
}
else {
_setPolicyState(POLICY_STATE_MATURED);
}
}
| 12,668,137 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract SaltyPirateCrew is ERC721, Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
using ECDSA for bytes32;
uint256 public constant MAX_SUPPLY = 3000;
uint256 public constant GIFT_BUFFER = 67;
uint256 public constant PRICE = 1;
uint256 public constant SNAPSHOT = 232;
Counters.Counter private _tokenIdCounter;
Counters.Counter public giftsSent;
Counters.Counter public _snapshotCounter;
address private signer;
uint256 public maxPresaleMint;
string public baseURI;
enum ContractState { PAUSED, PRESALE1, PRESALE2, PUBLIC }
ContractState public currentState = ContractState.PAUSED;
mapping(address => uint256) public whitelist;
constructor(
address _signer,
uint256 _maxPresaleMint,
string memory _URI) ERC721("SaltyPirateCrew", "SPC") {
signer = _signer;
maxPresaleMint = _maxPresaleMint;
baseURI = _URI;
}
// Verifies that the sender is whitelisted
function _verify(address sender, bytes memory signature) internal view returns (bool) {
return keccak256(abi.encodePacked(sender))
.toEthSignedMessageHash()
.recover(signature) == signer;
}
function setBaseURI(string memory _URI) public onlyOwner {
baseURI = _URI;
}
function giftsRemaining() public view returns (uint256) {
return GIFT_BUFFER - giftsSent.current();
}
// Returns the total supply minted
function totalSupply() public view returns (uint256) {
return _tokenIdCounter.current() + _snapshotCounter.current();
}
// Sets a new contract state: PAUSED, PRESALE1, PRESALE2, PUBLIC.
function setContractState(ContractState _newState) external onlyOwner {
currentState = _newState;
}
// Sets a new maximum for presale minting
function setMaxPresaleMint(uint256 _newMaxPresaleMint) external onlyOwner {
maxPresaleMint = _newMaxPresaleMint;
}
function airdrop(uint256 airdropAmount, address to) public onlyOwner {
require(airdropAmount > 0, "Airdrop != 0");
require(_snapshotCounter.current() + airdropAmount <= SNAPSHOT, "Airdrop > Max");
for(uint i = 0; i < airdropAmount; i++) {
uint256 tokenId = _snapshotCounter.current();
_snapshotCounter.increment();
_safeMint(to, tokenId);
}
}
// Gift function that will send the address passed the gift amount
function gift(uint256 giftAmount, address to) public onlyOwner {
require(giftAmount > 0, "Gift != 0");
require(giftsSent.current() + giftAmount <= GIFT_BUFFER, "Gifting exceeded");
require(giftAmount + _tokenIdCounter.current() <= MAX_SUPPLY - SNAPSHOT , "Gift > Max");
for(uint i = 0; i < giftAmount; i++) {
uint256 tokenId = _tokenIdCounter.current() + SNAPSHOT;
_tokenIdCounter.increment();
giftsSent.increment();
_safeMint(to, tokenId);
}
}
// Mint function uses OpenZeppelin's mint functions to ensure safety.
// Requires ensure that minting is 1-10 and that user is whitelisted. Does not allow to mint beyond the gift buffer or whitelisted allocation.
function firstPresale(uint256 mintAmount, bytes memory _signature) public payable nonReentrant {
require(currentState == ContractState.PRESALE1, "First presale not in session");
require(_verify(msg.sender, _signature), "You are not on the whitelist");
require(mintAmount > 0, "Can't mint 0");
require(mintAmount + _tokenIdCounter.current() <= MAX_SUPPLY - giftsRemaining() - SNAPSHOT, "Minting more than max supply");
require(mintAmount < 11, "Max mint is 10");
require(msg.value == PRICE * mintAmount, "Wrong price");
require(whitelist[msg.sender] + mintAmount <= maxPresaleMint, "Minting more than your whitelist allocation");
for(uint i = 0; i < mintAmount; i++) {
uint256 tokenId = _tokenIdCounter.current() + SNAPSHOT;
_tokenIdCounter.increment();
whitelist[msg.sender]++;
_safeMint(msg.sender, tokenId);
}
}
// Mint function uses OpenZeppelin's mint functions to ensure safety.
// Requires ensure that minting is 1-10 and that user is whitelisted. Does not allow to mint beyond the gift buffer.
function secondPresale(uint256 mintAmount, bytes memory _signature) public payable nonReentrant {
require(currentState == ContractState.PRESALE2, "Second presale not in session");
require(_verify(msg.sender, _signature), "You are not on the whitelist");
require(mintAmount > 0, "Can't mint 0");
require(mintAmount + _tokenIdCounter.current() <= MAX_SUPPLY - giftsRemaining() - SNAPSHOT , "Minting more than max supply");
require(mintAmount < 11, "Max mint is 10");
require(msg.value == PRICE * mintAmount, "Wrong price");
for(uint i = 0; i < mintAmount; i++) {
uint256 tokenId = _tokenIdCounter.current() + SNAPSHOT;
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
}
// Mint function uses OpenZeppelin's mint functions to ensure safety.
// Requires ensure that minting is 1-10. Does not allow to mint beyond the gift buffer.
function mint(uint256 mintAmount) public payable nonReentrant {
require(currentState == ContractState.PUBLIC, "Public sale not started");
require(mintAmount > 0, "Can't mint 0");
require(mintAmount + _tokenIdCounter.current() <= MAX_SUPPLY - giftsRemaining() - SNAPSHOT, "Minting more than max supply");
require(mintAmount < 11, "Max mint is 10");
require(msg.value == PRICE * mintAmount, "Wrong price");
for(uint i = 0; i < mintAmount; i++) {
uint256 tokenId = _tokenIdCounter.current() + SNAPSHOT;
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
}
// Withdraw funds
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
Address.sendValue(payable(msg.sender), balance);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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 (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 v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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/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/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Mint function uses OpenZeppelin's mint functions to ensure safety. Requires ensure that minting is 1-10. Does not allow to mint beyond the gift buffer.
|
function mint(uint256 mintAmount) public payable nonReentrant {
require(currentState == ContractState.PUBLIC, "Public sale not started");
require(mintAmount > 0, "Can't mint 0");
require(mintAmount + _tokenIdCounter.current() <= MAX_SUPPLY - giftsRemaining() - SNAPSHOT, "Minting more than max supply");
require(mintAmount < 11, "Max mint is 10");
require(msg.value == PRICE * mintAmount, "Wrong price");
for(uint i = 0; i < mintAmount; i++) {
uint256 tokenId = _tokenIdCounter.current() + SNAPSHOT;
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
}
| 9,998,259 |
./full_match/4/0xE849C5A1eaA1604e80841B9140B9f34Fb7017120/sources/contracts/potenza/PotenzaPricing.sol
|
Returns the next price for an open mint/
|
function getNextPriceForOpenMintInWei(uint256 numberOfMints) public virtual override view returns (uint256) {
return numberOfMints*openPrice;
}
| 794,068 |
./partial_match/4/0x592B137AE5a24b51E4413BBda4cFaCEb8E057eD8/sources/REFLECT.sol
|
tFee = 1% burnFee = 1% liquidityFee = 1% let's burn it! -------------------------------------
|
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
uint256 currentRate = _getRate();
uint256 rAmount = tAmount.mul(currentRate);
uint256 tFee = tAmount.div(100);
uint256 burnFee = tAmount.div(100);
uint256 liquidityFee = tAmount.div(100);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
uint256 tTransferAmount = tAmount.sub(tFee.mul(3));
_rOwned[burnAddress] = _rOwned[burnAddress].add(burnFee);
_tBurnTotal = balanceOf(burnAddress);
emit Transfer(sender, burnAddress, tTransferAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
| 8,529,338 |
./full_match/1/0x8Cba9816E49Ee0a2e6611Cf3ab81b195AD9C5514/sources/contracts/gemSwap/Atomicizer.sol
|
transfer ERC20 tokens from the sender to this contract transfer ERC721 tokens from the sender to this contract accept CryptoPunks default transfer ERC1155 tokens from the sender to this contract
|
function _transferFromHelper(
ERC20Details memory erc20Details,
SpecialTransferHelper.ERC721Details[] memory erc721Details,
ERC1155Details[] memory erc1155Details
) internal {
for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) {
erc20Details.tokenAddrs[i].call(
abi.encodeWithSelector(
0x23b872dd,
msg.sender,
address(this),
erc20Details.amounts[i]
)
);
}
for (uint256 i = 0; i < erc721Details.length; i++) {
if (
erc721Details[i].tokenAddr ==
0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB
) {
_acceptCryptoPunk(erc721Details[i]);
}
erc721Details[i].tokenAddr ==
0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6
) {
_acceptMoonCat(erc721Details[i]);
}
else {
for (uint256 j = 0; j < erc721Details[i].ids.length; j++) {
IERC721Upgradeable(erc721Details[i].tokenAddr).transferFrom(
_msgSender(),
address(this),
erc721Details[i].ids[j]
);
}
}
}
for (uint256 i = 0; i < erc1155Details.length; i++) {
IERC1155Upgradeable(erc1155Details[i].tokenAddr)
.safeBatchTransferFrom(
_msgSender(),
address(this),
erc1155Details[i].ids,
erc1155Details[i].amounts,
""
);
}
}
| 4,824,482 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.4 <0.8.0;
pragma experimental ABIEncoderV2;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/math/SafeMath.sol";
import "https://github.com/vigilance91/solidarity/contracts/allowance/eventsAllowance.sol";
import "https://github.com/vigilance91/solidarity/libraries/address/AddressConstraints.sol";
import "https://github.com/vigilance91/solidarity/libraries/unsigned/uint256Constraints.sol";
///
/// @title mixinAllowance
/// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 1/5/2021, All Rights Reserved
/// @dev Allowance mixin implementation
///
library mixinAllowance
{
using SafeMath for uint256;
using eventsAllowance for address;
//using stringUtilities for string;
using AddressConstraints for address;
using uint256Constraints for uint256;
//using EnumerableMap for EnumerableMap.Map;
struct AllowanceStorage{
uint256 totalAllowanceHeldInCustody;
mapping(address=>mapping(address=>uint256)) allowances;
//mapping(address=>mapping(address=>EnumerableMap.Map)) nonces;
}
bytes32 internal constant STORAGE_SLOT = keccak256("VSN.allownace.mixin.storage");
//string internal constant _NAME = ' mixinAllownace: ';
//string internal constant ... = _NAME.concatenate('owner can not be spender');
function storageAllowance(
)internal pure returns(
AllowanceStorage storage ret
){
bytes32 position = STORAGE_SLOT;
assembly {
ret_slot := position
}
}
function initialize(
)internal returns(
AllowanceStorage storage ret
){
ret = storageAllowance();
ret.totalAllowanceHeldInCustody = 0;
}
///
///getters
///
function totalAllowanceHeldInCustody(
)internal view returns(
uint256
){
return storageAllowance().totalAllowanceHeldInCustody;
}
function allowances(
)internal view returns(
mapping(address=>mapping(address=>uint256)) storage
){
return storageAllowance().allowances;
}
//function nonces(
//)internal view returns(
//mapping(address=>mapping(address=>EnumerableMap.Map)) storage
//){
//return storageAllowance().nonces;
//}
function allowancesAt(
address account
)internal view returns(
mapping(address=>uint256) storage
){
account.requireNotNull();
return allowances()[account];
}
//function noncesAt(
//address owner
//)internal view returns(
//EnumerableMap storage //mapping(address=>bytes32[]) storage
//){
//owner.requireNotNull();
//
//return nonces()[owner];
//}
function allowanceFor(
address owner,
address spender
)internal view returns(
uint256
){
owner.requireNotEqualAndNotNull(
spender
);
return allowances()[owner][spender];
}
/**
function currentNonceFor(
address owner,
address spender
)internal view returns(
bytes32
){
owner.requireNotEqualAndNotNull(spender);
bytes32[] memory N = nonces()[owner][spender];
return N[N.length.sub(1)];
}
function nonceCount(
address owner,
address spender
)internal view returns(
uint256
){
return noncesAt(owner,spender).length;
}
function nonceAlreadyUsed(
address owner,
address spender
)internal view returns(
bool
){
//bytes32[] memory N = nonces()[owner][spender];
//
//return N[N.length.sub(1)];
//bytes32 nonce = owner.hexadecimal().saltAndHash(
//spender.hexadecimal().concatenate(
//nonceCount(owner, spender).add(1).hexadecimal()
//)
//);
//
//return nonce()[owner][spender].contains(nonce) == true;
}
*/
///
///setters
///
/// note this is just a counter for bookkeeping and does not do anything or hold any value in and of itself
function _increaseTotalAllowanceHeldInCustody(
uint256 amountBy
)private
{
amountBy.requireGreaterThanZero();
AllowanceStorage storage s = storageAllowance();
s.totalAllowanceHeldInCustody = s.totalAllowanceHeldInCustody.add(
amountBy
);
}
function _decreaseTotalAllowanceHeldInCustody(
uint256 amountBy
)private
{
amountBy.requireGreaterThanZero();
AllowanceStorage storage s = storageAllowance();
s.totalAllowanceHeldInCustody = s.totalAllowanceHeldInCustody.sub(
amountBy
);
}
/**
function incrementNonce(
address owner,
address spender
)internal
{
nonces()[owner][spender].push(
owner.hexadecimal().saltAndHash(
spender.hexadecimal().concatenate(
nonceCount(owner, spender).add(1).hexadecimal()
)
)
);
}
*/
function _setAllowanceFor(
address owner,
address spender,
uint256 newAllowance
)private
{
//requireNonce...
//prevent redundant setting of allowance
allowanceFor(owner,spender).requireNotEqual(
newAllowance
//_NAME.concatenate('allowance already set to amount')
);
allowances()[owner][spender] = newAllowance;
//incrementNonce(owner,spender);
}
/// @dev spender must have no allowance (an allowance of 0) to approve
function approve(
address owner,
address spender,
uint256 amount
)internal
{
//cannot approve an allowance if one is already set
allowanceFor(owner,spender).requireEqual(0);
_setAllowanceFor(
owner,
spender,
amount
);
_increaseTotalAllowanceHeldInCustody(amount);
//assert(allowanceFor(owner,spender) == amount);
owner.emitApproveAllowance(
spender,
amount
);
}
/// @dev spender must have a non-zero allowance to revoke
function revoke(
address owner,
address spender
)internal returns(
uint256
){
uint256 A = allowanceFor(owner,spender);
A.requireGreaterThanZero();
//cannot revoke allowance if none is set
_setAllowanceFor(
owner,
spender,
0
);
_decreaseTotalAllowanceHeldInCustody(A);
//assert(allowanceFor(owner,spender) == 0);
owner.emitRevokeAllowance(
spender,
A
);
return A;
}
//for internal use only, to increase an allowance externally,
//it is recommended to first revoke the previous allowance
//and then approve the new desired allowance in order to prevent double spend attacks
function increaseAllowance(
address owner,
address spender,
uint256 amountBy
)internal returns(
uint256 newAllowance
){
uint256 PA = allowanceFor(owner,spender);
//cannot increase allowance if none is set,
//call approve before increase allowance
PA.requireGreaterThanZero(
//_NAME.concatenate('spender does not have an allowance')
);
newAllowance = PA.add(
amountBy
);
_setAllowanceFor(
owner,
spender,
newAllowance
);
_increaseTotalAllowanceHeldInCustody(amountBy);
//assert(NA > PA);
}
//for internal use only, to decrease an allowance externally,
//it is recommended to first revoke the previous allowance
//and then approve the new desired allowance in order to prevent double spend attacks
function decreaseAllowance(
address owner,
address spender,
uint256 amountBy
)internal returns(
uint256 newAllowance
){
uint256 PA = allowanceFor(owner,spender);
//cannot increase allowance if none is set,
//call approve before increase allowance
PA.requireGreaterThanZero(
//_NAME.concatenate('spender does not have an allowance')
);
newAllowance = PA.sub(
amountBy
);
_setAllowanceFor(
owner,
spender,
newAllowance
);
_decreaseTotalAllowanceHeldInCustody(amountBy);
//assert(NA < PA);
}
}
|
function nonces()internal view returns(mapping(address=>mapping(address=>EnumerableMap.Map)) storage){return storageAllowance().nonces;}
|
function allowancesAt(
address account
)internal view returns(
mapping(address=>uint256) storage
){
account.requireNotNull();
return allowances()[account];
}
| 5,525,799 |
./partial_match/1/0xFb64597ddA1345317A4f4f5DBA2425384bC5fA7B/sources/MICUSDTPool.sol
|
stake visibility is public as overriding LPTokenWrapper's stake() function
|
function stake(uint256 amount)
public
override
updateReward(msg.sender)
checkStart
{
require(amount > 0, 'MICUSDTPool: Cannot stake 0');
uint256 newDeposit = deposits[msg.sender].add(amount);
deposits[msg.sender] = newDeposit;
super.stake(amount);
emit Staked(msg.sender, amount);
}
| 2,823,957 |
/**
*Submitted for verification at Etherscan.io on 2022-03-28
*/
// File: contracts/nutra.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.0;
/* DESCRIPTION
*Nutraceutical.Finance is the first token to manufacture dietary supplements,
sell them on the open market, and throw the profits back into the coin.
No other token in cryptocurrency can compare to the utility that this coin has to offer.
This coin has a real world utility that the whole world can benefit from.
/* https://nutraceutical.finance/
* https://www.twitter.com/nutrafinance
*
* Tokenomics
*BUY TAX
*1% LP
*1% Development
*1% Marketing
*2% Rewards in USDT
*SELL TAX
*1% LP
*3% Marketing
*1% Development
*4% Rewards in USDT
* TOTAL SUPPLY 10 TRILLION
* MAX WALLET - 100 BILLION = 1% OF TOTAL SUPPLY
* MAX TRANSACTION - 50 BILLION = .5% OF TOTAL SUPPLY
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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);
}
/*
* @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;
}
}
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;
}
}
/**
* @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, IERC20Metadata {
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;
/**
* @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() external view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external 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, unloness 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:
*
* - `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:
*
* - `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 = _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 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 {}
}
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
/// @title Dividend-Paying Token Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev An interface for a dividend-paying token contract.
interface DividendPayingTokenInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns(uint256);
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/// @title Dividend-Paying Token Optional Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev OPTIONAL functions for a dividend-paying token contract.
interface DividendPayingTokenOptionalInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
}
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 () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/// @title Dividend-Paying Token
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether
/// to token holders as dividends and allows token holders to withdraw their dividends.
/// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
contract DividendPayingToken is ERC20, Ownable, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
address public immutable USDT = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); //USDT
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
uint256 public totalDividendsDistributed;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
}
function distributeUSDTDividends(uint256 amount) public onlyOwner{
require(totalSupply() > 0);
if (amount > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(amount).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, amount);
totalDividendsDistributed = totalDividendsDistributed.add(amount);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(payable(msg.sender));
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
bool success = IERC20(USDT).transfer(user, _withdrawableDividend);
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @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 virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @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 override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract NUTRA is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private swapping;
NUTRADividendTracker public dividendTracker;
address constant public deadWallet = 0x000000000000000000000000000000000000dEaD;
address public immutable USDT = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); //USDT
uint256 public swapTokensAtAmount = 50000 * (10**6) * (10**18);
uint256 public maxTransactionAmount = 50000000000 * (10**18); //1%
uint256 public _BuyUSDTRewardsFee = 2;
uint256 public _BuyLiquidityFee = 1;
uint256 public _BuyMarketingFee = 1;
uint256 public _BuyDevFee = 1;
// uint256 public extraFeeOnSell = 4;
uint256 public _BuyTotalFees = _BuyUSDTRewardsFee.add(_BuyLiquidityFee).add(_BuyMarketingFee).add(_BuyDevFee);
uint256 public _SellUSDTRewardsFee = 4;
uint256 public _SellLiquidityFee = 1;
uint256 public _SellMarketingFee = 3;
uint256 public _SellDevFee = 1;
uint256 public _SellTotalFees = _SellUSDTRewardsFee.add(_SellLiquidityFee).add(_SellMarketingFee).add(_SellDevFee);
uint256 public maxWalletToken = 100000000000 * (10**18); //1%
address public _marketingWalletAddress = 0x6b3a4a864F1990FA2dB4dd78bbe3A7081d124a0B;
address public _developmentWalletAddress = 0xB5E48bC38862dC0f37E03FdF5380dc209fed158f;
bool public tradingEnabled;
// use by default 300,000 gas to process auto-claiming dividends
uint256 public gasForProcessing = 300000;
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) private _isExcludedFromMaxWallet;
mapping (address => bool) private _isExcludedFromMaxTx;
mapping (address => bool) private _blacklisted;
mapping (address => bool) private _whitelisted;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeFromMaxTx(address indexed account, bool isExcluded);
event ExcludeFromMaxWallet(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event log(string error);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SendDividends(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
event SwapETHForTokens(
uint256 amountIn,
address[] path
);
constructor() ERC20("NUTRACEUTICAL", "NUTRA") {
dividendTracker = new NUTRADividendTracker();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(deadWallet);
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(_marketingWalletAddress);
dividendTracker.excludeFromDividends(_developmentWalletAddress);
// exclude from paying fees or having max transaction amount
excludeOrIncludeFromFees(owner(), true);
excludeOrIncludeFromFees(_marketingWalletAddress, true);
excludeOrIncludeFromFees(_developmentWalletAddress, true);
excludeOrIncludeFromFees(address(this), true);
excludeOrIncludeFromMaxTx(owner(), true);
excludeOrIncludeFromMaxTx(_marketingWalletAddress, true);
excludeOrIncludeFromMaxTx(_developmentWalletAddress, true);
excludeOrIncludeFromMaxTx(address(this), true);
excludeOrIncludeFromMaxWallet(owner(), true);
excludeOrIncludeFromMaxWallet(_marketingWalletAddress, true);
excludeOrIncludeFromMaxWallet(_developmentWalletAddress, true);
excludeOrIncludeFromMaxWallet(address(this), true);
_whitelisted[owner()] = true;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 10000000000000 * (10**18));
}
receive() external payable {
}
function setTradingEnabled(bool _enabled) external onlyOwner{
tradingEnabled = _enabled;
}
function addToBlackList(address _add) external onlyOwner
{
_blacklisted[_add] = true;
}
function removeFromBlackList(address _add) external onlyOwner
{
_blacklisted[_add] = false;
}
function isBlacklisted(address _add) public view returns(bool){
return _blacklisted[_add];
}
function addToWhitelist(address _add) external onlyOwner
{
_whitelisted[_add] = true;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "TEST: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function updateDividendTracker(address newAddress) public onlyOwner {
require(newAddress != address(dividendTracker), "NUTRA: The dividend tracker already has that address");
NUTRADividendTracker newDividendTracker = NUTRADividendTracker(payable(newAddress));
require(newDividendTracker.owner() == address(this), "NUTRA: The new dividend tracker must be owned by the EFT token contract");
newDividendTracker.excludeFromDividends(address(newDividendTracker));
newDividendTracker.excludeFromDividends(address(this));
newDividendTracker.excludeFromDividends(owner());
newDividendTracker.excludeFromDividends(address(uniswapV2Router));
dividendTracker.excludeFromDividends(_marketingWalletAddress);
dividendTracker.excludeFromDividends(_developmentWalletAddress);
dividendTracker.excludeFromDividends(deadWallet);
emit UpdateDividendTracker(newAddress, address(dividendTracker));
dividendTracker = newDividendTracker;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "NUTRA: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
uniswapV2Pair = _uniswapV2Pair;
}
function excludeOrIncludeFromFees(address account, bool excluded) public onlyOwner {
require(_isExcludedFromFees[account] != excluded, "NUTRA: Account is already the value of 'excluded'");
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeOrIncludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function excludeOrIncludeFromMaxTx(address account, bool excluded) public onlyOwner
{
require(_isExcludedFromMaxTx[account] != excluded, "NUTRA: Account is already the value of 'excluded'");
_isExcludedFromMaxTx[account] = excluded;
emit ExcludeFromMaxTx(account, excluded);
}
function excludeOrIncludeFromMaxWallet(address account, bool excluded) public onlyOwner
{
require(_isExcludedFromMaxWallet[account] != excluded, "NUTRA: Account is already the value of 'excluded'");
_isExcludedFromMaxWallet[account] = excluded;
emit ExcludeFromMaxWallet(account, excluded);
}
function setMaxWalletToken(uint256 _maxToken) external onlyOwner {
maxWalletToken = _maxToken;
}
function setMaxtx(uint256 _maxTxAmount) public onlyOwner {
maxTransactionAmount = _maxTxAmount;
}
function setMarketingWallet(address payable wallet) external onlyOwner{
require(wallet != address(0), "Invalid address");
_marketingWalletAddress = wallet;
}
function setDevelopmentWallet(address payable wallet) external onlyOwner{
require(wallet != address(0), "Invalid address");
_developmentWalletAddress = wallet;
}
function setBuyFees(uint256 buyUSDTRewardFee, uint256 buyLiquidityFee, uint256 buyMarketingFee, uint256 buyDevFee) external onlyOwner
{
_BuyUSDTRewardsFee = buyUSDTRewardFee;
_BuyLiquidityFee = buyLiquidityFee;
_BuyMarketingFee = buyMarketingFee;
_BuyDevFee = buyDevFee;
_BuyTotalFees = _BuyUSDTRewardsFee.add(_BuyLiquidityFee).add(_BuyMarketingFee).add(_BuyDevFee);
require(_BuyTotalFees >= 0 && _BuyTotalFees <= 20, "Fees are exceeding the limits");
}
function setSellFees(uint256 sellUSDTRewardFee, uint256 sellLiquidityFee, uint256 sellMarketingFee, uint256 sellDevFee) external onlyOwner
{
_SellUSDTRewardsFee = sellUSDTRewardFee;
_SellLiquidityFee = sellLiquidityFee;
_SellMarketingFee = sellMarketingFee;
_SellDevFee = sellDevFee;
_SellTotalFees = _SellUSDTRewardsFee.add(_SellLiquidityFee).add(_SellMarketingFee).add(_SellDevFee);
require(_SellTotalFees >= 0 && _SellTotalFees <= 20, "Fees are exceeding the limits");
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "NUTRA: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
require(newValue >= 200000 && newValue <= 800000, "NUTRA: gasForProcessing must be between 200,000 and 800,000");
require(newValue != gasForProcessing, "NUTRA: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function isExcludedFromMaxTx(address account) public view returns(bool) {
return _isExcludedFromMaxTx[account];
}
function isExcludedFromMaxWallet(address account) public view returns(bool) {
return _isExcludedFromMaxWallet[account];
}
function withdrawableDividendOf(address account) public view returns(uint256) {
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function excludeFromDividends(address account) external onlyOwner{
dividendTracker.excludeFromDividends(account);
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function changeSwapTokensAtAmount(uint256 swapAmount) external onlyOwner
{
swapTokensAtAmount = swapAmount;
}
function extraFeeOnSell() internal view returns(uint256)
{
return _SellTotalFees.sub(_BuyTotalFees);
}
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(!_blacklisted[to] && !_blacklisted[from], "address is blacklisted");
if(!_whitelisted[from]) { require(tradingEnabled, "Trading is not enabled yet");}
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
to != uniswapV2Pair
) {
uint256 contractBalanceRecepient = balanceOf(to);
if(!_isExcludedFromMaxWallet[to])
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if((!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to]))
{
if((!_isExcludedFromMaxTx[from]) && (!_isExcludedFromMaxTx[from])){
require(amount <= maxTransactionAmount, "transfer amount exceeds the maxSellTransactionAmount.");
}}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if( canSwap &&
!swapping &&
from != address(uniswapV2Pair) &&
from != owner() &&
to != owner()
)
{
swapping = true;
uint256 walletTokens = contractTokenBalance.mul(_SellMarketingFee.add(_SellDevFee)).div(_SellTotalFees);
uint256 contractBalance = address(this).balance;
swapTokensForEth(walletTokens);
uint256 newBalance = address(this).balance.sub(contractBalance);
uint256 marketingShare = newBalance.mul(_SellMarketingFee).div(_SellDevFee.add(_SellMarketingFee));
uint256 developmentShare = newBalance.sub(marketingShare);
payable(_marketingWalletAddress).transfer(marketingShare);
payable(_developmentWalletAddress).transfer(developmentShare);
uint256 swapTokens = contractTokenBalance.mul(_SellLiquidityFee).div(_SellTotalFees);
swapAndLiquify(swapTokens);
uint256 sellTokens = balanceOf(address(this));
swapAndSendDividends(sellTokens);
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(!automatedMarketMakerPairs[to] && !automatedMarketMakerPairs[from])
{ takeFee = false;}
if(takeFee) {
uint256 fees = amount.mul(_BuyTotalFees).div(100);
if(automatedMarketMakerPairs[to]){
fees += amount.mul(extraFeeOnSell()).div(100);
}
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch { emit log("failed");}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {emit log("failed");}
if(!swapping) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
}
catch {
emit log("failed");
}
}
}
function swapAndLiquify(uint256 tokens) private {
// split the contract balance into halves
uint256 half = tokens.div(2);
uint256 otherHalf = tokens.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
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 manualSwapTokensForEth(uint256 tokenAmount) public onlyOwner {
// 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 swapTokensForETH(uint256 tokenAmount) private {
address[] memory path = new address[](3);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
path[2] = USDT;
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
0,
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 swapAndSendDividends(uint256 tokens) private{
swapTokensForETH(tokens);
uint256 dividends = IERC20(USDT).balanceOf(address(this));
bool success = IERC20(USDT).transfer(address(dividendTracker), dividends);
if (success) {
dividendTracker.distributeUSDTDividends(dividends);
emit SendDividends(tokens, dividends);
}
}
function withdrawStuckUSDT() external onlyOwner{
require (address(this).balance > 0, "Can't withdraw negative or zero");
payable(owner()).transfer(address(this).balance);
}
function removeStuckToken(address _address) external onlyOwner {
require(_address != address(this), "Can't withdraw tokens destined for liquidity");
require(IERC20(_address).balanceOf(address(this)) > 0, "Can't withdraw 0");
IERC20(_address).transfer(owner(), IERC20(_address).balanceOf(address(this)));
}
}
contract NUTRADividendTracker is Ownable, DividendPayingToken {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public immutable minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() DividendPayingToken("NUTRA_Dividen_Tracker", "NUTRA_Dividend_Tracker") {
claimWait = 3600;
minimumTokenBalanceForDividends = 10000 * (10**18); //must hold 10000 tokens
}
function _transfer(address, address, uint256) internal pure override {
require(false, "NUTRA_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() public pure override {
require(false, "NUTRA_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main EFT contract.");
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludeFromDividends(account);
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 3600 && newClaimWait <= 86400, "NUTRA_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "NUTRA_Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
}
else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
|
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);
}
| 2,369,157 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2; // required to accept structs as function parameters
import 'hardhat/console.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
import '@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol';
import "@openzeppelin/contracts/utils/Strings.sol";
// ..
// -#@@%+.
// -*@@+**[email protected]@#-
// [email protected]@@[email protected]@@@:@@##@#-
// =#@@@@@[email protected]@-#@*%##@@@@+.
// -#@@#.-%@@%@#@@@:-*%%****@%=.
// :*@@@@@%@@@[email protected]@+#@:%+%@@@@@@@*@%=
// -%@@*+++%#@%[email protected]#%*@=*@@@@@@@#[email protected]@[email protected]%%@+
// *@####@@@**%%@@@#**@@:%@*@@[email protected]*#@*@@*@@
// *@##[email protected]@#=*@@@#[email protected][email protected]#@*#@@%@@##+*@@@@
// *@@@@@@@@[email protected]*+#@@*++-%@[email protected]@@%@@%%%#@@@@
// *@@*@%[email protected]+*#[email protected]#[email protected]@%@@:#@#***%@@@@@=*[email protected]
// *@@@@@#@#%%%@+--%+#@@*%*@%++#[email protected]@@@@#[email protected]
// *%:%@@@%***%@[email protected][email protected]@@%+%@*++=%[email protected]@#[email protected]@@@
// *%-***@%*%*@%#@@@@%-:++#@@@=%@#--++#@@
// [email protected]@@@@@@#[email protected]@#[email protected]@@[email protected]#%@@+*@@@@@@%@@@@@*
// -*@@#[email protected]#::++#@[email protected]@[email protected]+*-%@*#*%%@@%=
// =#@@@*@@@@@***[email protected]@#@@*@@+*@%+:
// .=%@%+++%@@@-#@@=:*@@@*:
// :*@@@+%@%#@@@##@#=
// -*@#@#[email protected]%@%=.
// -#@%@+:
// .:
//
//
//
//
// +++- :++= :++= :++= :++= =++- -+++++++++++++ =++++++++++++- -++++++ .+++
// @@@@= [email protected]@% [email protected]@# [email protected]@% [email protected]@@#. *@@@# *@@@@@@@@@@@@@ %@@@@@@@@@@@@@* %@@@@@@- [email protected]@@
// @@@@@* [email protected]@% [email protected]@# [email protected]@% [email protected]@@@@- :%@@@@# *@@# %@@+ *@@* [email protected]@= [email protected]@@ [email protected]@@
// @@@#@@%: [email protected]@% [email protected]@# [email protected]@% [email protected]@#%@@* [email protected]@@#@@# *@@# %@@+ *@@* [email protected]@% [email protected]@* [email protected]@@
// @@@[email protected]@@- [email protected]@% [email protected]@# [email protected]@% [email protected]@* *@@#*@@%[email protected]@# *@@%++++++++ %@@*-------#@@* *@@- %@@. [email protected]@@
// @@@- :%@@* [email protected]@% [email protected]@# [email protected]@% [email protected]@* [email protected]@@@+ [email protected]@# *@@@@@@@@@@@. %@@@@@@@@@@@@@- [email protected]@%:::::*@@# [email protected]@@
// @@@- *@@#[email protected]@% [email protected]@# [email protected]@% [email protected]@* .%@: [email protected]@# *@@# %@@*...:#@@%: %@@@@@@@@@@@@- [email protected]@@
// @@@- [email protected]@@@@% [email protected]@# [email protected]@% [email protected]@* . [email protected]@# *@@# %@@+ *@@% [email protected]@%[email protected]@@ [email protected]@@
// @@@- :%@@@% [email protected]@%+++++++#@@% [email protected]@* [email protected]@# *@@%++++++++++ %@@+ [email protected]@%: [email protected]@@: #@@+ [email protected]@@
// @@@- .%@@% .*@@@@@@@@@@@%- [email protected]@* [email protected]@* *@@@@@@@@@@@@@ #@@+ [email protected]@@: *@@* [email protected]@@. [email protected]@@
//
contract NumeraiTshirts is ERC721, EIP712, Ownable {
string public constant DOMAIN_NAME = 'NumeraiNFTee-Voucher';
string public constant DOMAIN_VERSION = '1';
uint256 public constant maxTokens = 6000;
// Base URI and contract URI
string private _myBaseURI;
string private _myContractURI;
constructor()
ERC721('Numerai Tshirts', 'NTEE')
EIP712(DOMAIN_NAME, DOMAIN_VERSION)
{}
/// @notice This function is used by OpenSea to retrieve storefront-level metadata
/// see: https://docs.opensea.io/docs/contract-level-metadata
function contractURI() public view returns (string memory) {
return _myContractURI;
}
/// @notice This contract uses the lazy and permissioned minting pattern enabled
/// by draft-EIP712. The minter signs and distributes vouchers to users off-chain, and
/// the user uses the signed voucher to redeem the NFT
struct Voucher {
uint256[] tokenIds;
address minter;
bytes signature;
}
/// @notice Check if the token exists
function tokenExists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
/// @notice Redeems a voucher for a NFT and returns the tokenIds
function redeem(Voucher calldata voucher)
external
returns (uint256[] memory)
{
// Make sure voucher is valid
_verify(voucher);
// Mint the NFTs to msg.sender. Will revert if tokenId is already owned!
for (uint256 i = 0; i < voucher.tokenIds.length; i++) {
_mint(msg.sender, voucher.tokenIds[i]);
}
return voucher.tokenIds;
}
/// @notice Verifies the signature of the voucher
/// @dev Will revert if msg.sender does not match voucher.minter address
/// @dev Will revert if the signature does not match the tokenIds
/// @dev Will revert if the signature does not match the domain name and version
/// @dev Will revert if the signature does not match the contract address and chain id
/// @dev Will revert if not signed by owner
function _verify(Voucher calldata voucher) internal view {
require(
voucher.minter == msg.sender,
'Voucher can only be redeemed by assigned wallet'
);
bytes32 digest = _hash(voucher);
address signer = ECDSA.recover(digest, voucher.signature);
require(signer == owner(), 'Signature invalid or unauthorized');
}
/// @notice Returns a hash of the given Voucher, prepared using EIP712 typed data hashing rules.
/// @dev see https://docs.openzeppelin.com/contracts/3.x/api/drafts#EIP712-_hashTypedDataV4-bytes32-
function _hash(Voucher calldata voucher) internal view returns (bytes32) {
return
_hashTypedDataV4(
keccak256(
abi.encode(
keccak256(
abi.encodePacked('Voucher(uint256[] tokenIds,address minter)')
),
keccak256(abi.encodePacked(voucher.tokenIds)),
voucher.minter
)
)
);
}
function getChainID() external view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function _baseURI() internal view override returns (string memory) {
return _myBaseURI;
}
/// @notice Mints tokenId to wallet address. External function can only be called
/// outside of the contract but uses less gas than a public function
function mintToAddress(uint256 tokenId, address recipient)
external
onlyOwner
returns (uint256)
{
require(tokenId < maxTokens);
// Mint the NFT to recipient. Will revert if tokenId is already owned!
_mint(recipient, tokenId);
return tokenId;
}
/// @notice Mints tokenIds to wallet addresses
function batchMintToAddress(
uint256[] calldata tokenIds,
address[] calldata recipients
) external onlyOwner returns (uint256[] memory) {
for (uint256 i = 0; i < tokenIds.length; i++) {
require(tokenIds[i] < maxTokens);
// Mint the NFT to recipient. Will revert if tokenId is already owned!
_mint(recipients[i], tokenIds[i]);
}
return tokenIds;
}
/// @notice Sets myBaseURI
function setBaseURI(string calldata baseURI) external onlyOwner {
_myBaseURI = baseURI;
}
/// @notice Sets _myContractURI
function setContractURI(string calldata _contractURI) external onlyOwner {
_myContractURI = _contractURI;
}
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, Strings.toString(tokenId), ".json")) : "";
}
}
// 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.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Redeems a voucher for a NFT and returns the tokenIds Make sure voucher is valid Mint the NFTs to msg.sender. Will revert if tokenId is already owned!
|
function redeem(Voucher calldata voucher)
external
returns (uint256[] memory)
{
_verify(voucher);
for (uint256 i = 0; i < voucher.tokenIds.length; i++) {
_mint(msg.sender, voucher.tokenIds[i]);
}
return voucher.tokenIds;
}
| 13,391,818 |
pragma solidity ^0.4.24;
// v1.0
import "../../lib/ownership/Upgradable.sol";
import "../../lib/lifecycle/Destructible.sol";
import "../bondage/BondageInterface.sol";
import "./ArbiterInterface.sol";
import "../database/DatabaseInterface.sol";
contract Arbiter is Destructible, ArbiterInterface, Upgradable {
// Called when a data purchase is initiated
event DataPurchase(
address indexed provider, // Etheruem address of the provider
address indexed subscriber, // Ethereum address of the subscriber
uint256 publicKey, // Public key of the subscriber
uint256 indexed amount, // Amount (in 1/100 ZAP) of ethereum sent
bytes32[] endpointParams, // Endpoint specific(nonce,encrypted_uuid),
bytes32 endpoint // Endpoint specifier
);
// Called when a data subscription is ended by either provider or terminator
event DataSubscriptionEnd(
address indexed provider, // Provider from the subscription
address indexed subscriber, // Subscriber from the subscription
SubscriptionTerminator indexed terminator // Which terminated the contract
);
// Called when party passes arguments to another party
event ParamsPassed(
address indexed sender,
address indexed receiver,
bytes32 endpoint,
bytes32[] params
);
// Used to specify who is the terminator of a contract
enum SubscriptionTerminator { Provider, Subscriber }
BondageInterface bondage;
address public bondageAddress;
// database address and reference
DatabaseInterface public db;
constructor(address c) Upgradable(c) public {
_updateDependencies();
}
function _updateDependencies() internal {
bondageAddress = coordinator.getContract("BONDAGE");
bondage = BondageInterface(bondageAddress);
address databaseAddress = coordinator.getContract("DATABASE");
db = DatabaseInterface(databaseAddress);
}
//@dev broadcast parameters from sender to offchain receiver
/// @param receiver address
/// @param endpoint Endpoint specifier
/// @param params arbitrary params to be passed
function passParams(address receiver, bytes32 endpoint, bytes32[] params) public {
emit ParamsPassed(msg.sender, receiver, endpoint, params);
}
/// @dev subscribe to specified number of blocks of provider
/// @param providerAddress Provider address
/// @param endpoint Endpoint specifier
/// @param endpointParams Endpoint specific params
/// @param publicKey Public key of the purchaser
/// @param blocks Number of blocks subscribed, 1block=1dot
function initiateSubscription(
address providerAddress, //
bytes32 endpoint, //
bytes32[] endpointParams, //
uint256 publicKey, // Public key of the purchaser
uint64 blocks //
)
public
{
// Must be atleast one block
require(blocks > 0, "Error: Must be at least one block");
// Can't reinitiate a currently active contract
require(getDots(providerAddress, msg.sender, endpoint) == 0, "Error: Cannot reinstantiate a currently active contract");
// Escrow the necessary amount of dots
bondage.escrowDots(msg.sender, providerAddress, endpoint, blocks);
// Initiate the subscription struct
setSubscription(
providerAddress,
msg.sender,
endpoint,
blocks,
uint96(block.number),
uint96(block.number) + uint96(blocks)
);
emit DataPurchase(
providerAddress,
msg.sender,
publicKey,
blocks,
endpointParams,
endpoint
);
}
/// @dev get subscription info
function getSubscription(address providerAddress, address subscriberAddress, bytes32 endpoint)
public
view
returns (uint64 dots, uint96 blockStart, uint96 preBlockEnd)
{
return (
getDots(providerAddress, subscriberAddress, endpoint),
getBlockStart(providerAddress, subscriberAddress, endpoint),
getPreBlockEnd(providerAddress, subscriberAddress, endpoint)
);
}
/// @dev Finish the data feed from the provider
function endSubscriptionProvider(
address subscriberAddress,
bytes32 endpoint
)
public
{
// Emit an event on success about who ended the contract
if (endSubscription(msg.sender, subscriberAddress, endpoint))
emit DataSubscriptionEnd(
msg.sender,
subscriberAddress,
SubscriptionTerminator.Provider
);
}
/// @dev Finish the data feed from the subscriber
function endSubscriptionSubscriber(
address providerAddress,
bytes32 endpoint
)
public
{
// Emit an event on success about who ended the contract
if (endSubscription(providerAddress, msg.sender, endpoint))
emit DataSubscriptionEnd(
providerAddress,
msg.sender,
SubscriptionTerminator.Subscriber
);
}
/// @dev Finish the data feed
function endSubscription(
address providerAddress,
address subscriberAddress,
bytes32 endpoint
)
private
returns (bool)
{
// get the total value/block length of this subscription
uint256 dots = getDots(providerAddress, subscriberAddress, endpoint);
uint256 preblockend = getPreBlockEnd(providerAddress, subscriberAddress, endpoint);
// Make sure the subscriber has a subscription
require(dots > 0, "Error: Subscriber must have a subscription");
if (block.number < preblockend) {
// Subscription ended early
uint256 earnedDots = block.number - getBlockStart(providerAddress, subscriberAddress, endpoint);
uint256 returnedDots = dots - earnedDots;
// Transfer the earned dots to the provider
bondage.releaseDots(
subscriberAddress,
providerAddress,
endpoint,
earnedDots
);
// Transfer the returned dots to the subscriber
bondage.returnDots(
subscriberAddress,
providerAddress,
endpoint,
returnedDots
);
} else {
// Transfer all the dots
bondage.releaseDots(
subscriberAddress,
providerAddress,
endpoint,
dots
);
}
// Kill the subscription
deleteSubscription(providerAddress, subscriberAddress, endpoint);
return true;
}
/*** --- *** STORAGE METHODS *** --- ***/
/// @dev get subscriber dots remaining for specified provider endpoint
function getDots(
address providerAddress,
address subscriberAddress,
bytes32 endpoint
)
public
view
returns (uint64)
{
return uint64(db.getNumber(keccak256(abi.encodePacked('subscriptions', providerAddress, subscriberAddress, endpoint, 'dots'))));
}
/// @dev get first subscription block number
function getBlockStart(
address providerAddress,
address subscriberAddress,
bytes32 endpoint
)
public
view
returns (uint96)
{
return uint96(db.getNumber(keccak256(abi.encodePacked('subscriptions', providerAddress, subscriberAddress, endpoint, 'blockStart'))));
}
/// @dev get last subscription block number
function getPreBlockEnd(
address providerAddress,
address subscriberAddress,
bytes32 endpoint
)
public
view
returns (uint96)
{
return uint96(db.getNumber(keccak256(abi.encodePacked('subscriptions', providerAddress, subscriberAddress, endpoint, 'preBlockEnd'))));
}
/**** Set Methods ****/
/// @dev store new subscription
function setSubscription(
address providerAddress,
address subscriberAddress,
bytes32 endpoint,
uint64 dots,
uint96 blockStart,
uint96 preBlockEnd
)
private
{
db.setNumber(keccak256(abi.encodePacked('subscriptions', providerAddress, subscriberAddress, endpoint, 'dots')), dots);
db.setNumber(keccak256(abi.encodePacked('subscriptions', providerAddress, subscriberAddress, endpoint, 'blockStart')), uint256(blockStart));
db.setNumber(keccak256(abi.encodePacked('subscriptions', providerAddress, subscriberAddress, endpoint, 'preBlockEnd')), uint256(preBlockEnd));
}
/**** Delete Methods ****/
/// @dev remove subscription
function deleteSubscription(
address providerAddress,
address subscriberAddress,
bytes32 endpoint
)
private
{
db.setNumber(keccak256(abi.encodePacked('subscriptions', providerAddress, subscriberAddress, endpoint, 'dots')), 0);
db.setNumber(keccak256(abi.encodePacked('subscriptions', providerAddress, subscriberAddress, endpoint, 'blockStart')), uint256(0));
db.setNumber(keccak256(abi.encodePacked('subscriptions', providerAddress, subscriberAddress, endpoint, 'preBlockEnd')), uint256(0));
}
}
/*************************************** STORAGE ****************************************
* 'holders', holderAddress, 'initialized', oracleAddress => {uint256} 1 -> provider-subscriber initialized, 0 -> not initialized
* 'holders', holderAddress, 'bonds', oracleAddress, endpoint => {uint256} number of dots this address has bound to this endpoint
* 'oracles', oracleAddress, endpoint, 'broker' => {address} address of endpoint broker, 0 if none
* 'escrow', holderAddress, oracleAddress, endpoint => {uint256} amount of Zap that have been escrowed
* 'totalBound', oracleAddress, endpoint => {uint256} amount of Zap bound to this endpoint
* 'totalIssued', oracleAddress, endpoint => {uint256} number of dots issued by this endpoint
* 'holders', holderAddress, 'oracleList' => {address[]} array of oracle addresses associated with this holder
****************************************************************************************/
|
Finish the data feed from the subscriber Emit an event on success about who ended the contract
|
function endSubscriptionSubscriber(
address providerAddress,
bytes32 endpoint
)
public
{
if (endSubscription(providerAddress, msg.sender, endpoint))
emit DataSubscriptionEnd(
providerAddress,
msg.sender,
SubscriptionTerminator.Subscriber
);
}
| 1,003,840 |
./full_match/5/0x7c08b08e17189b2976314eBf6ebfAc1F2A82e3D7/sources/SafuERC721Staking.sol
|
functon called by the users to Stake NFTs tokenIds array of Token IDs of the NFTs to be staked the Token IDs have to be prevoiusly approved for transfer in the ERC721 contract with the address of this contract
|
function stake(uint256[] memory tokenIds)
external
nonReentrant
updateReward(msg.sender)
{
require(tokenIds.length != 0, "Staking: No tokenIds provided");
uint256 amount = tokenIds.length;
for (uint256 i = 0; i < amount; i += 1) {
nftCollection.safeTransferFrom(
msg.sender,
address(this),
tokenIds[i]
);
stakedAssets[tokenIds[i]] = msg.sender;
tokensStaked[msg.sender].push(tokenIds[i]);
}
totalStakedSupply += amount;
emit Staked(msg.sender, amount, tokenIds);
}
| 1,886,880 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_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;
}
// SPDX-License-Identifier: MIT
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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal 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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
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
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./library/RLPReader.sol";
import "./library/RToken.sol";
import "./versions/Version0.sol";
import "./interfaces/IBridgeCosignerManager.sol";
import "./interfaces/IBridgeToken.sol";
import "./interfaces/IBridgeTokenManager.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IOwnable.sol";
contract BridgeRouter is
Version0,
OwnableUpgradeable,
ReentrancyGuardUpgradeable,
PausableUpgradeable
{
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
using RToken for RToken.Token;
mapping(address => uint256) internal _nonces;
mapping(bytes32 => bool) internal _commitments;
// ===== initialize override =====
IBridgeCosignerManager public cosignerManager;
IBridgeTokenManager public tokenManager;
uint256 internal _chainId;
// ===== signing =====
bytes32 internal constant ENTER_EVENT_SIG =
keccak256("Enter(address,address,uint256,uint256,uint256,uint256)");
// ===== proxy =====
uint256[49] private __gap;
// ===== fallbacks =====
receive() external payable {}
// ===== events =====
event Enter(
address indexed token,
address indexed exitor,
uint256 amount,
uint256 nonce,
uint256 localChainId,
uint256 targetChainId
);
event Exit(
address indexed token,
address indexed exitor,
uint256 amount,
bytes32 commitment,
uint256 localChainId,
uint256 extChainId
);
function emitEnter(
address token,
address from,
uint256 amount,
uint256 targetChainId
) internal {
emit Enter(token, from, amount, _nonces[from], _chainId, targetChainId);
_nonces[from]++;
}
function emitExit(
address token,
address to,
bytes32 commitment,
uint256 amount,
uint256 extChainId
) internal {
emit Exit(token, to, amount, commitment, _chainId, extChainId);
}
// ===== functionality to update =====
/**
* @notice Set the token manager, callable only by cosigners
* @dev This should be the contract responsible for checking and add tokens to crosschain mapping
* @param newTokenManager address of token manager contract
*/
function setTokenManager(address newTokenManager) external onlyOwner {
require(newTokenManager != address(0), "BR: ZERO_ADDRESS");
tokenManager = IBridgeTokenManager(newTokenManager);
}
/**
* @notice Set the cosigner manager, callable only by cosigners
* @dev This should be the contract responsible for sign by behalf of the payloads
* @param newCosignerManager address of cosigner manager contract
*/
function setCosignerManager(address newCosignerManager) external onlyOwner {
require(newCosignerManager != address(0), "BR: ZERO_ADDRESS");
cosignerManager = IBridgeCosignerManager(newCosignerManager);
}
// Initialize function for proxy constructor. Must be used atomically
function initialize(
IBridgeCosignerManager cosignerManager_,
IBridgeTokenManager tokenManager_
) public initializer {
cosignerManager = cosignerManager_;
tokenManager = tokenManager_;
assembly {
sstore(_chainId.slot, chainid())
}
// proxy inits
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
}
// enter amount of tokens to protocol
function enter(
address token,
uint256 amount,
uint256 targetChainId
) external nonReentrant whenNotPaused {
require(token != address(0), "BR: ZERO_ADDRESS");
require(amount != 0, "BR: ZERO_AMOUNT");
RToken.Token memory localToken = tokenManager
.getLocal(token, targetChainId)
.enter(_msgSender(), address(this), amount);
emitEnter(localToken.addr, _msgSender(), amount, targetChainId);
}
// enter amount of system currency to protocol
function enterETH(uint256 targetChainId)
external
payable
nonReentrant
whenNotPaused
{
require(msg.value != 0, "BR: ZERO_AMOUNT");
require(tokenManager.isZero(targetChainId), "BR: NOT_FOUND");
emitEnter(address(0), _msgSender(), msg.value, targetChainId);
}
// exit amount of tokens from protocol
function exit(bytes calldata data, bytes[] calldata signatures)
external
nonReentrant
whenNotPaused
{
RLPReader.RLPItem[] memory logRLPList = data.toRlpItem().toList();
RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics
require(
bytes32(logTopicRLPList[0].toUint()) == ENTER_EVENT_SIG, // topic0 is event sig
"BR: INVALID_EVT"
);
address extTokenAddr = logTopicRLPList[1].toAddress();
address exitor = logTopicRLPList[2].toAddress();
require(exitor == _msgSender(), "BR: NOT_ONWER");
uint256 amount = logRLPList[2].toUint();
require(amount != 0, "BR: ZERO_AMOUNT");
uint256 localChainId = logRLPList[5].toUint();
require(localChainId == _chainId, "BR: WRONG_TARGET_CHAIN");
uint256 extChainId = logRLPList[4].toUint();
require(extChainId != _chainId, "BR: WRONG_SOURCE_CHAIN");
// protected from replay on another network
bytes32 commitment = keccak256(data);
require(!_commitments[commitment], "BR: COMMITMENT_KNOWN");
_commitments[commitment] = true;
require(
cosignerManager.verify(commitment, extChainId, signatures),
"BR: INVALID_SIGNATURES"
);
RToken.Token memory localToken = tokenManager
.getLocal(extTokenAddr, _chainId)
.exit(address(this), exitor, amount);
emitExit(localToken.addr, exitor, commitment, amount, extChainId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IBridgeCosignerManager {
event CosignerAdded(address indexed cosaddr, uint256 chainId);
event CosignerRemoved(address indexed cosaddr, uint256 chainId);
struct Cosigner {
address addr;
uint256 chainId;
uint256 index;
bool active;
}
function addCosigner(address cosaddr, uint256 chainId) external;
function addCosignerBatch(address[] calldata cosaddrs, uint256 chainId)
external;
function removeCosigner(address cosaddr) external;
function removeCosignerBatch(address[] calldata cosaddrs) external;
function getCosigners(uint256 chainId)
external
view
returns (address[] memory);
function getCosignCount(uint256 chainId) external view returns (uint8);
function verify(
bytes32 commitment,
uint256 chainId,
bytes[] calldata signatures
) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IBridgeToken {
function burn(address from, uint256 amount) external;
function mint(address to, uint256 amount) external;
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../library/RToken.sol";
interface IBridgeTokenManager {
event TokenAdded(address indexed addr, uint256 chainId);
event TokenRemoved(address indexed addr, uint256 chainId);
function issue(
address[] calldata tokens,
RToken.IssueType[] calldata issueTypes,
uint256 targetChainId
) external;
function revoke(address targetAddr) external;
function getLocal(address sourceAddr, uint256 targetChainId)
external
view
returns (RToken.Token memory token);
function isZero(uint256 targetChainId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IOwnable {
function transferOwnership(address newOwner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint256 len;
uint256 memPtr;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint256 nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint256 ptr = self.nextPtr;
uint256 itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item)
internal
pure
returns (RLPItem memory)
{
uint256 memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self)
internal
pure
returns (Iterator memory)
{
require(isList(self));
uint256 ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param the RLP item.
*/
function rlpLen(RLPItem memory item) internal pure returns (uint256) {
return item.len;
}
/*
* @param the RLP item.
* @return (memPtr, len) pair: location of the item's payload in memory.
*/
function payloadLocation(RLPItem memory item)
internal
pure
returns (uint256, uint256)
{
uint256 offset = _payloadOffset(item.memPtr);
uint256 memPtr = item.memPtr + offset;
uint256 len = item.len - offset; // data length
return (memPtr, len);
}
/*
* @param the RLP item.
*/
function payloadLen(RLPItem memory item) internal pure returns (uint256) {
(, uint256 len) = payloadLocation(item);
return len;
}
/*
* @param the RLP item containing the encoded list.
*/
function toList(RLPItem memory item)
internal
pure
returns (RLPItem[] memory)
{
require(isList(item));
uint256 items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 dataLen;
for (uint256 i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if (item.len == 0) return false;
uint8 byte0;
uint256 memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START) return false;
return true;
}
/*
* @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory.
* @return keccak256 hash of RLP encoded bytes.
*/
function rlpBytesKeccak256(RLPItem memory item)
internal
pure
returns (bytes32)
{
uint256 ptr = item.memPtr;
uint256 len = item.len;
bytes32 result;
assembly {
result := keccak256(ptr, len)
}
return result;
}
/*
* @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory.
* @return keccak256 hash of the item payload.
*/
function payloadKeccak256(RLPItem memory item)
internal
pure
returns (bytes32)
{
(uint256 memPtr, uint256 len) = payloadLocation(item);
bytes32 result;
assembly {
result := keccak256(memPtr, len)
}
return result;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item)
internal
pure
returns (bytes memory)
{
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint256 ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte except "0x80" is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint256 result;
uint256 memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
// SEE Github Issue #5.
// Summary: Most commonly used RLP libraries (i.e Geth) will encode
// "0" as "0x80" instead of as "0". We handle this edge case explicitly
// here.
if (result == 0 || result == STRING_SHORT_START) {
return false;
} else {
return true;
}
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(uint160(toUint(item)));
}
function toUint(RLPItem memory item) internal pure returns (uint256) {
require(item.len > 0 && item.len <= 33);
(uint256 memPtr, uint256 len) = payloadLocation(item);
uint256 result;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint256) {
// one byte prefix
require(item.len == 33);
uint256 result;
uint256 memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
(uint256 memPtr, uint256 len) = payloadLocation(item);
bytes memory result = new bytes(len);
uint256 destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(memPtr, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint256) {
if (item.len == 0) return 0;
uint256 count = 0;
uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint256 memPtr) private pure returns (uint256) {
uint256 itemLen;
uint256 byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
} else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
} else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint256 memPtr) private pure returns (uint256) {
uint256 byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) return 0;
else if (
byte0 < STRING_LONG_START ||
(byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)
) return 1;
else if (byte0 < LIST_SHORT_START)
// being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(
uint256 src,
uint256 dest,
uint256 len
) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
if (len > 0) {
// left over bytes. Mask is used to remove unwanted bytes from the word
uint256 mask = 256**(WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IBridgeToken.sol";
library RToken {
using SafeERC20 for IERC20;
enum IssueType {
DEFAULT,
MINTABLE
}
struct Token {
address addr;
uint256 chainId;
IssueType issueType;
bool exist;
}
function unsafeTransfer(
address from,
address to,
uint256 amount
) internal {
require(from.balance >= amount, "RT: INSUFFICIENT_BALANCE");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = to.call{value: amount}("");
require(success, "RT: SEND_REVERT");
}
function enter(
Token memory token,
address from,
address to,
uint256 amount
) internal returns (Token memory) {
require(token.exist, "RT: NOT_LISTED");
if (token.issueType == IssueType.MINTABLE) {
IBridgeToken(token.addr).burn(from, amount);
} else if (token.issueType == IssueType.DEFAULT) {
IERC20(token.addr).safeTransferFrom(from, to, amount);
} else {
assert(false);
}
return token;
}
function exit(
Token memory token,
address from,
address to,
uint256 amount
) internal returns (Token memory) {
require(token.exist, "RT: NOT_LISTED");
if (token.addr == address(0)) {
unsafeTransfer(from, to, amount);
} else if (token.issueType == IssueType.MINTABLE) {
IBridgeToken(token.addr).mint(to, amount);
} else if (token.issueType == IssueType.DEFAULT) {
IERC20(token.addr).safeTransfer(to, amount);
} else {
assert(false);
}
return token;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @title Version0
* @notice Version getter for contracts
**/
contract Version0 {
uint8 public constant VERSION = 0;
}
|
enter amount of tokens to protocol
|
function enter(
address token,
uint256 amount,
uint256 targetChainId
) external nonReentrant whenNotPaused {
require(token != address(0), "BR: ZERO_ADDRESS");
require(amount != 0, "BR: ZERO_AMOUNT");
RToken.Token memory localToken = tokenManager
.getLocal(token, targetChainId)
.enter(_msgSender(), address(this), amount);
emitEnter(localToken.addr, _msgSender(), amount, targetChainId);
}
| 12,217,412 |
./full_match/44787/0xd6eA75EDb63EeE110a67aa7514894477ea9cB2A2/sources/scripts/Bonus.sol
|
tokenWithdraw[_tokenId] = tokenWithdraw[_tokenId].add(_amount); starToken.transfer(_msgSender(), _amount);
|
function bonusWithdraw(uint256 _tokenId) public {
require(_msgSender() == starNFT.ownerOf(_tokenId), "not your token");
uint256 _amount = _getBonus(_tokenId);
emit Test(_msgSender(),_tokenId,_amount);
require(_amount > 0, "no bonus");
bonusWithdrawn = bonusWithdrawn.add(_amount);
}
| 13,289,086 |
pragma solidity 0.5.10;
import "../interfaces/IBlockRewardAuRa.sol";
import "../interfaces/IERC677.sol";
import "../interfaces/IGovernance.sol";
import "../interfaces/IStakingAuRa.sol";
import "../interfaces/IValidatorSetAuRa.sol";
import "../upgradeability/UpgradeableOwned.sol";
import "../libs/SafeMath.sol";
/// @dev Implements staking and withdrawal logic.
contract StakingAuRaBase is UpgradeableOwned, IStakingAuRa {
using SafeMath for uint256;
// =============================================== Storage ========================================================
// WARNING: since this contract is upgradeable, do not remove
// existing storage variables, do not change their order,
// and do not change their types!
uint256[] internal _pools;
uint256[] internal _poolsInactive;
uint256[] internal _poolsToBeElected;
uint256[] internal _poolsToBeRemoved;
uint256[] internal _poolsLikelihood;
uint256 internal _poolsLikelihoodSum;
mapping(uint256 => address[]) internal _poolDelegators;
mapping(uint256 => address[]) internal _poolDelegatorsInactive;
mapping(address => uint256[]) internal _delegatorPools;
mapping(address => mapping(uint256 => uint256)) internal _delegatorPoolsIndexes;
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal _stakeAmountByEpoch;
mapping(uint256 => uint256) internal _stakeInitial;
// Reserved storage slots to allow for layout changes in the future.
uint256[24] private ______gapForInternal;
/// @dev The limit of the minimum candidate stake (CANDIDATE_MIN_STAKE).
uint256 public candidateMinStake;
/// @dev The limit of the minimum delegator stake (DELEGATOR_MIN_STAKE).
uint256 public delegatorMinStake;
/// @dev The snapshot of tokens amount staked into the specified pool by the specified delegator
/// before the specified staking epoch. Used by the `claimReward` function.
/// The first parameter is the pool id, the second one is delegator's address,
/// the third one is staking epoch number.
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public delegatorStakeSnapshot;
/// @dev The current amount of staking tokens/coins ordered for withdrawal from the specified
/// pool by the specified staker. Used by the `orderWithdraw`, `claimOrderedWithdraw` and other functions.
/// The first parameter is the pool id, the second one is the staker address.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => uint256)) public orderedWithdrawAmount;
/// @dev The current total amount of staking tokens/coins ordered for withdrawal from
/// the specified pool by all of its stakers. Pool id is accepted as a parameter.
mapping(uint256 => uint256) public orderedWithdrawAmountTotal;
/// @dev The number of the staking epoch during which the specified staker ordered
/// the latest withdraw from the specified pool. Used by the `claimOrderedWithdraw` function
/// to allow the ordered amount to be claimed only in future staking epochs. The first parameter
/// is the pool id, the second one is the staker address.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => uint256)) public orderWithdrawEpoch;
/// @dev The delegator's index in the array returned by the `poolDelegators` getter.
/// Used by the `_removePoolDelegator` internal function. The first parameter is a pool id.
/// The second parameter is delegator's address.
/// If the value is zero, it may mean the array doesn't contain the delegator.
/// Check if the delegator is in the array using the `poolDelegators` getter.
mapping(uint256 => mapping(address => uint256)) public poolDelegatorIndex;
/// @dev The delegator's index in the `poolDelegatorsInactive` array.
/// Used by the `_removePoolDelegatorInactive` internal function.
/// A delegator is considered inactive if they have withdrawn their stake from
/// the specified pool but haven't yet claimed an ordered amount.
/// The first parameter is a pool id. The second parameter is delegator's address.
mapping(uint256 => mapping(address => uint256)) public poolDelegatorInactiveIndex;
/// @dev The pool's index in the array returned by the `getPoolsInactive` getter.
/// Used by the `_removePoolInactive` internal function. The pool id is accepted as a parameter.
mapping(uint256 => uint256) public poolInactiveIndex;
/// @dev The pool's index in the array returned by the `getPools` getter.
/// Used by the `_removePool` internal function. A pool id is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `isPoolActive` getter.
mapping(uint256 => uint256) public poolIndex;
/// @dev The pool's index in the array returned by the `getPoolsToBeElected` getter.
/// Used by the `_deletePoolToBeElected` and `_isPoolToBeElected` internal functions.
/// The pool id is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `getPoolsToBeElected` getter.
mapping(uint256 => uint256) public poolToBeElectedIndex;
/// @dev The pool's index in the array returned by the `getPoolsToBeRemoved` getter.
/// Used by the `_deletePoolToBeRemoved` internal function.
/// The pool id is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `getPoolsToBeRemoved` getter.
mapping(uint256 => uint256) public poolToBeRemovedIndex;
/// @dev A boolean flag indicating whether the reward was already taken
/// from the specified pool by the specified staker for the specified staking epoch.
/// The first parameter is the pool id, the second one is staker's address,
/// the third one is staking epoch number.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => mapping(uint256 => bool))) public rewardWasTaken;
/// @dev The amount of tokens currently staked into the specified pool by the specified
/// staker. Doesn't include the amount ordered for withdrawal.
/// The first parameter is the pool id, the second one is the staker address.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => uint256)) public stakeAmount;
/// @dev The number of staking epoch before which the specified delegator placed their first
/// stake into the specified pool. If this is equal to zero, it means the delegator never
/// staked into the specified pool. The first parameter is the pool id,
/// the second one is delegator's address.
mapping(uint256 => mapping(address => uint256)) public stakeFirstEpoch;
/// @dev The number of staking epoch before which the specified delegator withdrew their stake
/// from the specified pool. If this is equal to zero and `stakeFirstEpoch` is not zero, that means
/// the delegator still has some stake in the specified pool. The first parameter is the pool id,
/// the second one is delegator's address.
mapping(uint256 => mapping(address => uint256)) public stakeLastEpoch;
/// @dev The duration period (in blocks) at the end of staking epoch during which
/// participants are not allowed to stake/withdraw/order/claim their staking tokens/coins.
uint256 public stakeWithdrawDisallowPeriod;
/// @dev The serial number of the current staking epoch.
uint256 public stakingEpoch;
/// @dev The duration of a staking epoch in blocks.
uint256 public stakingEpochDuration;
/// @dev The number of the first block of the current staking epoch.
uint256 public stakingEpochStartBlock;
/// @dev Returns the total amount of staking tokens/coins currently staked into the specified pool.
/// Doesn't include the amount ordered for withdrawal.
/// The pool id is accepted as a parameter.
mapping(uint256 => uint256) public stakeAmountTotal;
/// @dev The address of the `ValidatorSetAuRa` contract.
IValidatorSetAuRa public validatorSetContract;
/// @dev The block number of the last change in this contract.
/// Can be used by Staking DApp.
uint256 public lastChangeBlock;
/// @dev The address of the `Governance` contract.
IGovernance public governanceContract;
// Reserved storage slots to allow for layout changes in the future.
uint256[23] private ______gapForPublic;
// ============================================== Constants =======================================================
/// @dev The max number of candidates (including validators). This limit was determined through stress testing.
uint256 public constant MAX_CANDIDATES = 3000;
// ================================================ Events ========================================================
/// @dev Emitted by the `_addPool` internal function to signal that
/// a new pool is created.
/// @param poolStakingAddress The staking address of newly added pool.
/// @param poolMiningAddress The mining address of newly added pool.
/// @param poolId The id of newly added pool.
event AddedPool(address indexed poolStakingAddress, address indexed poolMiningAddress, uint256 poolId);
/// @dev Emitted by the `claimOrderedWithdraw` function to signal the staker withdrew the specified
/// amount of requested tokens/coins from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker` withdrew the `amount`.
/// @param staker The address of the staker that withdrew the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the claim was made.
/// @param amount The withdrawal amount.
/// @param fromPoolId An id of the pool from which the `staker` withdrew the `amount`.
event ClaimedOrderedWithdrawal(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 fromPoolId
);
/// @dev Emitted by the `moveStake` function to signal the staker moved the specified
/// amount of stake from one pool to another during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker` moved the stake.
/// @param toPoolStakingAddress A staking address of the destination pool where the `staker` moved the stake.
/// @param staker The address of the staker who moved the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the `amount` was moved.
/// @param amount The stake amount which was moved.
/// @param fromPoolId An id of the pool from which the `staker` moved the stake.
/// @param toPoolId An id of the destination pool where the `staker` moved the stake.
event MovedStake(
address fromPoolStakingAddress,
address indexed toPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 fromPoolId,
uint256 toPoolId
);
/// @dev Emitted by the `orderWithdraw` function to signal the staker ordered the withdrawal of the
/// specified amount of their stake from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker`
/// ordered a withdrawal of the `amount`.
/// @param staker The address of the staker that ordered the withdrawal of the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the order was made.
/// @param amount The ordered withdrawal amount. Can be either positive or negative.
/// See the `orderWithdraw` function.
/// @param fromPoolId An id of the pool from which the `staker` ordered a withdrawal of the `amount`.
event OrderedWithdrawal(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
int256 amount,
uint256 fromPoolId
);
/// @dev Emitted by the `stake` function to signal the staker placed a stake of the specified
/// amount for the specified pool during the specified staking epoch.
/// @param toPoolStakingAddress A staking address of the pool into which the `staker` placed the stake.
/// @param staker The address of the staker that placed the stake.
/// @param stakingEpoch The serial number of the staking epoch during which the stake was made.
/// @param amount The stake amount.
/// @param toPoolId An id of the pool into which the `staker` placed the stake.
event PlacedStake(
address indexed toPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 toPoolId
);
/// @dev Emitted by the `withdraw` function to signal the staker withdrew the specified
/// amount of a stake from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker` withdrew the `amount`.
/// @param staker The address of staker that withdrew the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the withdrawal was made.
/// @param amount The withdrawal amount.
/// @param fromPoolId An id of the pool from which the `staker` withdrew the `amount`.
event WithdrewStake(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 fromPoolId
);
// ============================================== Modifiers =======================================================
/// @dev Ensures the transaction gas price is not zero.
modifier gasPriceIsValid() {
require(tx.gasprice != 0);
_;
}
/// @dev Ensures the caller is the BlockRewardAuRa contract address.
modifier onlyBlockRewardContract() {
require(msg.sender == validatorSetContract.blockRewardContract());
_;
}
/// @dev Ensures the `initialize` function was called before.
modifier onlyInitialized {
require(isInitialized());
_;
}
/// @dev Ensures the caller is the ValidatorSetAuRa contract address.
modifier onlyValidatorSetContract() {
require(msg.sender == address(validatorSetContract));
_;
}
// =============================================== Setters ========================================================
/// @dev Fallback function. Prevents direct sending native coins to this contract.
function () payable external {
revert();
}
/// @dev Adds a new candidate's pool to the list of active pools (see the `getPools` getter),
/// moves the specified amount of staking tokens/coins from the candidate's staking address
/// to the candidate's pool, and returns a unique id of the newly added pool.
/// A participant calls this function using their staking address when
/// they want to create a pool. This is a wrapper for the `stake` function.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used in that case.
/// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address
/// (msg.sender). This address cannot be equal to `msg.sender`.
/// @param _name A name of the pool as UTF-8 string (max length is 256 bytes).
/// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes).
function addPool(
uint256 _amount,
address _miningAddress,
string calldata _name,
string calldata _description
) external payable returns(uint256) {
return _addPool(_amount, msg.sender, _miningAddress, false, _name, _description);
}
/// @dev Adds the `unremovable validator` to either the `poolsToBeElected` or the `poolsToBeRemoved` array
/// depending on their own stake in their own pool when they become removable. This allows the
/// `ValidatorSetAuRa.newValidatorSet` function to recognize the unremovable validator as a regular removable pool.
/// Called by the `ValidatorSet.clearUnremovableValidator` function.
/// @param _unremovablePoolId The pool id of the unremovable validator.
function clearUnremovableValidator(uint256 _unremovablePoolId) external onlyValidatorSetContract {
require(_unremovablePoolId != 0);
if (stakeAmount[_unremovablePoolId][address(0)] != 0) {
_addPoolToBeElected(_unremovablePoolId);
_setLikelihood(_unremovablePoolId);
} else {
_addPoolToBeRemoved(_unremovablePoolId);
}
}
/// @dev Increments the serial number of the current staking epoch.
/// Called by the `ValidatorSetAuRa.newValidatorSet` at the last block of the finished staking epoch.
function incrementStakingEpoch() external onlyValidatorSetContract {
stakingEpoch++;
}
/// @dev Initializes the network parameters.
/// Can only be called by the constructor of the `InitializerAuRa` contract or owner.
/// @param _validatorSetContract The address of the `ValidatorSetAuRa` contract.
/// @param _governanceContract The address of the `Governance` contract.
/// @param _initialIds The array of initial validators' pool ids.
/// @param _delegatorMinStake The minimum allowed amount of delegator stake in Wei.
/// @param _candidateMinStake The minimum allowed amount of candidate/validator stake in Wei.
/// @param _stakingEpochDuration The duration of a staking epoch in blocks
/// (e.g., 120954 = 1 week for 5-seconds blocks in AuRa).
/// @param _stakingEpochStartBlock The number of the first block of initial staking epoch
/// (must be zero if the network is starting from genesis block).
/// @param _stakeWithdrawDisallowPeriod The duration period (in blocks) at the end of a staking epoch
/// during which participants cannot stake/withdraw/order/claim their staking tokens/coins
/// (e.g., 4320 = 6 hours for 5-seconds blocks in AuRa).
function initialize(
address _validatorSetContract,
address _governanceContract,
uint256[] calldata _initialIds,
uint256 _delegatorMinStake,
uint256 _candidateMinStake,
uint256 _stakingEpochDuration,
uint256 _stakingEpochStartBlock,
uint256 _stakeWithdrawDisallowPeriod
) external {
require(_validatorSetContract != address(0));
require(_initialIds.length > 0);
require(_delegatorMinStake != 0);
require(_candidateMinStake != 0);
require(_stakingEpochDuration != 0);
require(_stakingEpochDuration > _stakeWithdrawDisallowPeriod);
require(_stakeWithdrawDisallowPeriod != 0);
require(_getCurrentBlockNumber() == 0 || msg.sender == _admin());
require(!isInitialized()); // initialization can only be done once
validatorSetContract = IValidatorSetAuRa(_validatorSetContract);
governanceContract = IGovernance(_governanceContract);
uint256 unremovablePoolId = validatorSetContract.unremovableValidator();
for (uint256 i = 0; i < _initialIds.length; i++) {
require(_initialIds[i] != 0);
_addPoolActive(_initialIds[i], false);
if (_initialIds[i] != unremovablePoolId) {
_addPoolToBeRemoved(_initialIds[i]);
}
}
delegatorMinStake = _delegatorMinStake;
candidateMinStake = _candidateMinStake;
stakingEpochDuration = _stakingEpochDuration;
stakingEpochStartBlock = _stakingEpochStartBlock;
stakeWithdrawDisallowPeriod = _stakeWithdrawDisallowPeriod;
lastChangeBlock = _getCurrentBlockNumber();
}
/// @dev Makes initial validator stakes. Can only be called by the owner
/// before the network starts (after `initialize` is called but before `stakingEpochStartBlock`),
/// or after the network starts from genesis (`stakingEpochStartBlock` == 0).
/// Cannot be called more than once and cannot be called when starting from genesis.
/// Requires `StakingAuRa` contract balance to be equal to the `_totalAmount`.
/// @param _totalAmount The initial validator total stake amount (for all initial validators).
function initialValidatorStake(uint256 _totalAmount) external onlyOwner {
uint256 currentBlock = _getCurrentBlockNumber();
require(stakingEpoch == 0);
require(currentBlock < stakingEpochStartBlock || stakingEpochStartBlock == 0);
require(_thisBalance() == _totalAmount);
require(_totalAmount % _pools.length == 0);
uint256 stakingAmount = _totalAmount.div(_pools.length);
uint256 stakingEpochStartBlock_ = stakingEpochStartBlock;
// Temporarily set `stakingEpochStartBlock` to the current block number
// to avoid revert in the `_stake` function
stakingEpochStartBlock = currentBlock;
for (uint256 i = 0; i < _pools.length; i++) {
uint256 poolId = _pools[i];
address stakingAddress = validatorSetContract.stakingAddressById(poolId);
require(stakeAmount[poolId][address(0)] == 0);
_stake(stakingAddress, stakingAddress, stakingAmount);
_stakeInitial[poolId] = stakingAmount;
}
// Restore `stakingEpochStartBlock` value
stakingEpochStartBlock = stakingEpochStartBlock_;
}
/// @dev Removes a specified pool from the `pools` array (a list of active pools which can be retrieved by the
/// `getPools` getter). Called by the `ValidatorSetAuRa._removeMaliciousValidator` internal function
/// when a pool must be removed by the algorithm.
/// @param _poolId The id of the pool to be removed.
function removePool(uint256 _poolId) external onlyValidatorSetContract {
_removePool(_poolId);
}
/// @dev Removes pools which are in the `_poolsToBeRemoved` internal array from the `pools` array.
/// Called by the `ValidatorSetAuRa.newValidatorSet` function when pools must be removed by the algorithm.
function removePools() external onlyValidatorSetContract {
uint256[] memory poolsToRemove = _poolsToBeRemoved;
for (uint256 i = 0; i < poolsToRemove.length; i++) {
_removePool(poolsToRemove[i]);
}
}
/// @dev Removes the candidate's or validator's pool from the `pools` array (a list of active pools which
/// can be retrieved by the `getPools` getter). When a candidate or validator wants to remove their pool,
/// they should call this function from their staking address. A validator cannot remove their pool while
/// they are an `unremovable validator`.
function removeMyPool() external gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(msg.sender);
require(poolId != 0);
// initial validator cannot remove their pool during the initial staking epoch
require(stakingEpoch > 0 || !validatorSetContract.isValidatorById(poolId));
require(poolId != validatorSetContract.unremovableValidator());
_removePool(poolId);
}
/// @dev Sets the number of the first block in the upcoming staking epoch.
/// Called by the `ValidatorSetAuRa.newValidatorSet` function at the last block of a staking epoch.
/// @param _blockNumber The number of the very first block in the upcoming staking epoch.
function setStakingEpochStartBlock(uint256 _blockNumber) external onlyValidatorSetContract {
stakingEpochStartBlock = _blockNumber;
}
/// @dev Moves staking tokens/coins from one pool to another. A staker calls this function when they want
/// to move their tokens/coins from one pool to another without withdrawing their tokens/coins.
/// @param _fromPoolStakingAddress The staking address of the source pool.
/// @param _toPoolStakingAddress The staking address of the target pool.
/// @param _amount The amount of staking tokens/coins to be moved. The amount cannot exceed the value returned
/// by the `maxWithdrawAllowed` getter.
function moveStake(
address _fromPoolStakingAddress,
address _toPoolStakingAddress,
uint256 _amount
) external {
require(_fromPoolStakingAddress != _toPoolStakingAddress);
uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress);
uint256 toPoolId = validatorSetContract.idByStakingAddress(_toPoolStakingAddress);
address staker = msg.sender;
_withdraw(_fromPoolStakingAddress, staker, _amount);
_stake(_toPoolStakingAddress, staker, _amount);
emit MovedStake(
_fromPoolStakingAddress,
_toPoolStakingAddress,
staker,
stakingEpoch,
_amount,
fromPoolId,
toPoolId
);
}
/// @dev Moves the specified amount of staking tokens/coins from the staker's address to the staking address of
/// the specified pool. Actually, the amount is stored in a balance of this StakingAuRa contract.
/// A staker calls this function when they want to make a stake into a pool.
/// @param _toPoolStakingAddress The staking address of the pool where the tokens should be staked.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used instead.
function stake(address _toPoolStakingAddress, uint256 _amount) external payable {
_stake(_toPoolStakingAddress, _amount);
}
/// @dev Moves the specified amount of staking tokens/coins from the staking address of
/// the specified pool to the staker's address. A staker calls this function when they want to withdraw
/// their tokens/coins.
/// @param _fromPoolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn.
/// @param _amount The amount of tokens/coins to be withdrawn. The amount cannot exceed the value returned
/// by the `maxWithdrawAllowed` getter.
function withdraw(address _fromPoolStakingAddress, uint256 _amount) external {
address payable staker = msg.sender;
uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress);
_withdraw(_fromPoolStakingAddress, staker, _amount);
_sendWithdrawnStakeAmount(staker, _amount);
emit WithdrewStake(_fromPoolStakingAddress, staker, stakingEpoch, _amount, fromPoolId);
}
/// @dev Orders tokens/coins withdrawal from the staking address of the specified pool to the
/// staker's address. The requested tokens/coins can be claimed after the current staking epoch is complete using
/// the `claimOrderedWithdraw` function.
/// @param _poolStakingAddress The staking address of the pool from which the amount will be withdrawn.
/// @param _amount The amount to be withdrawn. A positive value means the staker wants to either set or
/// increase their withdrawal amount. A negative value means the staker wants to decrease a
/// withdrawal amount that was previously set. The amount cannot exceed the value returned by the
/// `maxWithdrawOrderAllowed` getter.
function orderWithdraw(address _poolStakingAddress, int256 _amount) external gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(_poolStakingAddress != address(0));
require(_amount != 0);
require(poolId != 0);
address staker = msg.sender;
address delegatorOrZero = (staker != _poolStakingAddress) ? staker : address(0);
require(_isWithdrawAllowed(poolId, delegatorOrZero != address(0)));
uint256 newOrderedAmount = orderedWithdrawAmount[poolId][delegatorOrZero];
uint256 newOrderedAmountTotal = orderedWithdrawAmountTotal[poolId];
uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero];
uint256 newStakeAmountTotal = stakeAmountTotal[poolId];
if (_amount > 0) {
uint256 amount = uint256(_amount);
// How much can `staker` order for withdrawal from `_poolStakingAddress` at the moment?
require(amount <= maxWithdrawOrderAllowed(_poolStakingAddress, staker));
newOrderedAmount = newOrderedAmount.add(amount);
newOrderedAmountTotal = newOrderedAmountTotal.add(amount);
newStakeAmount = newStakeAmount.sub(amount);
newStakeAmountTotal = newStakeAmountTotal.sub(amount);
orderWithdrawEpoch[poolId][delegatorOrZero] = stakingEpoch;
} else {
uint256 amount = uint256(-_amount);
newOrderedAmount = newOrderedAmount.sub(amount);
newOrderedAmountTotal = newOrderedAmountTotal.sub(amount);
newStakeAmount = newStakeAmount.add(amount);
newStakeAmountTotal = newStakeAmountTotal.add(amount);
}
orderedWithdrawAmount[poolId][delegatorOrZero] = newOrderedAmount;
orderedWithdrawAmountTotal[poolId] = newOrderedAmountTotal;
stakeAmount[poolId][delegatorOrZero] = newStakeAmount;
stakeAmountTotal[poolId] = newStakeAmountTotal;
if (staker == _poolStakingAddress) {
// Initial validator cannot withdraw their initial stake
require(newStakeAmount >= _stakeInitial[poolId]);
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and `candidateMinStake`
require(newStakeAmount == 0 || newStakeAmount >= candidateMinStake);
uint256 unremovablePoolId = validatorSetContract.unremovableValidator();
if (_amount > 0) { // if the validator orders the `_amount` for withdrawal
if (newStakeAmount == 0 && poolId != unremovablePoolId) {
// If the removable validator orders their entire stake,
// mark their pool as `to be removed`
_addPoolToBeRemoved(poolId);
}
} else {
// If the validator wants to reduce withdrawal value,
// add their pool as `active` if it hasn't already done
_addPoolActive(poolId, poolId != unremovablePoolId);
}
} else {
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and `delegatorMinStake`
require(newStakeAmount == 0 || newStakeAmount >= delegatorMinStake);
if (_amount > 0) { // if the delegator orders the `_amount` for withdrawal
if (newStakeAmount == 0) {
// If the delegator orders their entire stake,
// remove the delegator from delegator list of the pool
_removePoolDelegator(poolId, staker);
}
} else {
// If the delegator wants to reduce withdrawal value,
// add them to delegator list of the pool if it hasn't already done
_addPoolDelegator(poolId, staker);
}
// Remember stake movement to use it later in the `claimReward` function
_snapshotDelegatorStake(poolId, staker);
}
_setLikelihood(poolId);
emit OrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, _amount, poolId);
}
/// @dev Withdraws the staking tokens/coins from the specified pool ordered during the previous staking epochs with
/// the `orderWithdraw` function. The ordered amount can be retrieved by the `orderedWithdrawAmount` getter.
/// @param _poolStakingAddress The staking address of the pool from which the ordered tokens/coins are withdrawn.
function claimOrderedWithdraw(address _poolStakingAddress) external {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(poolId != 0);
address payable staker = msg.sender;
address delegatorOrZero = (staker != _poolStakingAddress) ? staker : address(0);
require(stakingEpoch > orderWithdrawEpoch[poolId][delegatorOrZero]);
require(!_isPoolBanned(poolId, delegatorOrZero != address(0)));
uint256 claimAmount = orderedWithdrawAmount[poolId][delegatorOrZero];
require(claimAmount != 0);
orderedWithdrawAmount[poolId][delegatorOrZero] = 0;
orderedWithdrawAmountTotal[poolId] = orderedWithdrawAmountTotal[poolId].sub(claimAmount);
if (stakeAmount[poolId][delegatorOrZero] == 0) {
_withdrawCheckPool(poolId, _poolStakingAddress, staker);
}
_sendWithdrawnStakeAmount(staker, claimAmount);
emit ClaimedOrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, claimAmount, poolId);
}
/// @dev Sets (updates) the limit of the minimum candidate stake (CANDIDATE_MIN_STAKE).
/// Can only be called by the `owner`.
/// @param _minStake The value of a new limit in Wei.
function setCandidateMinStake(uint256 _minStake) external onlyOwner onlyInitialized {
candidateMinStake = _minStake;
}
/// @dev Sets (updates) the limit of the minimum delegator stake (DELEGATOR_MIN_STAKE).
/// Can only be called by the `owner`.
/// @param _minStake The value of a new limit in Wei.
function setDelegatorMinStake(uint256 _minStake) external onlyOwner onlyInitialized {
delegatorMinStake = _minStake;
}
// =============================================== Getters ========================================================
/// @dev Returns an array of the current active pools (the pool ids of candidates and validators).
/// The size of the array cannot exceed MAX_CANDIDATES. A pool can be added to this array with the `_addPoolActive`
/// internal function which is called by the `stake` or `orderWithdraw` function. A pool is considered active
/// if its address has at least the minimum stake and this stake is not ordered to be withdrawn.
function getPools() external view returns(uint256[] memory) {
return _pools;
}
/// @dev Returns an array of the current inactive pools (the pool ids of former candidates).
/// A pool can be added to this array with the `_addPoolInactive` internal function which is called
/// by `_removePool`. A pool is considered inactive if it is banned for some reason, if its address
/// has zero stake, or if its entire stake is ordered to be withdrawn.
function getPoolsInactive() external view returns(uint256[] memory) {
return _poolsInactive;
}
/// @dev Returns the array of stake amounts for each corresponding
/// address in the `poolsToBeElected` array (see the `getPoolsToBeElected` getter) and a sum of these amounts.
/// Used by the `ValidatorSetAuRa.newValidatorSet` function when randomly selecting new validators at the last
/// block of a staking epoch. An array value is updated every time any staked amount is changed in this pool
/// (see the `_setLikelihood` internal function).
/// @return `uint256[] likelihoods` - The array of the coefficients. The array length is always equal to the length
/// of the `poolsToBeElected` array.
/// `uint256 sum` - The total sum of the amounts.
function getPoolsLikelihood() external view returns(uint256[] memory likelihoods, uint256 sum) {
return (_poolsLikelihood, _poolsLikelihoodSum);
}
/// @dev Returns the list of pools (their ids) which will participate in a new validator set
/// selection process in the `ValidatorSetAuRa.newValidatorSet` function. This is an array of pools
/// which will be considered as candidates when forming a new validator set (at the last block of a staking epoch).
/// This array is kept updated by the `_addPoolToBeElected` and `_deletePoolToBeElected` internal functions.
function getPoolsToBeElected() external view returns(uint256[] memory) {
return _poolsToBeElected;
}
/// @dev Returns the list of pools (their ids) which will be removed by the
/// `ValidatorSetAuRa.newValidatorSet` function from the active `pools` array (at the last block
/// of a staking epoch). This array is kept updated by the `_addPoolToBeRemoved`
/// and `_deletePoolToBeRemoved` internal functions. A pool is added to this array when the pool's
/// address withdraws (or orders) all of its own staking tokens from the pool, inactivating the pool.
function getPoolsToBeRemoved() external view returns(uint256[] memory) {
return _poolsToBeRemoved;
}
/// @dev Returns the list of pool ids into which the specified delegator have ever staked.
/// @param _delegator The delegator address.
/// @param _offset The index in the array at which the reading should start. Ignored if the `_length` is 0.
/// @param _length The max number of items to return.
function getDelegatorPools(
address _delegator,
uint256 _offset,
uint256 _length
) external view returns(uint256[] memory result) {
uint256[] storage delegatorPools = _delegatorPools[_delegator];
if (_length == 0) {
return delegatorPools;
}
uint256 maxLength = delegatorPools.length.sub(_offset);
result = new uint256[](_length > maxLength ? maxLength : _length);
for (uint256 i = 0; i < result.length; i++) {
result[i] = delegatorPools[_offset + i];
}
}
/// @dev Returns the length of the list of pools into which the specified delegator have ever staked.
/// @param _delegator The delegator address.
function getDelegatorPoolsLength(address _delegator) external view returns(uint256) {
return _delegatorPools[_delegator].length;
}
/// @dev Determines whether staking/withdrawal operations are allowed at the moment.
/// Used by all staking/withdrawal functions.
function areStakeAndWithdrawAllowed() public view returns(bool) {
uint256 currentBlock = _getCurrentBlockNumber();
if (currentBlock < stakingEpochStartBlock) return false;
uint256 allowedDuration = stakingEpochDuration - stakeWithdrawDisallowPeriod;
if (stakingEpochStartBlock == 0) allowedDuration++;
return currentBlock - stakingEpochStartBlock < allowedDuration;
}
/// @dev Returns a boolean flag indicating if the `initialize` function has been called.
function isInitialized() public view returns(bool) {
return validatorSetContract != IValidatorSetAuRa(0);
}
/// @dev Returns a flag indicating whether a specified id is in the `pools` array.
/// See the `getPools` getter.
/// @param _poolId An id of the pool.
function isPoolActive(uint256 _poolId) public view returns(bool) {
uint256 index = poolIndex[_poolId];
return index < _pools.length && _pools[index] == _poolId;
}
/// @dev Returns the maximum amount which can be withdrawn from the specified pool by the specified staker
/// at the moment. Used by the `withdraw` and `moveStake` functions.
/// @param _poolStakingAddress The pool staking address from which the withdrawal will be made.
/// @param _staker The staker address that is going to withdraw.
function maxWithdrawAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0);
bool isDelegator = _poolStakingAddress != _staker;
if (!_isWithdrawAllowed(poolId, isDelegator)) {
return 0;
}
uint256 canWithdraw = stakeAmount[poolId][delegatorOrZero];
if (!isDelegator) {
// Initial validator cannot withdraw their initial stake
canWithdraw = canWithdraw.sub(_stakeInitial[poolId]);
}
if (!validatorSetContract.isValidatorOrPending(poolId)) {
// The pool is not a validator and is not going to become one,
// so the staker can only withdraw staked amount minus already
// ordered amount
return canWithdraw;
}
// The pool is a validator (active or pending), so the staker can only
// withdraw staked amount minus already ordered amount but
// no more than the amount staked during the current staking epoch
uint256 stakedDuringEpoch = stakeAmountByCurrentEpoch(poolId, delegatorOrZero);
if (canWithdraw > stakedDuringEpoch) {
canWithdraw = stakedDuringEpoch;
}
return canWithdraw;
}
/// @dev Returns the maximum amount which can be ordered to be withdrawn from the specified pool by the
/// specified staker at the moment. Used by the `orderWithdraw` function.
/// @param _poolStakingAddress The pool staking address from which the withdrawal will be ordered.
/// @param _staker The staker address that is going to order the withdrawal.
function maxWithdrawOrderAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
bool isDelegator = _poolStakingAddress != _staker;
address delegatorOrZero = isDelegator ? _staker : address(0);
if (!_isWithdrawAllowed(poolId, isDelegator)) {
return 0;
}
if (!validatorSetContract.isValidatorOrPending(poolId)) {
// If the pool is a candidate (not an active validator and not pending one),
// no one can order withdrawal from the `_poolStakingAddress`, but
// anyone can withdraw immediately (see the `maxWithdrawAllowed` getter)
return 0;
}
// If the pool is an active or pending validator, the staker can order withdrawal
// up to their total staking amount minus an already ordered amount
// minus an amount staked during the current staking epoch
uint256 canOrder = stakeAmount[poolId][delegatorOrZero];
if (!isDelegator) {
// Initial validator cannot withdraw their initial stake
canOrder = canOrder.sub(_stakeInitial[poolId]);
}
return canOrder.sub(stakeAmountByCurrentEpoch(poolId, delegatorOrZero));
}
/// @dev Returns an array of the current active delegators of the specified pool.
/// A delegator is considered active if they have staked into the specified
/// pool and their stake is not ordered to be withdrawn.
/// @param _poolId The pool id.
function poolDelegators(uint256 _poolId) public view returns(address[] memory) {
return _poolDelegators[_poolId];
}
/// @dev Returns an array of the current inactive delegators of the specified pool.
/// A delegator is considered inactive if their entire stake is ordered to be withdrawn
/// but not yet claimed.
/// @param _poolId The pool id.
function poolDelegatorsInactive(uint256 _poolId) public view returns(address[] memory) {
return _poolDelegatorsInactive[_poolId];
}
/// @dev Returns the amount of staking tokens/coins staked into the specified pool by the specified staker
/// during the current staking epoch (see the `stakingEpoch` getter).
/// Used by the `stake`, `withdraw`, and `orderWithdraw` functions.
/// @param _poolId The pool id.
/// @param _delegatorOrZero The delegator's address (or zero address if the staker is the pool itself).
function stakeAmountByCurrentEpoch(uint256 _poolId, address _delegatorOrZero)
public
view
returns(uint256)
{
return _stakeAmountByEpoch[_poolId][_delegatorOrZero][stakingEpoch];
}
/// @dev Returns the number of the last block of the current staking epoch.
function stakingEpochEndBlock() public view returns(uint256) {
uint256 startBlock = stakingEpochStartBlock;
return startBlock + stakingEpochDuration - (startBlock == 0 ? 0 : 1);
}
// ============================================== Internal ========================================================
/// @dev Adds the specified pool id to the array of active pools returned by
/// the `getPools` getter. Used by the `stake`, `addPool`, and `orderWithdraw` functions.
/// @param _poolId The pool id added to the array of active pools.
/// @param _toBeElected The boolean flag which defines whether the specified id should be
/// added simultaneously to the `poolsToBeElected` array. See the `getPoolsToBeElected` getter.
function _addPoolActive(uint256 _poolId, bool _toBeElected) internal {
if (!isPoolActive(_poolId)) {
poolIndex[_poolId] = _pools.length;
_pools.push(_poolId);
require(_pools.length <= _getMaxCandidates());
}
_removePoolInactive(_poolId);
if (_toBeElected) {
_addPoolToBeElected(_poolId);
}
}
/// @dev Adds the specified pool id to the array of inactive pools returned by
/// the `getPoolsInactive` getter. Used by the `_removePool` internal function.
/// @param _poolId The pool id added to the array of inactive pools.
function _addPoolInactive(uint256 _poolId) internal {
uint256 index = poolInactiveIndex[_poolId];
uint256 length = _poolsInactive.length;
if (index >= length || _poolsInactive[index] != _poolId) {
poolInactiveIndex[_poolId] = length;
_poolsInactive.push(_poolId);
}
}
/// @dev Adds the specified pool id to the array of pools returned by the `getPoolsToBeElected`
/// getter. Used by the `_addPoolActive` internal function. See the `getPoolsToBeElected` getter.
/// @param _poolId The pool id added to the `poolsToBeElected` array.
function _addPoolToBeElected(uint256 _poolId) internal {
uint256 index = poolToBeElectedIndex[_poolId];
uint256 length = _poolsToBeElected.length;
if (index >= length || _poolsToBeElected[index] != _poolId) {
poolToBeElectedIndex[_poolId] = length;
_poolsToBeElected.push(_poolId);
_poolsLikelihood.push(0); // assumes the likelihood is set with `_setLikelihood` function hereinafter
}
_deletePoolToBeRemoved(_poolId);
}
/// @dev Adds the specified pool id to the array of pools returned by the `getPoolsToBeRemoved`
/// getter. Used by withdrawal functions. See the `getPoolsToBeRemoved` getter.
/// @param _poolId The pool id added to the `poolsToBeRemoved` array.
function _addPoolToBeRemoved(uint256 _poolId) internal {
uint256 index = poolToBeRemovedIndex[_poolId];
uint256 length = _poolsToBeRemoved.length;
if (index >= length || _poolsToBeRemoved[index] != _poolId) {
poolToBeRemovedIndex[_poolId] = length;
_poolsToBeRemoved.push(_poolId);
}
_deletePoolToBeElected(_poolId);
}
/// @dev Deletes the specified pool id from the array of pools returned by the
/// `getPoolsToBeElected` getter. Used by the `_addPoolToBeRemoved` and `_removePool` internal functions.
/// See the `getPoolsToBeElected` getter.
/// @param _poolId The pool id deleted from the `poolsToBeElected` array.
function _deletePoolToBeElected(uint256 _poolId) internal {
if (_poolsToBeElected.length != _poolsLikelihood.length) return;
uint256 indexToDelete = poolToBeElectedIndex[_poolId];
if (_poolsToBeElected.length > indexToDelete && _poolsToBeElected[indexToDelete] == _poolId) {
if (_poolsLikelihoodSum >= _poolsLikelihood[indexToDelete]) {
_poolsLikelihoodSum -= _poolsLikelihood[indexToDelete];
} else {
_poolsLikelihoodSum = 0;
}
uint256 lastPoolIndex = _poolsToBeElected.length - 1;
uint256 lastPool = _poolsToBeElected[lastPoolIndex];
_poolsToBeElected[indexToDelete] = lastPool;
_poolsLikelihood[indexToDelete] = _poolsLikelihood[lastPoolIndex];
poolToBeElectedIndex[lastPool] = indexToDelete;
poolToBeElectedIndex[_poolId] = 0;
_poolsToBeElected.length--;
_poolsLikelihood.length--;
}
}
/// @dev Deletes the specified pool id from the array of pools returned by the
/// `getPoolsToBeRemoved` getter. Used by the `_addPoolToBeElected` and `_removePool` internal functions.
/// See the `getPoolsToBeRemoved` getter.
/// @param _poolId The pool id deleted from the `poolsToBeRemoved` array.
function _deletePoolToBeRemoved(uint256 _poolId) internal {
uint256 indexToDelete = poolToBeRemovedIndex[_poolId];
if (_poolsToBeRemoved.length > indexToDelete && _poolsToBeRemoved[indexToDelete] == _poolId) {
uint256 lastPool = _poolsToBeRemoved[_poolsToBeRemoved.length - 1];
_poolsToBeRemoved[indexToDelete] = lastPool;
poolToBeRemovedIndex[lastPool] = indexToDelete;
poolToBeRemovedIndex[_poolId] = 0;
_poolsToBeRemoved.length--;
}
}
/// @dev Removes the specified pool id from the array of active pools returned by
/// the `getPools` getter. Used by the `removePool`, `removeMyPool`, and withdrawal functions.
/// @param _poolId The pool id removed from the array of active pools.
function _removePool(uint256 _poolId) internal {
uint256 indexToRemove = poolIndex[_poolId];
if (_pools.length > indexToRemove && _pools[indexToRemove] == _poolId) {
uint256 lastPool = _pools[_pools.length - 1];
_pools[indexToRemove] = lastPool;
poolIndex[lastPool] = indexToRemove;
poolIndex[_poolId] = 0;
_pools.length--;
}
if (_isPoolEmpty(_poolId)) {
_removePoolInactive(_poolId);
} else {
_addPoolInactive(_poolId);
}
_deletePoolToBeElected(_poolId);
_deletePoolToBeRemoved(_poolId);
lastChangeBlock = _getCurrentBlockNumber();
}
/// @dev Removes the specified pool id from the array of inactive pools returned by
/// the `getPoolsInactive` getter. Used by withdrawal functions, by the `_addPoolActive` and
/// `_removePool` internal functions.
/// @param _poolId The pool id removed from the array of inactive pools.
function _removePoolInactive(uint256 _poolId) internal {
uint256 indexToRemove = poolInactiveIndex[_poolId];
if (_poolsInactive.length > indexToRemove && _poolsInactive[indexToRemove] == _poolId) {
uint256 lastPool = _poolsInactive[_poolsInactive.length - 1];
_poolsInactive[indexToRemove] = lastPool;
poolInactiveIndex[lastPool] = indexToRemove;
poolInactiveIndex[_poolId] = 0;
_poolsInactive.length--;
}
}
/// @dev Used by `addPool` and `onTokenTransfer` functions. See their descriptions and code.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used in that case.
/// @param _stakingAddress The staking address of the new candidate.
/// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address
/// (msg.sender). This address cannot be equal to `_stakingAddress`.
/// @param _byOnTokenTransfer A boolean flag defining whether this internal function is called
/// by the `onTokenTransfer` function.
/// @param _name A name of the pool as UTF-8 string (max length is 256 bytes).
/// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes).
function _addPool(
uint256 _amount,
address _stakingAddress,
address _miningAddress,
bool _byOnTokenTransfer,
string memory _name,
string memory _description
) internal returns(uint256) {
uint256 poolId = validatorSetContract.addPool(_miningAddress, _stakingAddress, _name, _description);
if (_byOnTokenTransfer) {
_stake(_stakingAddress, _stakingAddress, _amount);
} else {
_stake(_stakingAddress, _amount);
}
emit AddedPool(_stakingAddress, _miningAddress, poolId);
return poolId;
}
/// @dev Adds the specified address to the array of the current active delegators of the specified pool.
/// Used by the `stake` and `orderWithdraw` functions. See the `poolDelegators` getter.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _addPoolDelegator(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegators[_poolId];
uint256 index = poolDelegatorIndex[_poolId][_delegator];
uint256 length = delegators.length;
if (index >= length || delegators[index] != _delegator) {
poolDelegatorIndex[_poolId][_delegator] = length;
delegators.push(_delegator);
}
_removePoolDelegatorInactive(_poolId, _delegator);
}
/// @dev Adds the specified address to the array of the current inactive delegators of the specified pool.
/// Used by the `_removePoolDelegator` internal function.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _addPoolDelegatorInactive(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegatorsInactive[_poolId];
uint256 index = poolDelegatorInactiveIndex[_poolId][_delegator];
uint256 length = delegators.length;
if (index >= length || delegators[index] != _delegator) {
poolDelegatorInactiveIndex[_poolId][_delegator] = length;
delegators.push(_delegator);
}
}
/// @dev Removes the specified address from the array of the current active delegators of the specified pool.
/// Used by the withdrawal functions. See the `poolDelegators` getter.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _removePoolDelegator(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegators[_poolId];
uint256 indexToRemove = poolDelegatorIndex[_poolId][_delegator];
if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) {
address lastDelegator = delegators[delegators.length - 1];
delegators[indexToRemove] = lastDelegator;
poolDelegatorIndex[_poolId][lastDelegator] = indexToRemove;
poolDelegatorIndex[_poolId][_delegator] = 0;
delegators.length--;
}
if (orderedWithdrawAmount[_poolId][_delegator] != 0) {
_addPoolDelegatorInactive(_poolId, _delegator);
} else {
_removePoolDelegatorInactive(_poolId, _delegator);
}
}
/// @dev Removes the specified address from the array of the inactive delegators of the specified pool.
/// Used by the `_addPoolDelegator` and `_removePoolDelegator` internal functions.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _removePoolDelegatorInactive(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegatorsInactive[_poolId];
uint256 indexToRemove = poolDelegatorInactiveIndex[_poolId][_delegator];
if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) {
address lastDelegator = delegators[delegators.length - 1];
delegators[indexToRemove] = lastDelegator;
poolDelegatorInactiveIndex[_poolId][lastDelegator] = indexToRemove;
poolDelegatorInactiveIndex[_poolId][_delegator] = 0;
delegators.length--;
}
}
function _sendWithdrawnStakeAmount(address payable _to, uint256 _amount) internal;
/// @dev Calculates (updates) the probability of being selected as a validator for the specified pool
/// and updates the total sum of probability coefficients. Actually, the probability is equal to the
/// amount totally staked into the pool. See the `getPoolsLikelihood` getter.
/// Used by the staking and withdrawal functions.
/// @param _poolId An id of the pool for which the probability coefficient must be updated.
function _setLikelihood(uint256 _poolId) internal {
lastChangeBlock = _getCurrentBlockNumber();
(bool isToBeElected, uint256 index) = _isPoolToBeElected(_poolId);
if (!isToBeElected) return;
uint256 oldValue = _poolsLikelihood[index];
uint256 newValue = stakeAmountTotal[_poolId];
_poolsLikelihood[index] = newValue;
if (newValue >= oldValue) {
_poolsLikelihoodSum = _poolsLikelihoodSum.add(newValue - oldValue);
} else {
_poolsLikelihoodSum = _poolsLikelihoodSum.sub(oldValue - newValue);
}
}
/// @dev Makes a snapshot of the amount currently staked by the specified delegator
/// into the specified pool. Used by the `orderWithdraw`, `_stake`, and `_withdraw` functions.
/// @param _poolId An id of the pool.
/// @param _delegator The address of the delegator.
function _snapshotDelegatorStake(uint256 _poolId, address _delegator) internal {
uint256 nextStakingEpoch = stakingEpoch + 1;
uint256 newAmount = stakeAmount[_poolId][_delegator];
delegatorStakeSnapshot[_poolId][_delegator][nextStakingEpoch] =
(newAmount != 0) ? newAmount : uint256(-1);
if (stakeFirstEpoch[_poolId][_delegator] == 0) {
stakeFirstEpoch[_poolId][_delegator] = nextStakingEpoch;
}
stakeLastEpoch[_poolId][_delegator] = (newAmount == 0) ? nextStakingEpoch : 0;
}
function _stake(address _toPoolStakingAddress, uint256 _amount) internal;
/// @dev The internal function used by the `_stake`, `moveStake`, `initialValidatorStake`, `_addPool` functions.
/// See the `stake` public function for more details.
/// @param _poolStakingAddress The staking address of the pool where the tokens/coins should be staked.
/// @param _staker The staker's address.
/// @param _amount The amount of tokens/coins to be staked.
function _stake(
address _poolStakingAddress,
address _staker,
uint256 _amount
) internal gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(_poolStakingAddress != address(0));
require(poolId != 0);
require(_amount != 0);
require(!validatorSetContract.isValidatorIdBanned(poolId));
require(areStakeAndWithdrawAllowed());
address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0);
uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero].add(_amount);
if (_staker == _poolStakingAddress) {
// The staked amount must be at least CANDIDATE_MIN_STAKE
require(newStakeAmount >= candidateMinStake);
} else {
// The staked amount must be at least DELEGATOR_MIN_STAKE
require(newStakeAmount >= delegatorMinStake);
// The delegator cannot stake into the pool of the candidate which hasn't self-staked.
// Also, that candidate shouldn't want to withdraw all their funds.
require(stakeAmount[poolId][address(0)] != 0);
}
stakeAmount[poolId][delegatorOrZero] = newStakeAmount;
_stakeAmountByEpoch[poolId][delegatorOrZero][stakingEpoch] =
stakeAmountByCurrentEpoch(poolId, delegatorOrZero).add(_amount);
stakeAmountTotal[poolId] = stakeAmountTotal[poolId].add(_amount);
if (_staker == _poolStakingAddress) { // `staker` places a stake for himself and becomes a candidate
// Add `_poolStakingAddress` to the array of pools
_addPoolActive(poolId, poolId != validatorSetContract.unremovableValidator());
} else {
// Add `_staker` to the array of pool's delegators
_addPoolDelegator(poolId, _staker);
// Save/update amount value staked by the delegator
_snapshotDelegatorStake(poolId, _staker);
// Remember that the delegator (`_staker`) has ever staked into `_poolStakingAddress`
uint256[] storage delegatorPools = _delegatorPools[_staker];
uint256 delegatorPoolsLength = delegatorPools.length;
uint256 index = _delegatorPoolsIndexes[_staker][poolId];
bool neverStakedBefore = index >= delegatorPoolsLength || delegatorPools[index] != poolId;
if (neverStakedBefore) {
_delegatorPoolsIndexes[_staker][poolId] = delegatorPoolsLength;
delegatorPools.push(poolId);
}
if (delegatorPoolsLength == 0) {
// If this is the first time the delegator stakes,
// make sure the delegator has never been a mining address
require(validatorSetContract.hasEverBeenMiningAddress(_staker) == 0);
}
}
_setLikelihood(poolId);
emit PlacedStake(_poolStakingAddress, _staker, stakingEpoch, _amount, poolId);
}
/// @dev The internal function used by the `withdraw` and `moveStake` functions.
/// See the `withdraw` public function for more details.
/// @param _poolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn.
/// @param _staker The staker's address.
/// @param _amount The amount of the tokens/coins to be withdrawn.
function _withdraw(
address _poolStakingAddress,
address _staker,
uint256 _amount
) internal gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(_poolStakingAddress != address(0));
require(_amount != 0);
require(poolId != 0);
// How much can `_staker` withdraw from `_poolStakingAddress` at the moment?
require(_amount <= maxWithdrawAllowed(_poolStakingAddress, _staker));
address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0);
uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero].sub(_amount);
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and min allowed stake
uint256 minAllowedStake;
if (_poolStakingAddress == _staker) {
// initial validator cannot withdraw their initial stake
require(newStakeAmount >= _stakeInitial[poolId]);
minAllowedStake = candidateMinStake;
} else {
minAllowedStake = delegatorMinStake;
}
require(newStakeAmount == 0 || newStakeAmount >= minAllowedStake);
stakeAmount[poolId][delegatorOrZero] = newStakeAmount;
uint256 amountByEpoch = stakeAmountByCurrentEpoch(poolId, delegatorOrZero);
_stakeAmountByEpoch[poolId][delegatorOrZero][stakingEpoch] =
amountByEpoch >= _amount ? amountByEpoch - _amount : 0;
stakeAmountTotal[poolId] = stakeAmountTotal[poolId].sub(_amount);
if (newStakeAmount == 0) {
_withdrawCheckPool(poolId, _poolStakingAddress, _staker);
}
if (_staker != _poolStakingAddress) {
_snapshotDelegatorStake(poolId, _staker);
}
_setLikelihood(poolId);
}
/// @dev The internal function used by the `_withdraw` and `claimOrderedWithdraw` functions.
/// Contains a common logic for these functions.
/// @param _poolId The id of the pool from which the tokens/coins are withdrawn.
/// @param _poolStakingAddress The staking address of the pool from which the tokens/coins are withdrawn.
/// @param _staker The staker's address.
function _withdrawCheckPool(uint256 _poolId, address _poolStakingAddress, address _staker) internal {
if (_staker == _poolStakingAddress) {
uint256 unremovablePoolId = validatorSetContract.unremovableValidator();
if (_poolId != unremovablePoolId) {
if (validatorSetContract.isValidatorById(_poolId)) {
_addPoolToBeRemoved(_poolId);
} else {
_removePool(_poolId);
}
}
} else {
_removePoolDelegator(_poolId, _staker);
if (_isPoolEmpty(_poolId)) {
_removePoolInactive(_poolId);
}
}
}
/// @dev Returns the current block number. Needed mostly for unit tests.
function _getCurrentBlockNumber() internal view returns(uint256) {
return block.number;
}
/// @dev The internal function used by the `claimReward` function and `getRewardAmount` getter.
/// Finds the stake amount made by a specified delegator into a specified pool before a specified
/// staking epoch.
function _getDelegatorStake(
uint256 _epoch,
uint256 _firstEpoch,
uint256 _prevDelegatorStake,
uint256 _poolId,
address _delegator
) internal view returns(uint256 delegatorStake) {
while (true) {
delegatorStake = delegatorStakeSnapshot[_poolId][_delegator][_epoch];
if (delegatorStake != 0) {
delegatorStake = (delegatorStake == uint256(-1)) ? 0 : delegatorStake;
break;
} else if (_epoch == _firstEpoch) {
delegatorStake = _prevDelegatorStake;
break;
}
_epoch--;
}
}
/// @dev Returns the max number of candidates (including validators). See the MAX_CANDIDATES constant.
/// Needed mostly for unit tests.
function _getMaxCandidates() internal pure returns(uint256) {
return MAX_CANDIDATES;
}
/// @dev Returns a boolean flag indicating whether the specified pool is fully empty
/// (all stakes are withdrawn including ordered withdrawals).
/// @param _poolId An id of the pool.
function _isPoolEmpty(uint256 _poolId) internal view returns(bool) {
return stakeAmountTotal[_poolId] == 0 && orderedWithdrawAmountTotal[_poolId] == 0;
}
/// @dev Determines if the specified pool is in the `poolsToBeElected` array. See the `getPoolsToBeElected` getter.
/// Used by the `_setLikelihood` internal function.
/// @param _poolId An id of the pool.
/// @return `bool toBeElected` - The boolean flag indicating whether the `_poolId` is in the
/// `poolsToBeElected` array.
/// `uint256 index` - The position of the item in the `poolsToBeElected` array if `toBeElected` is `true`.
function _isPoolToBeElected(uint256 _poolId) internal view returns(bool toBeElected, uint256 index) {
index = poolToBeElectedIndex[_poolId];
if (_poolsToBeElected.length > index && _poolsToBeElected[index] == _poolId) {
return (true, index);
}
return (false, 0);
}
/// @dev Returns `true` if the specified pool is banned or the pool is under a governance ballot.
/// Used by the `_isWithdrawAllowed` internal function and the `claimOrderedWithdraw` function.
/// @param _poolId An id of the validator's pool.
/// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator.
function _isPoolBanned(uint256 _poolId, bool _isDelegator) internal view returns(bool) {
if (_isDelegator) {
if (validatorSetContract.areIdDelegatorsBanned(_poolId)) {
// The delegator cannot withdraw from the banned validator pool until the ban is expired
return true;
}
} else {
if (validatorSetContract.isValidatorIdBanned(_poolId)) {
// The banned validator cannot withdraw from their pool until the ban is expired
return true;
} else if (governanceContract != IGovernance(0) && governanceContract.isValidatorUnderBallot(_poolId)) {
// There is an active ballot in the Governance contract for this validator removal
return true;
}
}
return false;
}
/// @dev Returns `true` if withdrawal from the pool of the specified candidate/validator is allowed at the moment.
/// Used by all withdrawal functions.
/// @param _poolId An id of the validator's pool.
/// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator.
function _isWithdrawAllowed(uint256 _poolId, bool _isDelegator) internal view returns(bool) {
if (_isPoolBanned(_poolId, _isDelegator)) {
return false;
}
if (!areStakeAndWithdrawAllowed()) {
return false;
}
return true;
}
/// @dev Returns the balance of this contract in staking tokens or coins
/// depending on implementation.
function _thisBalance() internal view returns(uint256);
}
|
Moves the specified amount of staking tokens/coins from the staking address of the specified pool to the staker's address. A staker calls this function when they want to withdraw their tokens/coins. _fromPoolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn. _amount The amount of tokens/coins to be withdrawn. The amount cannot exceed the value returned by the `maxWithdrawAllowed` getter.
|
function withdraw(address _fromPoolStakingAddress, uint256 _amount) external {
address payable staker = msg.sender;
uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress);
_withdraw(_fromPoolStakingAddress, staker, _amount);
_sendWithdrawnStakeAmount(staker, _amount);
emit WithdrewStake(_fromPoolStakingAddress, staker, stakingEpoch, _amount, fromPoolId);
}
| 13,080,975 |
pragma solidity ^0.4.24;
/*
* Creator: XERA
*/
/*
* Abstract Token Smart Contract
*
*/
/*
* Safe Math Smart Contract.
* https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract 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 safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* ERC-20 standard token interface, as defined
* <a href="http://github.com/ethereum/EIPs/issues/20">here</a>.
*/
contract Token {
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* Abstract Token Smart Contract that could be used as a base contract for
* ERC-20 token contracts.
*/
contract AbstractToken is Token, SafeMath {
/**
* Create new Abstract Token contract.
*/
function AbstractToken () {
// Do nothing
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return accounts [_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
* accounts [_to] + _value > accounts [_to] for overflow check
* which is already in safeMath
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer (msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
* accounts [_to] + _value > accounts [_to] for overflow check
* which is already in safeMath
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer(_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
* @param _spender address to allow the owner of to transfer tokens from message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value) returns (bool success) {
allowances [msg.sender][_spender] = _value;
emit Approval (msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance(address _owner, address _spender) constant
returns (uint256 remaining) {
return allowances [_owner][_spender];
}
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) accounts;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) private allowances;
}
/**
* XERA Token Smart Contract.
*/
contract XERA is AbstractToken {
/**
* Maximum allowed number of tokens in circulation.
* tokenSupply = tokensIActuallyWant * (10 ^ decimals)
*/
uint256 constant MAX_TOKEN_COUNT = 95000000 * (10**18);
/**
* Address of the owner of this smart contract.
*/
address private owner;
/**
* Frozen account list holder
*/
mapping (address => bool) private frozenAccount;
/**
* Burning account list holder
*/
mapping (address => bool) private burningAccount;
/**
* Current number of tokens in circulation.
*/
uint256 tokenCount = 0;
/**
* True if tokens transfers are currently frozen, false otherwise.
*/
bool frozen = false;
/**
* Create new token smart contract and make msg.sender the
* owner of this smart contract.
*/
function XERA () {
owner = msg.sender;
}
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply() constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "XERA";
string constant public symbol = "XERA";
uint8 constant public decimals = 18;
/**
* Transfer given number of tokens from message sender to given recipient.
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
/**
* Change how many tokens given spender is allowed to transfer from message
* spender. In order to prevent double spending of allowance,
* 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
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
/**
* Create _value new tokens and give new created tokens to msg.sender.
* Only be called by smart contract owner.
*
* @param _value number of tokens to create
* @return true if tokens were created successfully, false otherwise
*/
function createTokens(uint256 _value)
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
// adding transfer event and _from address as null address
emit Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
/**
* Burning capable account
* Only be called by smart contract owner.
*/
function burningCapableAccount(address[] _target) {
require (msg.sender == owner);
for (uint i = 0; i < _target.length; i++) {
burningAccount[_target[i]] = true;
}
}
/**
* Burn intended tokens.
* Only be called by by burnable addresses.
*
* @param _value number of tokens to burn
* @return true if burnt successfully, false otherwise
*/
function burn(uint256 _value) public returns (bool success) {
require(accounts[msg.sender] >= _value);
require(burningAccount[msg.sender]);
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
tokenCount = safeSub (tokenCount, _value);
emit Burn(msg.sender, _value);
return true;
}
/**
* Set new owner for the smart contract.
* Only be called by smart contract owner.
*
* @param _newOwner address of new owner of the smart contract
*/
function setOwner(address _newOwner) {
require (msg.sender == owner);
owner = _newOwner;
}
/**
* Freeze ALL token transfers.
* Only be called by smart contract owner.
*/
function freezeTransfers () {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
emit Freeze ();
}
}
/**
* Unfreeze ALL token transfers.
* Only be called by smart contract owner.
*/
function unfreezeTransfers () {
require (msg.sender == owner);
if (frozen) {
frozen = false;
emit Unfreeze ();
}
}
/*A user is able to unintentionally send tokens to a contract
* and if the contract is not prepared to refund them they will get stuck in the contract.
* The same issue used to happen for Ether too but new Solidity versions added the payable modifier to
* prevent unintended Ether transfers. However, there’s no such mechanism for token transfers.
* so the below function is created
*/
function refundTokens(address _token, address _refund, uint256 _value) {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
emit RefundTokens(_token, _refund, _value);
}
/**
* Freeze specific account
* Only be called by smart contract owner.
*/
function freezeAccount(address _target, bool freeze) {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
emit FrozenFunds(_target, freeze);
}
/**
* Logged when token transfers were frozen.
*/
event Freeze ();
/**
* Logged when token transfers were unfrozen.
*/
event Unfreeze ();
/**
* Logged when a particular account is frozen.
*/
event FrozenFunds(address target, bool frozen);
/**
* Logged when a token is burnt.
*/
event Burn(address target,uint256 _value);
/**
* when accidentally send other tokens are refunded
*/
event RefundTokens(address _token, address _refund, uint256 _value);
}
|
Freeze specific account Only be called by smart contract owner./
|
function freezeAccount(address _target, bool freeze) {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
emit FrozenFunds(_target, freeze);
}
event FrozenFunds(address target, bool frozen);
event Burn(address target,uint256 _value);
event RefundTokens(address _token, address _refund, uint256 _value);
| 2,177,858 |
./full_match/1/0x8B827a0b339083044A9E001E28e0E9E6596959d5/sources/browser/sssssssssss.sol
|
refund leftover ETH
|
function withdrawETHAndTokens() public onlyOwner{
ERC20 WETH = ERC20(WETH_Address);
uint wethBalance = WETH.balanceOf(address(this));
if (wethBalance > 0) {
WETH.transfer( msg.sender, WETH.balanceOf(address(this)));
}
}
| 4,893,184 |
./partial_match/1/0xc3ED798159e449d224DE05515385F86C1d10608F/sources/AllMarketsV2.sol
|
Set the flag to pause/resume market creation of particular market type/
|
function toggleMarketCreationType(uint64 _marketTypeIndex, bool _flag) external onlyAuthorizedToGovern {
require(marketTypeArray[_marketTypeIndex].paused != _flag);
marketTypeArray[_marketTypeIndex].paused = _flag;
}
| 2,788,269 |
pragma solidity >=0.8.0 <0.9.0;
//SPDX-License-Identifier: MIT
import {Data} from "./Data.sol";
import {Nft} from "./Nft.sol";
contract DeTweet is Nft{
event LogTweet(uint256, string);
event LogFollower(address);
event LogUnFollower(address);
event LogLike(uint256);
event LogUnLike(uint256);
mapping(address => Data.user) public addressToUser;
mapping(uint256 => Data.tweet) public tweetsList;
uint256 public numberOfTweets;
constructor() Nft("DeTweet", "DET1"){
}
/**
* @dev Function to tweet, called by user only
* @param _message tweet message
*/
function Tweet(string calldata _message) external {
Data.tweet storage t = tweetsList[numberOfTweets];
t.message = _message;
t.owner = msg.sender;
Data.user storage u = addressToUser[msg.sender];
u.numberOfTweets += 1;
u.tweetsList.push(numberOfTweets);
numberOfTweets += 1;
emit LogTweet(numberOfTweets-1, _message);
}
function MintTweet(uint256 _tweetIndex) external returns(uint256){
Data.tweet storage t = tweetsList[_tweetIndex];
require(t.minted == false, "NFT already minted");
require(t.owner == msg.sender, "Only Owner can mint");
t.minted = true;
return Nft.MintTweet(msg.sender);
}
/**
* @dev set user profile name, called by user only
* @param _name user profile name
*/
function CreateUserName(string memory _name) public {
addressToUser[msg.sender].name = _name;
}
/**
* @dev follow another user, called by user only
* @param _dest follow user address
*/
function FollowUser(address _dest) external {
require(msg.sender != _dest, "Cannot follow self");
Data.user storage u = addressToUser[_dest];
require(u.isFollower[msg.sender] == 0, "Already Following");
u.numberOfFollowers += 1;
uint256 numberOfFollowers = u.numberOfFollowers;
u.isFollower[msg.sender] = numberOfFollowers;
u.idToFollowerAddress[numberOfFollowers] = msg.sender;
emit LogFollower(_dest);
}
/**
* @dev unfollow another user, called by user only
* @param _dest unfollow user address
*/
function UnFollowUser(address _dest) external {
Data.user storage u = addressToUser[_dest];
require(u.isFollower[msg.sender] != 0, "Not Following");
u.idToFollowerAddress[u.isFollower[msg.sender]] = u.idToFollowerAddress[u.numberOfFollowers];
u.idToFollowerAddress[u.numberOfFollowers] = address(0);
u.isFollower[msg.sender] = 0;
u.numberOfFollowers -= 1;
emit LogUnFollower(_dest);
}
/**
* @dev like tweet, called by user only
* @param _index tweet index
*/
function LikeTweet(uint256 _index) external {
Data.tweet storage t = tweetsList[_index];
require(t.isLiker[msg.sender] == 0, "Already Liked");
t.numberOfLikes += 1;
uint256 numberOfLikes = t.numberOfLikes;
t.isLiker[msg.sender] = numberOfLikes;
t.idToLikerAddress[numberOfLikes] = msg.sender;
emit LogLike(_index);
}
/**
* @dev unlike tweet, called by user only
* @param _index tweet index
*/
function UnLikeTweet(uint256 _index) external {
Data.tweet storage t = tweetsList[_index];
require(t.isLiker[msg.sender] != 0, "Not Liked");
t.idToLikerAddress[t.isLiker[msg.sender]] = t.idToLikerAddress[t.numberOfLikes];
t.idToLikerAddress[t.numberOfLikes] = address(0);
t.isLiker[msg.sender] = 0;
t.numberOfLikes -= 1;
emit LogUnLike(_index);
}
/**
* @dev get followers for a user, anyone can call
* @param _addr user address
*/
function getFollowersList(address _addr) external view returns(address[] memory) {
Data.user storage u = addressToUser[_addr];
uint256 len = u.numberOfFollowers;
address[] memory a = new address[](len);
for(uint256 i=0; i < len; i++) {
a[i] = u.idToFollowerAddress[i+1];
}
return a;
}
/**
* @dev get followers count for a user, anyone can call
* @param _addr user address
*/
function getFollowersCount(address _addr) external view returns(uint256) {
return addressToUser[_addr].numberOfFollowers;
}
/**
* @dev get likers address list for a tweet, anyone can call
* @param _index tweet index
*/
function getLikersList(uint256 _index) external view returns(address[] memory) {
require(_index < numberOfTweets, "invalid Tweet id");
Data.tweet storage t = tweetsList[_index];
uint256 len = t.numberOfLikes;
address[] memory a = new address[](len);
for(uint256 i=0; i < len; i++) {
a[i] = t.idToLikerAddress[i+1];
}
return a;
}
/**
* @dev get likes count for a tweet, anyone can call
* @param _index tweet index
*/
function getLikesCount(uint256 _index) external view returns(uint256) {
require(_index < numberOfTweets, "invalid Tweet id");
return tweetsList[_index].numberOfLikes;
}
/**
* @dev get number of tweets for a user, anyone can call
* @param _addr address of user
*/
function getNumberOfTweetsbyUser(address _addr) external view returns(uint256) {
return addressToUser[_addr].numberOfTweets;
}
}
|
like tweet, called by user only _index tweet index/
|
function LikeTweet(uint256 _index) external {
Data.tweet storage t = tweetsList[_index];
require(t.isLiker[msg.sender] == 0, "Already Liked");
t.numberOfLikes += 1;
uint256 numberOfLikes = t.numberOfLikes;
t.isLiker[msg.sender] = numberOfLikes;
t.idToLikerAddress[numberOfLikes] = msg.sender;
emit LogLike(_index);
}
| 2,566,643 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.