file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/access/Ownable.sol';
import "@openzeppelin/contracts/utils/Counters.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
/*
* @title Contract for Pixelvault list randomizations using Chainlink VRF
*
* @author Niftydude
*/
contract ListRandomizer is VRFConsumerBase, Ownable {
using Counters for Counters.Counter;
Counters.Counter private counter;
bytes32 internal keyHash;
uint256 internal fee;
mapping(uint256 => Randomization) public randomizations;
struct Randomization {
uint256 listLength;
string description;
uint256 randomNumber;
bool isFulfilled;
string entryListIpfsHash;
}
constructor(
address _vrfCoordinator,
address _linkToken,
bytes32 _keyHash,
uint256 _fee
) VRFConsumerBase(_vrfCoordinator, _linkToken) {
keyHash = _keyHash;
fee = _fee;
}
/**
* @notice initiate a new randomization
*
* @param _listLength the number of entries in the list
* @param _entryListIpfsHash ipfs hash pointing to the list of entries
*
*/
function startRandomization(
uint256 _listLength,
string memory _entryListIpfsHash,
string memory _description
) external onlyOwner returns (bytes32 requestId) {
require(counter.current() == 0 || randomizations[counter.current()-1].isFulfilled, "Previous randomization not fulfilled");
require(
LINK.balanceOf(address(this)) >= fee,
"Not enough LINK"
);
Randomization storage d = randomizations[counter.current()];
d.listLength = _listLength;
d.entryListIpfsHash = _entryListIpfsHash;
d.description = _description;
counter.increment();
return requestRandomness(keyHash, fee);
}
/**
* @notice return randomized list for a given randomization
*
* @param _id the randomization id to return the list for
*/
function getRandomList(uint256 _id) external view returns (uint256[] memory) {
require(randomizations[_id].isFulfilled, "Randomization not fulfilled yet");
uint256[] memory arr = new uint256[](randomizations[_id].listLength);
for (uint256 i = 0; i < randomizations[_id].listLength; i++) {
uint256 j = (uint256(keccak256(abi.encode(randomizations[_id].randomNumber, i))) % (i + 1));
arr[i] = arr[j];
arr[j] = i+1;
}
return arr;
}
function withdrawLink() external onlyOwner {
LINK.transfer(owner(), LINK.balanceOf(address(this)));
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32, uint256 randomness) internal override {
randomizations[counter.current()-1].randomNumber = randomness;
randomizations[counter.current()-1].isFulfilled = true;
}
}
// 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
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 private constant USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) {
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface internal immutable LINK;
address private immutable vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 => uint256) /* keyHash */ /* nonce */
private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// 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.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
} | rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF proof. rawFulfillRandomness then calls fulfillRandomness, after validating the origin of the call | function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
| 71,377 |
// SPDX-License-Identifier: ISC
/// @title OMNI Token V1 / Ethereum v1
/// @author Alfredo Lopez / Arthur Miranda / OMNI App 2021.5 */
pragma solidity 0.8.4;
pragma experimental ABIEncoderV2;
import "../lib/@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "../lib/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../lib/main/Vesting.sol";
contract OmniTokenV1 is Initializable, Vesting{
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
// Constant Max Total Supply of OMNI Social Media Network
uint256 private constant _maxTotalSupply = 638_888_889 * (uint256(10) ** uint256(18));
function initialize() initializer() public {
__Ownable_init();
__ERC20_init_unchained('OMNI Coin', 'OMN');
__Pausable_init_unchained();
__ERC20Permit_init('OMNI Coin');
// Mint Total Supply
mint(getMaxTotalSupply());
// Begininng Deploy of Allocation in the ERC20
// Allocation #1 / VestingType # 0, Early Backers Total (6.94956521970783)% and Start with 31 days Locked the Token
vestingTypes.push(VestingType(1930501930501930, 0, 31 days, 0, 0, true, true)); // 31 Days Locked, 0.193050193050193 Percent daily for 518 days
// Allocation #2 / VestingType # 1, Seed Total (9.39130435095652)% and Start with 31 days Locked the Token
vestingTypes.push(VestingType(2188183807439820, 0, 31 days, 0, 0, true, true)); // 30 Days Locked, 0.218818380743982 Percent daily for 457 days
// Allocation #3 / VestingType # 2, Private Sale Total (9.52434782926174)%, Unlocked 10% when start the vesting, Start with 31 days Locked the Token and After (8.57191304633557)%
vestingTypes.push(VestingType(2272727272727270, 100000000000000000, 31 days, 0, 0, true, true)); // 10% Unlocked when start, 31 Days Locked, 0.227272727272727 Percent daily for 396 Days for the 90% Rest
// Allocation #4 / VestingType # 3, Public Sale Total (1.56521739182609)%, Unlocked 34% when start the vesting, Start with 0 days Locked the Token and After (33)% Monthly
vestingTypes.push(VestingType(0, 340000000000000000, 0, 330000000000000000, 0, true, false)); // 34% Unlocked when start, 33% Percent Monthly for 2 months Rest
// Allocation #5 / VestingType # 4, OMNI Team Total (10)% and Start After 274 days Locked the Token
vestingTypes.push(VestingType(3636363636363640, 0, 274 days, 0, 0, true, true)); // 274 Days Locked, 0.363636363636364 Percent daily for 275 days
// Allocation #6 / VestingType # 5, Advisors Total (5)% and Start After 31 days Locked the Token
vestingTypes.push(VestingType(2525252525252530, 0, 31 days, 0, 0, true, true)); // 31 Days Locked, 0.2525252525252530 Percent daily for 396 days
// Allocation #7 / VestingType # 6, Tech Partners Total (10)% Start After 365 days Locked the Token
vestingTypes.push(VestingType(1562500000000000, 0, 365 days, 0, 0, true, true)); // 365 Days Locked, 0.15625 Percent daily for 640 days
// Allocation #8 / VestingType # 7, Marketing Total (8)% Start After 184 days Locked the Token
vestingTypes.push(VestingType(3663003663003660, 0, 184 days, 0, 0, true, true)); // 184 Days Locked, 0.366300366300366 Percent daily for 273 days
// Allocation #9 / VestingType # 8, Foundation Total (5)% and Start After 274 days Locked the Token
vestingTypes.push(VestingType(1562500000000000, 0, 274 days, 0, 0, true, true)); // 274 Days Locked, 0.15625 Percent daily for 640 days
// Allocation #10 / VestingType # 9, Liquidity Total (3)% and Daily Rate in wei (0), Unlocked the all Token immediatly when Start the Vesting
vestingTypes.push(VestingType(1000000000000000000, 1000000000000000000, 0, 0, 0, true, true)); // 0 Days 100 Percent
// Allocation #11 / VestingType # 10, Ecosystem Total (20)% and Start After 92 days Locked the Token
vestingTypes.push(VestingType(782472613458529, 0, 92 days, 0, 0, true, true)); // 92 Days Locked, 0.0783085356303837 Percent daily for 1278 days
// Allocation #12 / VestingType # 11, Community Reserve Total (3)% and Start After 183 days Locked the Token
vestingTypes.push(VestingType(843170320404722, 0, 184 days, 0, 0, true, true)); // 184 Days Locked, 0.0843170320404722 Percent daily for 1186 days
// Allocation #13 / VestingType # 12, Company Reserve Total (8.56956520824781)% and Start After 273 days Locked the Token
vestingTypes.push(VestingType(994035785288270, 0, 274 days, 0, 0, true, true)); // 274 Days Locked, 0.099403578528827 Percent daily for 1006 days
}
/**
* @dev This Method permit getting Maximun total Supply .
* See {ERC20-_burn}.
*/
function getMaxTotalSupply() public pure returns (uint256) {
return _maxTotalSupply;
}
/**
* @dev Implementation / Instance of TransferMany of Parsiq Token.
* @dev This method permitr to habdle AirDrop process with a reduce cost of gas in at least 30%
* @param recipients Array of Address to receive the Tokens in AirDrop process
* @param amounts Array of Amounts of token to receive
* See {https://github.com/parsiq/parsiq-bsc-token/blob/main/contracts/ParsiqToken.sol}.
*/
function transferMany(address[] calldata recipients, uint256[] calldata amounts)
external
onlyOwner()
whenNotPaused()
{
require(recipients.length == amounts.length, "ERC20 OMN: Wrong array length");
uint256 total = 0;
for (uint256 i = 0; i < amounts.length; i++) {
address recipient = recipients[i];
require(recipient != address(0), "ERC20: transfer to the zero address");
require(!isBlacklisted(recipient), "ERC20 OMN: recipient account is blacklisted");
require(amounts[i] != 0, "ERC20 OMN: total amount token is zero");
total = total.add(amounts[i]);
}
_balances[msg.sender] = _balances[msg.sender].sub(total, "ERC20: transfer amount exceeds balance");
for (uint256 i = 0; i < recipients.length; i++) {
address recipient = recipients[i];
uint256 amount = amounts[i];
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(msg.sender, recipient, amount);
}
}
/**
* @dev Circulating Supply Method for Calculated based on Wallets of OMNI Foundation
*/
function circulatingSupply() public view returns (uint256 result) {
uint256 index = omni_wallets.length;
result = totalSupply().sub(balanceOf(owner()));
for (uint256 i=0; i < index ; i++ ) {
if ((omni_wallets[i] != address(0)) && (result != 0)) {
result -= balanceOf(omni_wallets[i]);
}
}
}
/**
* @dev Implementation / Instance of paused methods() in the ERC20.
* @param status Setting the status boolean (True for paused, or False for unpaused)
* See {ERC20Pausable}.
*/
function pause(bool status) public onlyOwner() {
if (status) {
_pause();
} else {
_unpause();
}
}
/**
* @dev Destroys `amount` tokens from the caller.
* @param amount Amount token to burn
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev Override the Hook of Open Zeppelin for checking before execute the method transfer/transferFrom/mint/burn.
* @param sender Addres of Sender of the token
* @param amount Amount token to transfer/transferFrom/mint/burn, Verify that in hook _beforeTokenTransfer
*/
function canTransfer(address sender, uint256 amount) public view returns (bool) {
// Control is scheduled wallet
if (!frozenWallets[sender].scheduled) {
return true;
}
uint256 balance = balanceOf(sender);
uint256 restAmount = getRestAmount(sender);
if (balance > frozenWallets[sender].totalAmount && balance.sub(frozenWallets[sender].totalAmount) >= amount) {
return true;
}
if (!isStarted(frozenWallets[sender].startDay) || balance.sub(amount) < restAmount) {
return false;
}
return true;
}
/**
* @dev Override the Hook of Open Zeppelin for checking before execute the method transfer/transferFrom/mint/burn.
* @param sender Addres of Sender of the token
* @param recipient Address of Receptor of the token
* @param amount Amount token to transfer/transferFrom/mint/burn
* See {ERC20 Upgradeable}.
*/
function _beforeTokenTransfer(address sender, address recipient, uint256 amount) internal virtual override notBlacklisted(sender) {
require(!isBlacklisted(recipient), "ERC20 OMN: recipient account is blacklisted");
// Permit the Owner execute token transfer/mint/burn while paused contract
if (_msgSender() != owner()) {
require(!paused(), "ERC20 OMN: token transfer/mint/burn while paused");
}
require(canTransfer(sender, amount), "ERC20 OMN: Wait for vesting day!");
super._beforeTokenTransfer(sender, recipient, amount);
}
/**
* @dev Override the Standard Transfer Method of Open Zeppelin for checking before if Transfer status is Enabled or Disable.
* @param sender Addres of Sender of the token
* @param recipient Address of Receptor of the token
* @param amount Amount token to transfer/transferFrom/mint/burn
* See {https://github.com/ShieldFinanceHQ/contracts/blob/master/contracts/ShieldToken.sol}.
*/
function _transfer(address sender, address recipient, uint256 amount) internal override {
if (isTransferDisabled()) {
// anti-sniping bot defense is on
// burn tokens instead of transferring them >:]
super._burn(sender, amount);
emit TransferBurned(sender, amount);
} else {
super._transfer(sender, recipient, amount);
}
}
/**
* @dev Creates `amount` new tokens for `to`.
* @param _amount Amount Token to mint
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `OWNER`.
* - After upgrade the SmartContract and Eliminate this method
*/
function mint( uint256 _amount) public onlyOwner() {
require(getMaxTotalSupply() >= totalSupply().add(_amount), "ERC20: Can't Mint, it exceeds the maximum supply ");
_mint(owner(), _amount);
}
}
| Override the Standard Transfer Method of Open Zeppelin for checking before if Transfer status is Enabled or Disable. sender Addres of Sender of the token recipient Address of Receptor of the token amount Amount token to transfer/transferFrom/mint/burn/ anti-sniping bot defense is on burn tokens instead of transferring them >:] | function _transfer(address sender, address recipient, uint256 amount) internal override {
if (isTransferDisabled()) {
super._burn(sender, amount);
emit TransferBurned(sender, amount);
super._transfer(sender, recipient, amount);
}
}
| 13,047,431 |
pragma solidity 0.5.11;
pragma experimental ABIEncoderV2;
import "./ParameterStore.sol";
import "./IDonationReceiver.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
contract Gatekeeper {
// EVENTS
event PermissionRequested(
uint256 indexed epochNumber,
address indexed resource,
uint requestID,
bytes metadataHash
);
event SlateCreated(uint slateID, address indexed recommender, uint[] requestIDs, bytes metadataHash);
event SlateStaked(uint slateID, address indexed staker, uint numTokens);
event VotingTokensDeposited(address indexed voter, uint numTokens);
event VotingTokensWithdrawn(address indexed voter, uint numTokens);
event VotingRightsDelegated(address indexed voter, address delegate);
event BallotCommitted(
uint indexed epochNumber,
address indexed committer,
address indexed voter,
uint numTokens,
bytes32 commitHash
);
event BallotRevealed(uint indexed epochNumber, address indexed voter, uint numTokens);
event ContestAutomaticallyFinalized(
uint256 indexed epochNumber,
address indexed resource,
uint256 winningSlate
);
event ContestFinalizedWithoutWinner(uint indexed epochNumber, address indexed resource);
event VoteFinalized(
uint indexed epochNumber,
address indexed resource,
uint winningSlate,
uint winnerVotes,
uint totalVotes
);
event VoteFailed(
uint indexed epochNumber,
address indexed resource,
uint leadingSlate,
uint leaderVotes,
uint runnerUpSlate,
uint runnerUpVotes,
uint totalVotes
);
event RunoffFinalized(
uint indexed epochNumber,
address indexed resource,
uint winningSlate,
uint winnerVotes,
uint losingSlate,
uint loserVotes
);
event StakeWithdrawn(uint slateID, address indexed staker, uint numTokens);
// STATE
using SafeMath for uint256;
uint constant ONE_WEEK = 604800;
// The timestamp of the start of the first epoch
uint public startTime;
uint public constant EPOCH_LENGTH = ONE_WEEK * 13;
uint public constant SLATE_SUBMISSION_PERIOD_START = ONE_WEEK;
uint public constant COMMIT_PERIOD_START = ONE_WEEK * 11;
uint public constant REVEAL_PERIOD_START = ONE_WEEK * 12;
// Parameters
ParameterStore public parameters;
// Associated token
IERC20 public token;
// Requests
struct Request {
bytes metadataHash;
// The resource (contract) the permission is being requested for
address resource;
bool approved;
uint expirationTime;
uint epochNumber;
}
// The requests made to the Gatekeeper.
Request[] public requests;
// Voting
enum SlateStatus {
Unstaked,
Staked,
Accepted
}
struct Slate {
address recommender;
bytes metadataHash;
mapping(uint => bool) requestIncluded;
uint[] requests;
SlateStatus status;
// Staking info
address staker;
uint stake;
// Ballot info
uint256 epochNumber;
address resource;
}
// The slates created by the Gatekeeper.
Slate[] public slates;
// The number of tokens each account has available for voting
mapping(address => uint) public voteTokenBalance;
// The delegated account for each voting account
mapping(address => address) public delegate;
// The data committed when voting
struct VoteCommitment {
bytes32 commitHash;
uint numTokens;
bool committed;
bool revealed;
}
// The votes for a slate in a contest
struct SlateVotes {
uint firstChoiceVotes;
// slateID -> count
mapping(uint => uint) secondChoiceVotes;
uint totalSecondChoiceVotes;
}
enum ContestStatus {
Empty,
NoContest,
Active,
Finalized
}
struct Contest {
ContestStatus status;
// slateIDs
uint[] slates;
uint[] stakedSlates;
uint256 lastStaked;
// slateID -> tally
mapping(uint => SlateVotes) votes;
uint256 stakesDonated;
// Intermediate results
uint voteLeader;
uint voteRunnerUp;
uint256 leaderVotes;
uint256 runnerUpVotes;
uint256 totalVotes;
// Final results
uint winner;
}
// The current incumbent for a resource
mapping(address => address) public incumbent;
// A group of Contests in an epoch
struct Ballot {
// resource -> Contest
mapping(address => Contest) contests;
// NOTE: keep to avoid error about "internal or recursive type"
bool created;
// commitments for each voter
mapping(address => VoteCommitment) commitments;
}
// All the ballots created so far
// epoch number -> Ballot
mapping(uint => Ballot) public ballots;
// IMPLEMENTATION
/**
@dev Initialize a Gatekeeper contract.
@param _startTime The start time of the first batch
@param _parameters The parameter store to use
*/
constructor(uint _startTime, ParameterStore _parameters, IERC20 _token) public {
require(address(_parameters) != address(0), "Parameter store address cannot be zero");
parameters = _parameters;
require(address(_token) != address(0), "Token address cannot be zero");
token = _token;
startTime = _startTime;
}
// TIMING
/**
* @dev Get the number of the current epoch.
*/
function currentEpochNumber() public view returns(uint) {
uint elapsed = now.sub(startTime);
uint epoch = elapsed.div(EPOCH_LENGTH);
return epoch;
}
/**
* @dev Get the start of the given epoch.
*/
function epochStart(uint256 epoch) public view returns(uint) {
return startTime.add(EPOCH_LENGTH.mul(epoch));
}
// SLATE GOVERNANCE
/**
* @dev Create a new slate with the associated requestIds and metadata hash.
* @param resource The resource to submit the slate for
* @param requestIDs A list of request IDs to include in the slate
* @param metadataHash A reference to metadata about the slate
*/
function recommendSlate(
address resource,
uint[] memory requestIDs,
bytes memory metadataHash
)
public returns(uint)
{
require(isCurrentGatekeeper(), "Not current gatekeeper");
require(slateSubmissionPeriodActive(resource), "Submission period not active");
require(metadataHash.length > 0, "metadataHash cannot be empty");
uint256 epochNumber = currentEpochNumber();
// create slate
Slate memory s = Slate({
recommender: msg.sender,
metadataHash: metadataHash,
requests: requestIDs,
status: SlateStatus.Unstaked,
staker: address(0),
stake: 0,
epochNumber: epochNumber,
resource: resource
});
// Record slate and return its ID
uint slateID = slateCount();
slates.push(s);
// Set up the requests
for (uint i = 0; i < requestIDs.length; i++) {
uint requestID = requestIDs[i];
require(requestID < requestCount(), "Invalid requestID");
Request memory r = requests[requestID];
// Every request's resource must match the one passed in
require(r.resource == resource, "Resource does not match");
// Requests must be current
require(r.epochNumber == epochNumber, "Invalid epoch");
// Requests cannot be duplicated
require(slates[slateID].requestIncluded[requestID] == false, "Duplicate requests are not allowed");
slates[slateID].requestIncluded[requestID] = true;
}
// Assign the slate to the appropriate contest
ballots[epochNumber].contests[resource].slates.push(slateID);
emit SlateCreated(slateID, msg.sender, requestIDs, metadataHash);
return slateID;
}
/**
@dev Get a list of the requests associated with a slate
@param slateID The slate
*/
function slateRequests(uint slateID) public view returns(uint[] memory) {
return slates[slateID].requests;
}
/**
@dev Stake tokens on the given slate to include it for consideration in votes. If the slate
loses in a contest, the amount staked will go to the winner. If it wins, it will be returned.
@param slateID The slate to stake on
*/
function stakeTokens(uint slateID) public returns(bool) {
require(isCurrentGatekeeper(), "Not current gatekeeper");
require(slateID < slateCount(), "No slate exists with that slateID");
require(slates[slateID].status == SlateStatus.Unstaked, "Slate has already been staked");
address staker = msg.sender;
// Staker must have enough tokens
uint stakeAmount = parameters.getAsUint("slateStakeAmount");
require(token.balanceOf(staker) >= stakeAmount, "Insufficient token balance");
Slate storage slate = slates[slateID];
// Submission period must be active
require(slateSubmissionPeriodActive(slate.resource), "Submission period not active");
uint256 epochNumber = currentEpochNumber();
assert(slate.epochNumber == epochNumber);
// Transfer tokens and update the slate's staking info
// Must successfully transfer tokens from staker to this contract
slate.staker = staker;
slate.stake = stakeAmount;
slate.status = SlateStatus.Staked;
require(token.transferFrom(staker, address(this), stakeAmount), "Failed to transfer tokens");
// Associate the slate with a contest and update the contest status
// A vote can only happen if there is more than one associated slate
Contest storage contest = ballots[slate.epochNumber].contests[slate.resource];
contest.stakedSlates.push(slateID);
// offset from the start of the epoch, for easier calculations
contest.lastStaked = now.sub(epochStart(epochNumber));
uint256 numSlates = contest.stakedSlates.length;
if (numSlates == 1) {
contest.status = ContestStatus.NoContest;
} else {
contest.status = ContestStatus.Active;
}
emit SlateStaked(slateID, staker, stakeAmount);
return true;
}
/**
@dev Withdraw tokens previously staked on a slate that was accepted through slate governance.
@param slateID The slate to withdraw the stake from
*/
function withdrawStake(uint slateID) public returns(bool) {
require(slateID < slateCount(), "No slate exists with that slateID");
// get slate
Slate memory slate = slates[slateID];
require(slate.status == SlateStatus.Accepted, "Slate has not been accepted");
require(msg.sender == slate.staker, "Only the original staker can withdraw this stake");
require(slate.stake > 0, "Stake has already been withdrawn");
// Update slate and transfer tokens
slates[slateID].stake = 0;
require(token.transfer(slate.staker, slate.stake), "Failed to transfer tokens");
emit StakeWithdrawn(slateID, slate.staker, slate.stake);
return true;
}
/**
@dev Deposit `numToken` tokens into the Gatekeeper to use in voting
Assumes that `msg.sender` has approved the Gatekeeper to spend on their behalf
@param numTokens The number of tokens to devote to voting
*/
function depositVoteTokens(uint numTokens) public returns(bool) {
require(isCurrentGatekeeper(), "Not current gatekeeper");
address voter = msg.sender;
// Voter must have enough tokens
require(token.balanceOf(msg.sender) >= numTokens, "Insufficient token balance");
// Transfer tokens to increase the voter's balance by `numTokens`
uint originalBalance = voteTokenBalance[voter];
voteTokenBalance[voter] = originalBalance.add(numTokens);
// Must successfully transfer tokens from voter to this contract
require(token.transferFrom(voter, address(this), numTokens), "Failed to transfer tokens");
emit VotingTokensDeposited(voter, numTokens);
return true;
}
/**
@dev Withdraw `numTokens` vote tokens to the caller and decrease voting power
@param numTokens The number of tokens to withdraw
*/
function withdrawVoteTokens(uint numTokens) public returns(bool) {
require(commitPeriodActive() == false, "Tokens locked during voting");
address voter = msg.sender;
uint votingRights = voteTokenBalance[voter];
require(votingRights >= numTokens, "Insufficient vote token balance");
// Transfer tokens to decrease the voter's balance by `numTokens`
voteTokenBalance[voter] = votingRights.sub(numTokens);
require(token.transfer(voter, numTokens), "Failed to transfer tokens");
emit VotingTokensWithdrawn(voter, numTokens);
return true;
}
/**
@dev Set a delegate account that can vote on behalf of the voter
@param _delegate The account being delegated to
*/
function delegateVotingRights(address _delegate) public returns(bool) {
address voter = msg.sender;
require(voter != _delegate, "Delegate and voter cannot be equal");
delegate[voter] = _delegate;
emit VotingRightsDelegated(voter, _delegate);
return true;
}
/**
@dev Submit a commitment for the current ballot
@param voter The voter to commit for
@param commitHash The hash representing the voter's vote choices
@param numTokens The number of vote tokens to use
*/
function commitBallot(address voter, bytes32 commitHash, uint numTokens) public {
uint epochNumber = currentEpochNumber();
require(commitPeriodActive(), "Commit period not active");
require(didCommit(epochNumber, voter) == false, "Voter has already committed for this ballot");
require(commitHash != 0, "Cannot commit zero hash");
address committer = msg.sender;
// Must be a delegate if not the voter
if (committer != voter) {
require(committer == delegate[voter], "Not a delegate");
require(voteTokenBalance[voter] >= numTokens, "Insufficient tokens");
} else {
// If the voter doesn't have enough tokens for voting, deposit more
if (voteTokenBalance[voter] < numTokens) {
uint remainder = numTokens.sub(voteTokenBalance[voter]);
depositVoteTokens(remainder);
}
}
assert(voteTokenBalance[voter] >= numTokens);
// Set the voter's commitment for the current ballot
Ballot storage ballot = ballots[epochNumber];
VoteCommitment memory commitment = VoteCommitment({
commitHash: commitHash,
numTokens: numTokens,
committed: true,
revealed: false
});
ballot.commitments[voter] = commitment;
emit BallotCommitted(epochNumber, committer, voter, numTokens, commitHash);
}
/**
@dev Return true if the voter has committed for the given epoch
@param epochNumber The epoch to check
@param voter The voter's address
*/
function didCommit(uint epochNumber, address voter) public view returns(bool) {
return ballots[epochNumber].commitments[voter].committed;
}
/**
@dev Get the commit hash for a given voter and epoch. Revert if voter has not committed yet.
@param epochNumber The epoch to check
@param voter The voter's address
*/
function getCommitHash(uint epochNumber, address voter) public view returns(bytes32) {
VoteCommitment memory v = ballots[epochNumber].commitments[voter];
require(v.committed, "Voter has not committed for this ballot");
return v.commitHash;
}
/**
@dev Reveal a given voter's choices for the current ballot and record their choices
@param voter The voter's address
@param resources The contests to vote on
@param firstChoices The corresponding first choices
@param secondChoices The corresponding second choices
@param salt The salt used to generate the original commitment
*/
function revealBallot(
uint256 epochNumber,
address voter,
address[] memory resources,
uint[] memory firstChoices,
uint[] memory secondChoices,
uint salt
) public {
uint256 epochTime = now.sub(epochStart(epochNumber));
require(
(REVEAL_PERIOD_START <= epochTime) && (epochTime < EPOCH_LENGTH),
"Reveal period not active"
);
require(voter != address(0), "Voter address cannot be zero");
require(resources.length == firstChoices.length, "All inputs must have the same length");
require(firstChoices.length == secondChoices.length, "All inputs must have the same length");
require(didCommit(epochNumber, voter), "Voter has not committed");
require(didReveal(epochNumber, voter) == false, "Voter has already revealed");
// calculate the hash
bytes memory buf;
uint votes = resources.length;
for (uint i = 0; i < votes; i++) {
buf = abi.encodePacked(
buf,
resources[i],
firstChoices[i],
secondChoices[i]
);
}
buf = abi.encodePacked(buf, salt);
bytes32 hashed = keccak256(buf);
Ballot storage ballot = ballots[epochNumber];
// compare to the stored data
VoteCommitment memory v = ballot.commitments[voter];
require(hashed == v.commitHash, "Submitted ballot does not match commitment");
// Update tally for each contest
for (uint i = 0; i < votes; i++) {
address resource = resources[i];
// get the contest for the current resource
Contest storage contest = ballot.contests[resource];
// Increment totals for first and second choice slates
uint firstChoice = firstChoices[i];
uint secondChoice = secondChoices[i];
// Update first choice standings
if (slates[firstChoice].status == SlateStatus.Staked) {
SlateVotes storage firstChoiceSlate = contest.votes[firstChoice];
contest.totalVotes = contest.totalVotes.add(v.numTokens);
uint256 newCount = firstChoiceSlate.firstChoiceVotes.add(v.numTokens);
// Update first choice standings
if (firstChoice == contest.voteLeader) {
// Leader is still the leader
contest.leaderVotes = newCount;
} else if (newCount > contest.leaderVotes) {
// This slate is now the leader, and the previous leader is now the runner-up
contest.voteRunnerUp = contest.voteLeader;
contest.runnerUpVotes = contest.leaderVotes;
contest.voteLeader = firstChoice;
contest.leaderVotes = newCount;
} else if (newCount > contest.runnerUpVotes) {
// This slate overtook the previous runner-up
contest.voteRunnerUp = firstChoice;
contest.runnerUpVotes = newCount;
}
firstChoiceSlate.firstChoiceVotes = newCount;
// Update second choice standings
if (slates[secondChoice].status == SlateStatus.Staked) {
SlateVotes storage secondChoiceSlate = contest.votes[secondChoice];
secondChoiceSlate.totalSecondChoiceVotes = secondChoiceSlate.totalSecondChoiceVotes.add(v.numTokens);
firstChoiceSlate.secondChoiceVotes[secondChoice] = firstChoiceSlate.secondChoiceVotes[secondChoice].add(v.numTokens);
}
}
}
// update state
ballot.commitments[voter].revealed = true;
emit BallotRevealed(epochNumber, voter, v.numTokens);
}
/**
@dev Reveal ballots for multiple voters
*/
function revealManyBallots(
uint256 epochNumber,
address[] memory _voters,
bytes[] memory _ballots,
uint[] memory _salts
) public {
uint numBallots = _voters.length;
require(
_salts.length == _voters.length && _ballots.length == _voters.length,
"Inputs must have the same length"
);
for (uint i = 0; i < numBallots; i++) {
// extract resources, firstChoices, secondChoices from the ballot
(
address[] memory resources,
uint[] memory firstChoices,
uint[] memory secondChoices
) = abi.decode(_ballots[i], (address[], uint[], uint[]));
revealBallot(epochNumber, _voters[i], resources, firstChoices, secondChoices, _salts[i]);
}
}
/**
@dev Get the number of first-choice votes cast for the given slate and resource
@param epochNumber The epoch
@param resource The resource
@param slateID The slate
*/
function getFirstChoiceVotes(uint epochNumber, address resource, uint slateID) public view returns(uint) {
SlateVotes storage v = ballots[epochNumber].contests[resource].votes[slateID];
return v.firstChoiceVotes;
}
/**
@dev Get the number of second-choice votes cast for the given slate and resource
@param epochNumber The epoch
@param resource The resource
@param slateID The slate
*/
function getSecondChoiceVotes(uint epochNumber, address resource, uint slateID) public view returns(uint) {
// for each option that isn't this one, get the second choice votes
Contest storage contest = ballots[epochNumber].contests[resource];
uint numSlates = contest.stakedSlates.length;
uint votes = 0;
for (uint i = 0; i < numSlates; i++) {
uint otherSlateID = contest.stakedSlates[i];
if (otherSlateID != slateID) {
SlateVotes storage v = contest.votes[otherSlateID];
// get second-choice votes for the target slate
votes = votes.add(v.secondChoiceVotes[slateID]);
}
}
return votes;
}
/**
@dev Return true if the voter has revealed for the given epoch
@param epochNumber The epoch
@param voter The voter's address
*/
function didReveal(uint epochNumber, address voter) public view returns(bool) {
return ballots[epochNumber].commitments[voter].revealed;
}
/**
@dev Finalize contest, triggering a vote count if necessary, and update the status of the
contest.
If there is a single slate, it automatically wins. Otherwise, count votes.
Count the first choice votes for each slate. If a slate has more than 50% of the votes,
then it wins and the vote is finalized. Otherwise, wait for a runoff. If no
votes are counted, finalize without a winner.
@param epochNumber The epoch
@param resource The resource to finalize for
*/
function finalizeContest(uint epochNumber, address resource) public {
require(isCurrentGatekeeper(), "Not current gatekeeper");
// Finalization must be after the vote period (i.e when the given epoch is over)
require(currentEpochNumber() > epochNumber, "Contest epoch still active");
// Make sure the ballot has a contest for this resource
Contest storage contest = ballots[epochNumber].contests[resource];
require(contest.status == ContestStatus.Active || contest.status == ContestStatus.NoContest,
"Either no contest is in progress for this resource, or it has been finalized");
// A single staked slate in the contest automatically wins
if (contest.status == ContestStatus.NoContest) {
uint256 winningSlate = contest.stakedSlates[0];
assert(slates[winningSlate].status == SlateStatus.Staked);
contest.winner = winningSlate;
contest.status = ContestStatus.Finalized;
acceptSlate(winningSlate);
emit ContestAutomaticallyFinalized(epochNumber, resource, winningSlate);
return;
}
// no votes
if (contest.totalVotes > 0) {
uint256 winnerVotes = contest.leaderVotes;
// If the winner has more than 50%, we are done
// Otherwise, trigger a runoff
if (winnerVotes.mul(2) > contest.totalVotes) {
contest.winner = contest.voteLeader;
acceptSlate(contest.winner);
contest.status = ContestStatus.Finalized;
emit VoteFinalized(epochNumber, resource, contest.winner, winnerVotes, contest.totalVotes);
} else {
emit VoteFailed(epochNumber, resource, contest.voteLeader, winnerVotes, contest.voteRunnerUp, contest.runnerUpVotes, contest.totalVotes);
_finalizeRunoff(epochNumber, resource);
}
} else {
// no one voted
contest.status = ContestStatus.Finalized;
emit ContestFinalizedWithoutWinner(epochNumber, resource);
return;
}
}
/**
@dev Return the status of the specified contest
*/
function contestStatus(uint epochNumber, address resource) public view returns(ContestStatus) {
return ballots[epochNumber].contests[resource].status;
}
/**
@dev Return the IDs of the slates (staked and unstaked) associated with the contest
*/
function contestSlates(uint epochNumber, address resource) public view returns(uint[] memory) {
return ballots[epochNumber].contests[resource].slates;
}
/**
@dev Get the details of the specified contest
*/
function contestDetails(uint256 epochNumber, address resource) external view
returns(
ContestStatus status,
uint256[] memory allSlates,
uint256[] memory stakedSlates,
uint256 lastStaked,
uint256 voteWinner,
uint256 voteRunnerUp,
uint256 winner
) {
Contest memory c = ballots[epochNumber].contests[resource];
status = c.status;
allSlates = c.slates;
stakedSlates = c.stakedSlates;
lastStaked = c.lastStaked;
voteWinner = c.voteLeader;
voteRunnerUp = c.voteRunnerUp;
winner = c.winner;
}
/**
@dev Trigger a runoff and update the status of the contest
Revert if a runoff is not pending.
Eliminate all slates but the top two from the initial vote. Re-count, including the
second-choice votes for the top two slates. The slate with the most votes wins. In case
of a tie, the earliest slate submitted (slate with the lowest ID) wins.
@param epochNumber The epoch
@param resource The resource to count votes for
*/
function _finalizeRunoff(uint epochNumber, address resource) internal {
require(isCurrentGatekeeper(), "Not current gatekeeper");
Contest storage contest = ballots[epochNumber].contests[resource];
uint voteLeader = contest.voteLeader;
uint voteRunnerUp = contest.voteRunnerUp;
// Get the number of second-choice votes for the top two choices, subtracting
// any second choice votes where the first choice was for one of the top two
SlateVotes storage leader = contest.votes[voteLeader];
SlateVotes storage runnerUp = contest.votes[voteRunnerUp];
uint256 secondChoiceVotesForLeader = leader.totalSecondChoiceVotes
.sub(runnerUp.secondChoiceVotes[voteLeader]).sub(leader.secondChoiceVotes[voteLeader]);
uint256 secondChoiceVotesForRunnerUp = runnerUp.totalSecondChoiceVotes
.sub(leader.secondChoiceVotes[voteRunnerUp]).sub(runnerUp.secondChoiceVotes[voteRunnerUp]);
uint256 leaderTotal = contest.leaderVotes.add(secondChoiceVotesForLeader);
uint256 runnerUpTotal = contest.runnerUpVotes.add(secondChoiceVotesForRunnerUp);
// Tally for the runoff
uint runoffWinner = 0;
uint runoffWinnerVotes = 0;
uint runoffLoser = 0;
uint runoffLoserVotes = 0;
// Original winner has more votes, or it's tied and the original winner has a smaller ID
if ((leaderTotal > runnerUpTotal) ||
((leaderTotal == runnerUpTotal) &&
(voteLeader < voteRunnerUp)
)) {
runoffWinner = voteLeader;
runoffWinnerVotes = leaderTotal;
runoffLoser = voteRunnerUp;
runoffLoserVotes = runnerUpTotal;
} else {
runoffWinner = voteRunnerUp;
runoffWinnerVotes = runnerUpTotal;
runoffLoser = voteLeader;
runoffLoserVotes = leaderTotal;
}
// Update state
contest.winner = runoffWinner;
contest.status = ContestStatus.Finalized;
acceptSlate(runoffWinner);
emit RunoffFinalized(epochNumber, resource, runoffWinner, runoffWinnerVotes, runoffLoser, runoffLoserVotes);
}
/**
@dev Send tokens of the rejected slates to the token capacitor.
@param epochNumber The epoch
@param resource The resource
*/
function donateChallengerStakes(uint256 epochNumber, address resource, uint256 startIndex, uint256 count) public {
Contest storage contest = ballots[epochNumber].contests[resource];
require(contest.status == ContestStatus.Finalized, "Contest is not finalized");
uint256 numSlates = contest.stakedSlates.length;
require(contest.stakesDonated != numSlates, "All stakes donated");
// If there are still stakes to be donated, continue
require(startIndex == contest.stakesDonated, "Invalid start index");
uint256 endIndex = startIndex.add(count);
require(endIndex <= numSlates, "Invalid end index");
address stakeDonationAddress = parameters.getAsAddress("stakeDonationAddress");
IDonationReceiver donationReceiver = IDonationReceiver(stakeDonationAddress);
bytes memory stakeDonationHash = "Qmepxeh4KVkyHYgt3vTjmodB5RKZgUEmdohBZ37oKXCUCm";
for (uint256 i = startIndex; i < endIndex; i++) {
uint256 slateID = contest.stakedSlates[i];
Slate storage slate = slates[slateID];
if (slate.status != SlateStatus.Accepted) {
uint256 donationAmount = slate.stake;
slate.stake = 0;
// Only donate for non-zero amounts
if (donationAmount > 0) {
require(
token.approve(address(donationReceiver), donationAmount),
"Failed to approve Gatekeeper to spend tokens"
);
donationReceiver.donate(address(this), donationAmount, stakeDonationHash);
}
}
}
// Update state
contest.stakesDonated = endIndex;
}
/**
@dev Return the ID of the winning slate for the given epoch and resource
Revert if the vote has not been finalized yet.
@param epochNumber The epoch
@param resource The resource of interest
*/
function getWinningSlate(uint epochNumber, address resource) public view returns(uint) {
Contest storage c = ballots[epochNumber].contests[resource];
require(c.status == ContestStatus.Finalized, "Vote is not finalized yet");
return c.winner;
}
// ACCESS CONTROL
/**
@dev Request permission to perform the action described in the metadataHash
@param metadataHash A reference to metadata about the action
*/
function requestPermission(bytes memory metadataHash) public returns(uint) {
require(isCurrentGatekeeper(), "Not current gatekeeper");
require(metadataHash.length > 0, "metadataHash cannot be empty");
address resource = msg.sender;
uint256 epochNumber = currentEpochNumber();
require(slateSubmissionPeriodActive(resource), "Submission period not active");
// If the request is created in epoch n, expire at the start of epoch n + 2
uint256 expirationTime = epochStart(epochNumber.add(2));
// Create new request
Request memory r = Request({
metadataHash: metadataHash,
resource: resource,
approved: false,
expirationTime: expirationTime,
epochNumber: epochNumber
});
// Record request and return its ID
uint requestID = requestCount();
requests.push(r);
emit PermissionRequested(epochNumber, resource, requestID, metadataHash);
return requestID;
}
/**
@dev Update a slate and its associated requests
@param slateID The slate to update
*/
function acceptSlate(uint slateID) private {
// Mark the slate as accepted
Slate storage s = slates[slateID];
s.status = SlateStatus.Accepted;
// Record the incumbent
if (incumbent[s.resource] != s.recommender) {
incumbent[s.resource] = s.recommender;
}
// mark all of its requests as approved
uint[] memory requestIDs = s.requests;
for (uint i = 0; i < requestIDs.length; i++) {
uint requestID = requestIDs[i];
requests[requestID].approved = true;
}
}
/**
@dev Return true if the requestID has been approved via slate governance and has not expired
@param requestID The ID of the request to check
*/
function hasPermission(uint requestID) public view returns(bool) {
return requests[requestID].approved && now < requests[requestID].expirationTime;
}
// MISCELLANEOUS GETTERS
function slateCount() public view returns(uint256) {
return slates.length;
}
function requestCount() public view returns (uint256) {
return requests.length;
}
/**
@dev Return the slate submission deadline for the given resource
@param epochNumber The epoch
@param resource The resource
*/
function slateSubmissionDeadline(uint256 epochNumber, address resource) public view returns(uint256) {
Contest memory contest = ballots[epochNumber].contests[resource];
uint256 offset = (contest.lastStaked.add(COMMIT_PERIOD_START)).div(2);
return epochStart(epochNumber).add(offset);
}
/**
@dev Return true if the slate submission period is active for the given resource and the
current epoch.
*/
function slateSubmissionPeriodActive(address resource) public view returns(bool) {
uint256 epochNumber = currentEpochNumber();
uint256 start = epochStart(epochNumber).add(SLATE_SUBMISSION_PERIOD_START);
uint256 end = slateSubmissionDeadline(epochNumber, resource);
return (start <= now) && (now < end);
}
/**
@dev Return true if the commit period is active for the current epoch
*/
function commitPeriodActive() private view returns(bool) {
uint256 epochTime = now.sub(epochStart(currentEpochNumber()));
return (COMMIT_PERIOD_START <= epochTime) && (epochTime < REVEAL_PERIOD_START);
}
/**
@dev Return true if this is the Gatekeeper currently pointed to by the ParameterStore
*/
function isCurrentGatekeeper() public view returns(bool) {
return parameters.getAsAddress("gatekeeperAddress") == address(this);
}
}
| / extract resources, firstChoices, secondChoices from the ballot | function revealManyBallots(
uint256 epochNumber,
address[] memory _voters,
bytes[] memory _ballots,
uint[] memory _salts
) public {
uint numBallots = _voters.length;
require(
_salts.length == _voters.length && _ballots.length == _voters.length,
"Inputs must have the same length"
);
for (uint i = 0; i < numBallots; i++) {
(
address[] memory resources,
uint[] memory firstChoices,
uint[] memory secondChoices
) = abi.decode(_ballots[i], (address[], uint[], uint[]));
revealBallot(epochNumber, _voters[i], resources, firstChoices, secondChoices, _salts[i]);
}
}
@param epochNumber The epoch
@param resource The resource
@param slateID The slate
| 927,860 |
/**
*Submitted for verification at Etherscan.io on 2021-11-03
*/
// SPDX-License-Identifier: MIT
// 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/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @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);
}
// File: token.sol
// contracts/SimpleToken.sol
pragma solidity ^0.8.7;
/**
* @title CRI
* @dev CRI is the token for Crypto International
* All rights reserved by Crypto International Inc.
*/
contract CRI is Context, IERC20, IERC20Metadata {
address private _owner;
uint256 private _reward;
uint256 private _reward_period;
mapping (address => uint256) private _stakes;
mapping (address => uint256) private _stake_ts;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Constructor that gives _msgSender() all of existing tokens.
*
* - `initialSupply` and `initialReward` should have the unit of 1e-18.
*
*/
constructor (
string memory name_,
string memory symbol_,
uint256 initialSupply,
uint256 initialReward,
uint32 rewardPeriod
) {
_name = name_;
_symbol = symbol_;
_reward = initialReward;
_reward_period = rewardPeriod;
_owner = _msgSender();
_mint(_msgSender(), initialSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `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 { }
/**
* @dev adjusts the per-day reward value per token.
*
* - `reward` should have the unit of 1e-18
*
*/
function setReward(uint256 reward) public {
require(_msgSender() == _owner);
_reward = reward;
}
/**
* @dev mints new tokens.
*
* - `amount` specifies amount of tokens to be minted (in 1e-18).
*
*/
function mint(uint256 amount) public {
require(_msgSender() == _owner);
_mint(_msgSender(), amount);
}
/**
* @dev rewards sender rewards for holding their tokens.
*
* CRI wallets can choose to obtain daily reward for tokens they are
* currently holding. Wallet holders can specify any amount equals to or
* below their balance to get reward for. Please note that by getting
* reward, the specified portion of their balance will be locked.
*
*/
function getReward() public {
require(_stake_ts[_msgSender()] <= block.timestamp - _reward_period, "CRI: need to keep stake for at least a day.");
uint256 unit_reward = _stakes[_msgSender()] * _reward / 1e18;
uint256 units = (block.timestamp - _stake_ts[_msgSender()]) / _reward_period;
_stake_ts[_msgSender()] += units * _reward_period;
_mint(_msgSender(), unit_reward * units);
}
/**
* @dev put tokens into staking.
*
* CRI allows user to obtain reward by participating in staking. Users need
* to explicitly add their tokens for staking to be able to receive reward.
*
* - `amount` specifies amount of tokens to add stake for.
*
*/
function putStake(uint256 amount) public {
require(_balances[_msgSender()] >= amount, "CRI: Not enough balance");
require(_stakes[_msgSender()] == 0, "CRI: Must empty stake first");
_stakes[_msgSender()] = amount;
_stake_ts[_msgSender()] = block.timestamp;
_balances[_msgSender()] -= amount;
}
/**
* @dev retrieve tokens from staking.
*
* CRI allows user to obtain reward by participating in staking. Users need
* to explicitly add their tokens for staking to be able to receive reward.
*
*/
function retrieveStake() public {
require(_stakes[_msgSender()] >= 0, "CRI: Empty stake");
_balances[_msgSender()] += _stakes[_msgSender()];
_stakes[_msgSender()] = 0;
}
/**
* @dev view the amount of stake that the sender currently has.
*
*/
function viewStake() public
view
returns(uint256) {
return _stakes[_msgSender()];
}
/**
* @dev view the current reward period.
*
*/
function viewRewardPeriod() public
view
returns(uint256) {
return _reward_period;
}
/**
* @dev view the currenct reward per token.
*
*/
function viewReward() public
view
returns(uint256) {
return _reward;
}
} | mints new tokens. - `amount` specifies amount of tokens to be minted (in 1e-18)./ | function mint(uint256 amount) public {
require(_msgSender() == _owner);
_mint(_msgSender(), amount);
}
| 7,954,020 |
./partial_match/1/0xd49B090E3E959cB34F8b6f485D7Af56bc48394AA/sources/ClusterRewards.sol | clusters[_cluster].accRewardPerShare[tokens[i]] = clusters[_cluster].accRewardPerShare[tokens[i]].add( delegatorReward .mul(rewardFactor[tokens[i]]) .mul(1030) .div(weightedStake) ); | function _updateRewards(address _cluster) public {
uint256 reward = clusterRewards.claimReward(_cluster);
if(reward == 0) {
return;
}
Cluster memory cluster = clusters[_cluster];
if(cluster.weightedStake == 0) {
clusters[_cluster].lastRewardDistNonce++;
return;
}
uint256 commissionReward = reward.mul(clusterRegistry.getCommission(_cluster)).div(100);
uint256 delegatorReward = reward.sub(commissionReward);
uint256 weightedStake = cluster.weightedStake;
bytes32[] memory tokens = tokenList;
for(uint i=0; i < tokens.length; i++) {
clusters[_cluster].accRewardPerShare[tokens[i]] = clusters[_cluster].accRewardPerShare[tokens[i]].add(
delegatorReward
.mul(10**30)
.div(tokens.length)
.div(totalDelegations[tokens[i]])
);
}
clusters[_cluster].lastRewardDistNonce = cluster.lastRewardDistNonce.add(1);
transferRewards(clusterRegistry.getRewardAddress(_cluster), commissionReward);
emit ClusterRewardDistributed(_cluster);
}
| 9,355,942 |
pragma solidity ^0.4.25;
/**
* Digipay Network - The Future of Online Payments
* ----------------------------------------------------------------------------
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
* ----------------------------------------------------------------------------
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev if the owner calls this function, the function is executed
* and otherwise, an exception is thrown.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
* ----------------------------------------------------------------------------
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev https://github.com/ethereum/EIPs/issues/179
* @dev This ERC describes a simpler version of the ERC20 standard token contract
* ----------------------------------------------------------------------------
*/
contract ERC20Basic {
// The total token supply
function totalSupply() public view returns (uint256);
// @notice Get the account balance of another account with address `who`
function balanceOf(address who) public view returns (uint256);
// @notice Transfer `value' amount of tokens to address `to`
function transfer(address to, uint256 value) public returns (bool);
// @notice Triggered when tokens are transferred
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 Standard
* @dev https://github.com/ethereum/EIPs/issues/20
* ----------------------------------------------------------------------------
*/
contract ERC20 is ERC20Basic {
// @notice Returns the amount which `spender` is still allowed to withdraw from `owner`
function allowance(address owner, address spender) public view returns (uint256);
// @notice Transfer `value` amount of tokens from address `from` to address `to`
// Address `to` can withdraw after it is approved by address `from`
function transferFrom(address from, address to, uint256 value) public returns (bool);
// @notice Allow `spender` to withdraw, multiple times, up to the `value` amount
function approve(address spender, uint256 value) public returns (bool);
// @notice Triggered whenever approve(address spender, uint256 value) is called
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title BasicToken
* @dev Simpler version of StandardToken, with basic functions
* ----------------------------------------------------------------------------
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
// @notice This creates an array with all balances
mapping(address => uint256) balances;
// @notice Get the token balance of address `_owner`
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns (bool) {
// @notice Prevent transfer to 0x0 address
require(_to != address(0));
// @notice `Check if the sender has enough` is not needed
// because sub(balances[msg.sender], _value) will `throw` if this condition is not met
require(balances[msg.sender] >= _value);
// @notice `Check for overflows` is not needed
// because add(_to, _value) will `throw` if this condition is not met
require(balances[_to] + _value >= balances[_to]);
// @notice Subtract from the sender
balances[msg.sender] = balances[msg.sender].sub(_value);
// @notice Add the same to the recipient
balances[_to] = balances[_to].add(_value);
// @notice Trigger `transfer` event
emit Transfer(msg.sender, _to, _value);
return true;
}
}
/**
* @title ERC20 Token Standard
* @dev Implementation of the Basic token standard
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
* ----------------------------------------------------------------------------
*/
contract StandardToken is ERC20, BasicToken {
// @notice Owner of address approves the transfer of an amount to another address
mapping (address => mapping (address => uint256)) allowed;
// @notice Owner allows `_spender` to transfer or withdraw `_value` tokens from owner to `_spender`
// Trigger `approve` event
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
// @notice This check is not needed
// because sub(_allowance, _value) will throw if this condition is not met
require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
// @notice Returns the amount which `_spender` is still allowed to withdraw from `_owner`
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* @notice Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @notice Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title tokensale.digipay.network TokenSaleKYC
* @dev Verified addresses can participate in the token sale
*/
contract TokenSaleKYC is Ownable {
// @dev This creates an array with all verification statuses of addresses
mapping(address=>bool) public verified;
//@dev Trigger `verification status` events
event VerificationStatusUpdated(address participant, bool verificationStatus);
/**
* @dev Updates verification status of an address
* @dev Only owner can update
* @param participant Address that is submitted by a participant
* @param verificationStatus True or false
*/
function updateVerificationStatus(address participant, bool verificationStatus) public onlyOwner {
verified[participant] = verificationStatus;
emit VerificationStatusUpdated(participant, verificationStatus);
}
/**
* @dev Updates verification statuses of addresses
* @dev Only owner can update
* @param participants An array of addresses
* @param verificationStatus True or false
*/
function updateVerificationStatuses(address[] participants, bool verificationStatus) public onlyOwner {
for (uint i = 0; i < participants.length; i++) {
updateVerificationStatus(participants[i], verificationStatus);
}
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
* ----------------------------------------------------------------------------
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title DigiPayToken contract
* @dev Allocate tokens to wallets based on our token distribution
* @dev Accept contributions only within a time frame
* @dev Participants must complete KYC process
* @dev There are two stages (Pre-sale and Mainsale)
* @dev Require minimum and maximum contributions
* @dev Calculate bonuses and rates
* @dev Can pause contributions
* @dev The token sale stops automatically when the hardcap is reached
* @dev Lock (can not transfer) tokens until the token sale ends
* @dev Burn unsold tokens
* @dev Update the total supply after burning
* @author digipay.network
* ----------------------------------------------------------------------------
*/
contract DigiPayToken is StandardToken, Ownable, TokenSaleKYC, Pausable {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 public weiRaised;
uint256 public hardCap;
address public wallet;
address public TEAM_WALLET;
address public AIRDROP_WALLET;
address public RESERVE_WALLET;
uint internal _totalSupply;
uint internal _teamAmount;
uint internal _airdropAmount;
uint internal _reserveAmount;
uint256 internal presaleStartTime;
uint256 internal presaleEndTime;
uint256 internal mainsaleStartTime;
uint256 internal mainsaleEndTime;
bool internal presaleOpen;
bool internal mainsaleOpen;
bool internal Open;
bool public locked;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount);
event Burn(address indexed burner, uint tokens);
// @dev The token sale stops automatically when the hardcap is reached
modifier onlyWhileOpen {
require(now >= presaleStartTime && now <= mainsaleEndTime && Open && weiRaised <= hardCap);
_;
}
// @dev Lock (can not transfer) tokens until the token sale ends
// Aidrop wallet and reserve wallet are allowed to transfer
modifier onlyUnlocked() {
require(msg.sender == AIRDROP_WALLET || msg.sender == RESERVE_WALLET || msg.sender == owner || !locked);
_;
}
/**
* ------------------------------------------------------------------------
* Constructor
* ------------------------------------------------------------------------
*/
constructor (address _owner, address _wallet, address _team, address _airdrop, address _reserve) public {
_setTimes();
name = "DigiPay";
symbol = "DIP";
decimals = 18;
hardCap = 20000 ether;
owner = _owner;
wallet = _wallet;
TEAM_WALLET = _team;
AIRDROP_WALLET = _airdrop;
RESERVE_WALLET = _reserve;
// @dev initial total supply
_totalSupply = 180000000e18;
// @dev Tokens initialy allocated for the team (20%)
_teamAmount = 36000000e18;
// @dev Tokens initialy allocated for airdrop campaigns (8%)
_airdropAmount = 14400000e18;
// @dev Tokens initialy allocated for testing the platform (2%)
_reserveAmount = 3600000e18;
balances[this] = totalSupply();
emit Transfer(address(0x0),this, totalSupply());
_transfer(TEAM_WALLET, _teamAmount);
_transfer(AIRDROP_WALLET, _airdropAmount);
_transfer(RESERVE_WALLET, _reserveAmount);
Open = true;
locked = true;
}
function updateWallet(address _wallet) public onlyOwner {
wallet = _wallet;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function _setTimes() internal {
presaleStartTime = 1541062800; // 01st Nov 2018 09:00:00 GMT
presaleEndTime = 1543481999; // 29th Nov 2018 08:59:59 GMT
mainsaleStartTime = 1545296400; // 20th Dec 2018 09:00:00 GMT
mainsaleEndTime = 1548320399; // 24th Jan 2019 08:59:59 GMT
}
function unlock() public onlyOwner {
locked = false;
}
function lock() public onlyOwner {
locked = true;
}
/**
* @dev override `transfer` function to add onlyUnlocked
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) public onlyUnlocked returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev override `transferFrom` function to add onlyUnlocked
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferFrom(address _from, address _to, uint _value) public onlyUnlocked returns (bool) {
return super.transferFrom(_from, _to, _value);
}
// @dev Return `true` if the token sale is live
function _checkOpenings() internal {
if(now >= presaleStartTime && now <= presaleEndTime) {
presaleOpen = true;
mainsaleOpen = false;
}
else if(now >= mainsaleStartTime && now <= mainsaleEndTime) {
presaleOpen = false;
mainsaleOpen = true;
}
else {
presaleOpen = false;
mainsaleOpen = false;
}
}
// @dev Fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) internal onlyWhileOpen whenNotPaused {
// @dev `msg.value` contains the amount of wei sent in a transaction
uint256 weiAmount = msg.value;
/**
* @dev Validation of an incoming purchase
* @param _beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
require(_beneficiary != address(0));
require(weiAmount != 0);
_checkOpenings();
/**
* @dev Check verification statuses of addresses
* @return True if participants can buy tokens, false otherwise
*/
require(verified[_beneficiary]);
require(presaleOpen || mainsaleOpen);
if(presaleOpen) {
// @dev Presale contributions must be Min 2 ETH and Max 500 ETH
require(weiAmount >= 2e18 && weiAmount <= 5e20);
}
else {
// @dev Mainsale contributions must be Min 0.2 ETH and Max 500 ETH
require(weiAmount >= 2e17 && weiAmount <= 5e20);
}
// @dev Calculate token amount to be returned
uint256 tokens = _getTokenAmount(weiAmount);
// @dev Get more 10% bonus when purchasing more than 10 ETH
if(weiAmount >= 10e18) {
tokens = tokens.add(weiAmount.mul(500));
}
// @dev Update funds raised
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
// @dev Trigger `token purchase` event
emit TokenPurchase(_beneficiary, weiAmount, tokens);
_forwardFunds(msg.value);
}
/**
* @dev Return an amount of tokens based on a current token rate
* @param _weiAmount Value in wei to be converted into tokens
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 RATE;
if(presaleOpen) {
RATE = 7500; // @dev 1 ETH = 7500 DIP
}
if(now >= mainsaleStartTime && now < (mainsaleStartTime + 1 weeks)) {
RATE = 6000; // @dev 1 ETH = 6000 DIP
}
if(now >= (mainsaleStartTime + 1 weeks) && now < (mainsaleStartTime + 2 weeks)) {
RATE = 5750; // @dev 1 ETH = 5750 DIP
}
if(now >= (mainsaleStartTime + 2 weeks) && now < (mainsaleStartTime + 3 weeks)) {
RATE = 5500; // @dev 1 ETH = 5500 DIP
}
if(now >= (mainsaleStartTime + 3 weeks) && now < (mainsaleStartTime + 4 weeks)) {
RATE = 5250; // @dev 1 ETH = 5250 DIP
}
if(now >= (mainsaleStartTime + 4 weeks) && now <= mainsaleEndTime) {
RATE = 5000; // @dev 1 ETH = 5000 DIP
}
return _weiAmount.mul(RATE);
}
/**
* @dev Source of tokens
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
_transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Forward ether to the fund collection wallet
* @param _amount Amount of wei to be forwarded
*/
function _forwardFunds(uint256 _amount) internal {
wallet.transfer(_amount);
}
/**
* @dev Transfer `tokens` from contract address to address `to`
*/
function _transfer(address to, uint256 tokens) internal returns (bool success) {
require(to != 0x0);
require(balances[this] >= tokens );
require(balances[to] + tokens >= balances[to]);
balances[this] = balances[this].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(this,to,tokens);
return true;
}
/**
* @dev Allow owner to call an emergency stop
*/
function stopTokenSale() public onlyOwner {
Open = false;
}
/**
* @dev Allow owner to transfer free tokens from `AIRDROP_WALLET` to multiple wallet addresses
*/
function sendtoMultiWallets(address[] _addresses, uint256[] _values) public onlyOwner {
require(_addresses.length == _values.length);
for (uint256 i = 0; i < _addresses.length; i++) {
// @dev Update balances and trigger `transfer` events
balances[AIRDROP_WALLET] = balances[AIRDROP_WALLET].sub(_values[i]*10**uint(decimals));
balances[_addresses[i]] = balances[_addresses[i]].add(_values[i]*10**uint(decimals));
emit Transfer(AIRDROP_WALLET, _addresses[i], _values[i]*10**uint(decimals));
}
}
/**
* @dev Transfer the unsold tokens from contract address
* @dev This function can be used only if the token sale does not reach Softcap
*/
function drainRemainingToken(address _to, uint256 _value) public onlyOwner {
require(now > mainsaleEndTime);
_transfer(_to, _value);
}
/**
* @dev Burn unsold tokens
* @param _value The remaining amount to be burned
*/
function burnRemainingToken(uint256 _value) public onlyOwner returns (bool) {
balances[this] = balances[this].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(this, _value);
emit Transfer(this, address(0x0), _value);
return true;
}
} | Executed when a purchase has been validated and is ready to be executed _beneficiary Address receiving the tokens _tokenAmount Number of tokens to be purchased/ | function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
| 6,354,933 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "hardhat/console.sol";
contract Marketplace is ReentrancyGuard, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _itemIds;
Counters.Counter private _itemSold; // total number of items sold
mapping(address => uint) public userWallets;
uint public fee = 0.025 ether; // only charge when sales are made
struct ListingItem {
uint itemId;
address nftContract;
uint tokenId;
address payable seller;
address payable owner; // initial to address(0), then new owner/buyder
uint price;
bool sold;
}
mapping(uint => ListingItem) private _listingItems;
event ItemListed(
uint itemId,
address indexed nftContract,
uint indexed tokenId,
address payable seller,
address payable owner,
uint price,
bool sold
);
event ItemSold(
uint itemId,
address indexed nftContract,
uint indexed tokenId,
address payable seller,
address payable owner,
uint price,
bool sold
);
// function setFee(uint _price) public onlyOwner {
// fee = _price;
// }
function listItem(address nftContract, uint tokenId, uint price) public nonReentrant {
uint _newItemId = _itemIds.current();
_listingItems[_newItemId] = ListingItem(
_newItemId,
nftContract,
tokenId,
payable(msg.sender),
payable(address(0)),
price,
false
);
_itemIds.increment();
IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId);
emit ItemListed(
_newItemId,
nftContract,
tokenId,
payable(msg.sender),
payable(address(0)),
price,
false
);
}
function buyItem(address nftContract, uint itemId) public payable nonReentrant {
require(msg.value == _listingItems[itemId].price + fee, "Price does not match listing price");
require(!_listingItems[itemId].sold, "Item is already sold");
IERC721(nftContract).transferFrom(address(this), msg.sender, _listingItems[itemId].tokenId);
// send price to the seller's wallet
// take withdrawal pattern
userWallets[_listingItems[itemId].seller] += (msg.value-fee);
_listingItems[itemId].owner = payable(msg.sender);
_listingItems[itemId].sold = true;
_itemSold.increment();
emit ItemSold(
itemId,
nftContract,
_listingItems[itemId].tokenId,
payable(_listingItems[itemId].seller),
payable(msg.sender),
_listingItems[itemId].price,
true
);
}
/// @notice user can withdraw from their wallet
function withdraw() public {
require(userWallets[msg.sender] > 0, "No money to withdraw");
(bool sent,) = msg.sender.call{value: userWallets[msg.sender]}("");
require(sent, "Failed to send Ether");
userWallets[msg.sender] = 0;
}
/// @notice fetch all unsold items
function fetchAllListingItems() public view returns (ListingItem[] memory) {
ListingItem[] memory _items = new ListingItem[](_itemIds.current() - _itemSold.current());
uint _itemCount = 0;
for (uint i = 0; i < _itemIds.current(); i++) {
if(!_listingItems[i].sold && _listingItems[i].owner == address(0)){
_items[_itemCount] = _listingItems[i];
_itemCount++;
}
}
return _items;
}
/// @notice fetch items user bought
function fetchUserBoughtItems() public view returns (ListingItem[] memory) {
uint _userItemCount = 0;
for (uint i = 0; i < _itemIds.current(); i++) {
if(_listingItems[i].sold && _listingItems[i].owner == address(msg.sender)){
_userItemCount++;
}
}
uint _itemCount = 0;
ListingItem[] memory _items = new ListingItem[](_userItemCount);
for (uint i = 0; i < _itemIds.current(); i++) {
if(_listingItems[i].sold && _listingItems[i].owner == address(msg.sender)){
_items[_itemCount] = _listingItems[i];
_itemCount++;
}
}
return _items;
}
/// @notice fetch item user owns
function fetchUserOwningItems() public view returns (ListingItem[] memory) {
uint _userItemCount = 0;
for (uint i = 0; i < _itemIds.current(); i++) {
if(_listingItems[i].owner == address(msg.sender)){
_userItemCount++;
}
}
uint _itemCount = 0;
ListingItem[] memory _items = new ListingItem[](_userItemCount);
for (uint i = 0; i < _itemIds.current(); i++) {
if(_listingItems[i].owner == address(msg.sender)){
_items[_itemCount] = _listingItems[i];
_itemCount++;
}
}
return _items;
}
/// @notice fetch user's listing/unsold items
function fetchUserListingItems() public view returns (ListingItem[] memory) {
uint _userItemCount = 0;
for (uint i = 0; i < _itemIds.current(); i++) {
if(!_listingItems[i].sold && _listingItems[i].seller == address(msg.sender)){
_userItemCount++;
}
}
uint _itemCount = 0;
ListingItem[] memory _items = new ListingItem[](_userItemCount);
for (uint i = 0; i < _itemIds.current(); i++) {
if(!_listingItems[i].sold && _listingItems[i].seller == address(msg.sender)){
_items[_itemCount] = _listingItems[i];
_itemCount++;
}
}
return _items;
}
} | user can withdraw from their wallet | function withdraw() public {
require(userWallets[msg.sender] > 0, "No money to withdraw");
require(sent, "Failed to send Ether");
userWallets[msg.sender] = 0;
}
| 12,855,249 |
./full_match/1/0x29F933645F8086719236825A28d04D8A055D98dB/sources/_arbitrum/token-bridge-contracts/contracts/tokenbridge/arbitrum/gateway/L2CustomGateway.sol | internal utility function used to handle when no contract is deployed at expected address/ it is assumed that the custom token is deployed in the L2 before deposits are made trigger withdrawal we don't need the return value from triggerWithdrawal since this is forcing a withdrawal back to the L1 instead of composing with a L2 dapp | function handleNoContract(
address _l1Token,
address, /* expectedL2Address */
address _from,
address, /* _to */
uint256 _amount,
bytes memory /* gatewayData */
) internal override returns (bool shouldHalt) {
triggerWithdrawal(_l1Token, address(this), _from, _amount, "");
return true;
}
| 8,380,489 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../../ImplBase.sol";
import "../../helpers/errors.sol";
import "../../interfaces/arbitrum.sol";
/**
// @title Native Arbitrum Bridge Implementation.
// @notice This is the L1 implementation,
// so this is used when transferring from ethereum to arbitrum via their native bridge.
// Called by the registry if the selected bridge is Native Arbitrum.
// @dev Follows the interface of ImplBase. This is only used for depositing tokens.
// @author Movr Network.
*/
contract NativeArbitrumImpl is ImplBase, ReentrancyGuard {
using SafeERC20 for IERC20;
address public router;
address public inbox;
event UpdateArbitrumRouter(address indexed routerAddress);
event UpdateArbitrumInbox(address indexed inbox);
/// @notice registry and L1 gateway router address required.
constructor(
address _registry,
address _router,
address _inbox
) ImplBase(_registry) {
router = _router;
inbox = _inbox;
}
/// @notice setter function for the L1 gateway router address
function setInbox(address _inbox) public onlyOwner {
inbox = _inbox;
emit UpdateArbitrumInbox(_inbox);
}
/// @notice setter function for the L1 gateway router address
function setRouter(address _router) public onlyOwner {
router = _router;
emit UpdateArbitrumRouter(_router);
}
/**
// @notice function responsible for the native arbitrum deposits from ethereum.
// @dev gateway address is the address where the first deposit is made.
// It holds max submission price and further data.
// @param _amount amount to be sent.
// @param _from senders address
// @param _receiverAddress receivers address
// @param _token token address on the source chain that is L1.
// param _toChainId not required, follows the impl base.
// @param _extraData extradata required for calling the l1 router function. Explain above.
*/
function outboundTransferTo(
uint256 _amount,
address _from,
address _receiverAddress,
address _token,
uint256, // _toChainId
bytes memory _extraData
) external payable override onlyRegistry nonReentrant {
IERC20 token = IERC20(_token);
(
address _gatewayAddress,
uint256 _maxGas,
uint256 _gasPriceBid,
bytes memory _data
) = abi.decode(_extraData, (address, uint256, uint256, bytes));
if (_token == NATIVE_TOKEN_ADDRESS) {
require(msg.value != 0, MovrErrors.VALUE_SHOULD_NOT_BE_ZERO);
Inbox(inbox).depositEth{value: _amount}(_maxGas);
return;
}
// @notice here we dont provide a 0 value check
// since arbitrum may need native token as well along
// with ERC20
token.safeTransferFrom(_from, address(this), _amount);
token.safeIncreaseAllowance(_gatewayAddress, _amount);
L1GatewayRouter(router).outboundTransfer{value: msg.value}(
_token,
_receiverAddress,
_amount,
_maxGas,
_gasPriceBid,
_data
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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'
// 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");
}
}
}
// 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.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./helpers/errors.sol";
/**
@title Abstract Implementation Contract.
@notice All Bridge Implementation will follow this interface.
*/
abstract contract ImplBase is Ownable {
using SafeERC20 for IERC20;
address public registry;
address public constant NATIVE_TOKEN_ADDRESS =
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
event UpdateRegistryAddress(address indexed registryAddress);
constructor(address _registry) Ownable() {
registry = _registry;
}
modifier onlyRegistry() {
require(msg.sender == registry, MovrErrors.INVALID_SENDER);
_;
}
function updateRegistryAddress(address newRegistry) external onlyOwner {
registry = newRegistry;
emit UpdateRegistryAddress(newRegistry);
}
function rescueFunds(
address token,
address userAddress,
uint256 amount
) external onlyOwner {
IERC20(token).safeTransfer(userAddress, amount);
}
function outboundTransferTo(
uint256 _amount,
address _from,
address _receiverAddress,
address _token,
uint256 _toChainId,
bytes memory _extraData
) external payable virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
library MovrErrors {
string internal constant ADDRESS_0_PROVIDED = "ADDRESS_0_PROVIDED";
string internal constant EMPTY_INPUT = "EMPTY_INPUT";
string internal constant LENGTH_MISMATCH = "LENGTH_MISMATCH";
string internal constant INVALID_VALUE = "INVALID_VALUE";
string internal constant INVALID_AMT = "INVALID_AMT";
string internal constant IMPL_NOT_FOUND = "IMPL_NOT_FOUND";
string internal constant ROUTE_NOT_FOUND = "ROUTE_NOT_FOUND";
string internal constant IMPL_NOT_ALLOWED = "IMPL_NOT_ALLOWED";
string internal constant ROUTE_NOT_ALLOWED = "ROUTE_NOT_ALLOWED";
string internal constant INVALID_CHAIN_DATA = "INVALID_CHAIN_DATA";
string internal constant CHAIN_NOT_SUPPORTED = "CHAIN_NOT_SUPPORTED";
string internal constant TOKEN_NOT_SUPPORTED = "TOKEN_NOT_SUPPORTED";
string internal constant NOT_IMPLEMENTED = "NOT_IMPLEMENTED";
string internal constant INVALID_SENDER = "INVALID_SENDER";
string internal constant INVALID_BRIDGE_ID = "INVALID_BRIDGE_ID";
string internal constant MIDDLEWARE_ACTION_FAILED =
"MIDDLEWARE_ACTION_FAILED";
string internal constant VALUE_SHOULD_BE_ZERO = "VALUE_SHOULD_BE_ZERO";
string internal constant VALUE_SHOULD_NOT_BE_ZERO = "VALUE_SHOULD_NOT_BE_ZERO";
string internal constant VALUE_NOT_ENOUGH = "VALUE_NOT_ENOUGH";
string internal constant VALUE_NOT_EQUAL_TO_AMOUNT = "VALUE_NOT_EQUAL_TO_AMOUNT";
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity >=0.8.0;
interface L1GatewayRouter {
function outboundTransfer(
address _token,
address _to,
uint256 _amount,
uint256 _maxGas,
uint256 _gasPriceBid,
bytes calldata _data
) external payable returns (bytes calldata);
}
interface Inbox {
function depositEth(uint256 maxSubmissionCost) external payable returns (uint256) ;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
} | setter function for the L1 gateway router address | function setInbox(address _inbox) public onlyOwner {
inbox = _inbox;
emit UpdateArbitrumInbox(_inbox);
}
| 6,974,609 |
pragma solidity ^0.5.16;
interface IBEP20 {
// Returns the amount of tokens in existence
function totalSupply() external view returns (uint);
// Returns the token decimals
function decimals() external view returns (uint);
// Returns the token symbol
function symbol() external view returns (string memory);
// Returns the token name
function name() external view returns (string memory);
// Returns the token owner
function getOwner() external view returns (address);
// Returns the amount of tokens owned by `account`
function balanceOf(address account) external view returns (uint);
// Moves `amount` tokens from the caller's account to `recipient`
function transfer(address recipient, uint 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 (uint);
/// Sets `amount` as the allowance of `spender` over the caller's tokens
function approve(address spender, uint amount) external returns (bool);
// Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
/* EVENTS */
// Emitted when `value` tokens are moved from one account (`from`) to another (`to`)
event Transfer(address indexed from, address indexed to, uint 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, uint value);
}
// Provides information about the current execution context
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
// Wrappers over Solidity's arithmetic operations with added overflow checks
library SafeMath {
// Returns the addition of two unsigned integers, reverting on 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)
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)
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.
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;
}
// Returns the integer division of two unsigned integers. Reverts on
// division by zero. The result is rounded towards 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
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
// Provides a basic access control mechanism, where there is an
// owner that can be granted exclusive access to specific functions
contract Ownable is Context {
address public _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 owner() public view returns (address) {
return _owner;
}
// Throws if called by any account other than the owner
modifier onlyOwner() {
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 transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
// Transfers ownership of the contract to a new account (`newOwner`)
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract BlackList is Ownable {
uint public _totalSupply;
// Getters to allow the same blacklist to be used also by other contracts
function getBlackListStatus(address _maker) external view returns (bool) {
return isBlackListed[_maker];
}
// Returns the token owner
function getOwner() external view returns (address) {
return owner();
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = _balances[_blackListedUser];
_balances[_blackListedUser] = 0;
_totalSupply -= dirtyFunds;
DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
contract WhiteList is Ownable {
// Getters to allow the same Whitelist to be used also by other contracts
function getWhiteListStatus(address _maker) external view returns (bool) {
return isWhiteListed[_maker];
}
// Returns the token owner
function getOwner() external view returns (address) {
return owner();
}
mapping (address => bool) public isWhiteListed;
function addWhiteList (address _user) public onlyOwner {
isWhiteListed[_user] = true;
emit AddedWhiteList(_user);
}
function removeWhiteList (address _user) public onlyOwner {
isWhiteListed[_user] = false;
emit RemovedWhiteList(_user);
}
event AddedWhiteList(address _user);
event RemovedWhiteList(address _user);
}
// Allows to implement an emergency stop mechanism
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
// Modifier to make a function callable only when the contract is not paused
modifier whenNotPaused() {
require(!paused);
_;
}
// Modifier to make a function callable only when the contract is paused
modifier whenPaused() {
require(paused);
_;
}
// Called by the owner to pause, triggers stopped state
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
// Called by the owner to unpause, returns to normal state
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract BEP20Token is Context, Ownable, BlackList, WhiteList {
using SafeMath for uint;
// Get the balances
mapping (address => mapping (address => uint)) public _allowances;
mapping (address => uint) public _balances;
string public _name;
string public _symbol;
uint public _decimals;
constructor (
string memory tokenName,
string memory tokenSymbol,
uint initialSupply,
uint decimalUnits
) public {
_name = tokenName;
_symbol = tokenSymbol;
_decimals = decimalUnits;
_totalSupply = initialSupply * (10 ** _decimals);
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
// Returns the token decimals
function decimals() external view returns (uint) {
return _decimals;
}
// Returns the token symbol
function symbol() external view returns (string memory) {
return _symbol;
}
// Returns the token name
function name() external view returns (string memory) {
return _name;
}
// See {BEP20-totalSupply}
function totalSupply() external view returns (uint) {
return _totalSupply;
}
// Moves tokens `amount` from `sender` to `recipient`
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
// See {BEP20-balanceOf}
function balanceOf(address account) external view returns (uint) {
return _balances[account];
}
// See {BEP20-transfer}
// `recipient` cannot be the zero address
// the caller must have a balance of at least `amount`
function transfer(address recipient, uint amount) external whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
_transfer(_msgSender(), recipient, amount);
return true;
}
// See {BEP20-allowance}
function allowance(address owner, address spender) external view returns (uint) {
return _allowances[owner][spender];
}
// See {BEP20-approve}
// `spender` cannot be the zero address
function approve(address spender, uint amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
// See {BEP20-transferFrom}
// `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, uint amount) external returns (bool) {
require(!isBlackListed[sender]);
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance")
);
return true;
}
// Atomically increases the allowance granted to `spender` by the caller
// `spender` cannot be the zero address
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
// Automatically decreases the allowance granted to `spender` by the caller
// `spender` cannot be the zero address
// `spender` must have allowance for the caller of at least `subtractedValue`
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")
);
return true;
}
// Creates `amount` tokens and assigns them to `msg.sender`, increasing the total supply
// `msg.sender` must be the token owner
function mint(uint amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
// Creates `amount` tokens and assigns them to `account`, increasing
// `to` cannot be the zero address
function _mint(address account, uint amount) internal {
require(account != address(0), "BEP20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
// Destroy `amount` tokens from `msg.sender`, reducing
// `msg.sender` must be the token owner
function burn(uint amount) public onlyOwner returns (bool) {
_burn(_msgSender(), amount);
return true;
}
// Destroys `amount` tokens from `account`, reducing the total supply
// `account` cannot be the zero address
// `account` must have at least `amount` tokens
function _burn(address account, uint amount) internal {
require(account != address(0), "BEP20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "BEP20: 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
// `owner` cannot be the zero address.
// `spender` cannot be the zero address.
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | Returns the amount of tokens in existence Returns the token decimals Returns the token symbol Returns the token name Returns the token owner Returns the amount of tokens owned by `account` Moves `amount` tokens from the caller's account to `recipient` Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism Emitted when `value` tokens are moved from one account (`from`) to another (`to`) Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance | interface IBEP20 {
function totalSupply() external view returns (uint);
function decimals() external view returns (uint);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint amount) external returns (bool);
function allowance(address _owner, address spender) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
| 2,474,137 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
interface ISqwidMigrator {
function positionClosed(
uint256 positionId,
address receiver,
bool saleCreated
) external;
}
interface ISqwidERC1155 {
function mint(
address to,
uint256 amount,
string memory tokenURI,
string calldata mimeType_,
address royaltyRecipient,
uint256 royaltyValue
) external returns (uint256);
function mintBatch(
address to,
uint256[] memory amounts,
string[] memory tokenURIs,
string[] calldata mimeTypes,
address[] memory royaltyRecipients,
uint256[] memory royaltyValues
) external returns (uint256[] memory);
function burn(
address account,
uint256 id,
uint256 amount
) external;
function wrapERC721(
address extNftContract,
uint256 extTokenId,
string calldata mimeType_
) external returns (uint256);
function wrapERC1155(
address extNftContract,
uint256 extTokenId,
string calldata mimeType_,
uint256 amount
) external returns (uint256);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) external;
function balanceOf(address account, uint256 id) external view returns (uint256);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator) external view returns (bool);
function mimeType(uint256 tokenId) external view returns (string memory);
}
interface ISqwidMarketplace {
enum PositionState {
Available,
RegularSale,
Auction,
Raffle,
Loan
}
struct Item {
uint256 itemId;
address nftContract;
uint256 tokenId;
address creator;
uint256 positionCount;
ItemSale[] sales;
}
struct Position {
uint256 positionId;
uint256 itemId;
address payable owner;
uint256 amount;
uint256 price;
uint256 marketFee;
PositionState state;
}
struct ItemSale {
address seller;
address buyer;
uint256 price;
uint256 amount;
}
struct AuctionData {
uint256 deadline;
uint256 minBid;
address highestBidder;
uint256 highestBid;
mapping(address => uint256) addressToAmount;
mapping(uint256 => address) indexToAddress;
uint256 totalAddresses;
}
struct RaffleData {
uint256 deadline;
uint256 totalValue;
mapping(address => uint256) addressToAmount;
mapping(uint256 => address) indexToAddress;
uint256 totalAddresses;
}
struct LoanData {
uint256 loanAmount;
uint256 feeAmount;
uint256 numMinutes;
uint256 deadline;
address lender;
}
struct AuctionDataResponse {
uint256 deadline;
uint256 minBid;
address highestBidder;
uint256 highestBid;
uint256 totalAddresses;
}
struct RaffleDataResponse {
uint256 deadline;
uint256 totalValue;
uint256 totalAddresses;
}
function transferOwnership(address newOwner) external;
function setMarketFee(uint16 marketFee_, PositionState typeFee) external;
function setMimeTypeFee(uint256 mimeTypeFee_) external;
function setNftContractAddress(ISqwidERC1155 sqwidERC1155_) external;
function setMigratorAddress(ISqwidMigrator sqwidMigrator_) external;
function withdraw() external;
function currentItemId() external view returns (uint256);
function currentPositionId() external view returns (uint256);
function fetchItem(uint256 itemId) external view returns (Item memory);
function fetchPosition(uint256 positionId) external view returns (Position memory);
function fetchStateCount(PositionState state) external view returns (uint256);
function fetchAuctionData(uint256 positionId)
external
view
returns (AuctionDataResponse memory);
function fetchBid(uint256 positionId, uint256 bidIndex)
external
view
returns (address, uint256);
function fetchRaffleData(uint256 positionId) external view returns (RaffleDataResponse memory);
function fetchRaffleEntry(uint256 positionId, uint256 entryIndex)
external
view
returns (address, uint256);
function fetchLoanData(uint256 positionId) external view returns (LoanData memory);
}
contract SqwidMarketplaceUtil is Ownable {
struct ItemResponse {
uint256 itemId;
address nftContract;
uint256 tokenId;
address creator;
ISqwidMarketplace.ItemSale[] sales;
ISqwidMarketplace.Position[] positions;
}
struct PositionResponse {
uint256 positionId;
ISqwidMarketplace.Item item;
address payable owner;
uint256 amount;
uint256 price;
uint256 marketFee;
ISqwidMarketplace.PositionState state;
ISqwidMarketplace.AuctionDataResponse auctionData;
ISqwidMarketplace.RaffleDataResponse raffleData;
ISqwidMarketplace.LoanData loanData;
}
struct AuctionBidded {
PositionResponse auction;
uint256 bidAmount;
}
struct RaffleEntered {
PositionResponse raffle;
uint256 enteredAmount;
}
ISqwidMarketplace public marketplace;
modifier pagination(uint256 pageNumber, uint256 pageSize) {
require(pageNumber > 0, "SqwidMarketUtil: Page number cannot be 0");
require(pageSize <= 100 && pageSize > 0, "SqwidMarketUtil: Invalid page size");
_;
}
modifier idsSize(uint256 size) {
require(size <= 100 && size > 0, "SqwidMarketUtil: Invalid number of ids");
_;
}
constructor(ISqwidMarketplace marketplace_) {
marketplace = marketplace_;
}
/**
* Sets new market contract address.
*/
function setMarketContractAddress(ISqwidMarketplace marketplace_) external onlyOwner {
marketplace = marketplace_;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// ITEMS ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Returns item and all its item positions.
*/
function fetchItem(uint256 itemId) public view returns (ItemResponse memory) {
ISqwidMarketplace.Item memory item = marketplace.fetchItem(itemId);
require(item.itemId > 0, "SqwidMarketUtil: Item not found");
return
ItemResponse(
itemId,
item.nftContract,
item.tokenId,
item.creator,
item.sales,
_fetchPositionsByItemId(itemId)
);
}
/**
* Returns <limit> valid items for a given state starting at <startIndex> (where the itemIds
* are part of approvedIds)
*/
function fetchItems(
uint256 startIndex,
uint256 limit,
bytes memory approvedIds
) external view returns (ISqwidMarketplace.Item[] memory items) {
require(limit >= 1 && limit <= 100, "SqwidMarketUtil: Invalid limit");
uint256 totalItems = marketplace.currentItemId();
if (startIndex == 0) {
startIndex = totalItems;
}
require(
startIndex >= 1 && startIndex <= totalItems,
"SqwidMarketUtil: Invalid start index"
);
require(approvedIds.length > 0, "SqwidMarketUtil: Invalid approvedIds");
if (startIndex < limit) {
limit = startIndex;
}
items = new ISqwidMarketplace.Item[](limit);
uint256 count;
for (uint256 i = startIndex; i > 0; i--) {
if (_checkExistsBytes(i, approvedIds)) {
items[count] = marketplace.fetchItem(i);
count++;
if (count == limit) break;
}
}
}
/**
* Returns items paginated.
*/
function fetchItemsPage(uint256 pageSize, uint256 pageNumber)
external
view
pagination(pageSize, pageNumber)
returns (ISqwidMarketplace.Item[] memory items, uint256 totalPages)
{
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalItemCount = marketplace.currentItemId();
if (totalItemCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (items, 0);
}
if (startIndex > totalItemCount) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > totalItemCount) {
endIndex = totalItemCount;
}
// Fill array
items = new ISqwidMarketplace.Item[](endIndex - startIndex + 1);
uint256 count;
for (uint256 i = startIndex; i <= endIndex; i++) {
items[count] = marketplace.fetchItem(i);
count++;
}
// Set total number pages
totalPages = (totalItemCount + pageSize - 1) / pageSize;
}
/**
* Returns total number of items.
*/
function fetchNumberItems() public view returns (uint256) {
return marketplace.currentItemId();
}
/**
* Returns number of items created by an address.
*/
function fetchAddressNumberItemsCreated(address targetAddress) public view returns (uint256) {
uint256 createdItemCount = 0;
uint256 totalItemCount = marketplace.currentItemId();
for (uint256 i; i < totalItemCount; i++) {
if (marketplace.fetchItem(i + 1).creator == targetAddress) {
createdItemCount++;
}
}
return createdItemCount;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// POSITIONS ////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Returns item position.
*/
function fetchPosition(uint256 positionId) public view returns (PositionResponse memory) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(positionId);
require(position.positionId > 0, "SqwidMarketUtil: Position not found");
ISqwidMarketplace.AuctionDataResponse memory auctionData;
ISqwidMarketplace.RaffleDataResponse memory raffleData;
ISqwidMarketplace.LoanData memory loanData;
ISqwidMarketplace.Item memory item = marketplace.fetchItem(position.itemId);
uint256 amount = position.amount;
if (position.state == ISqwidMarketplace.PositionState.Available) {
amount = ISqwidERC1155(item.nftContract).balanceOf(position.owner, item.tokenId);
} else if (position.state == ISqwidMarketplace.PositionState.Auction) {
auctionData = marketplace.fetchAuctionData(positionId);
} else if (position.state == ISqwidMarketplace.PositionState.Raffle) {
raffleData = marketplace.fetchRaffleData(positionId);
} else if (position.state == ISqwidMarketplace.PositionState.Loan) {
loanData = marketplace.fetchLoanData(positionId);
}
return
PositionResponse(
positionId,
item,
position.owner,
amount,
position.price,
position.marketFee,
position.state,
auctionData,
raffleData,
loanData
);
}
/**
* Returns <limit> valid positions for a given state starting at <startIndex> (where the itemIds
* are part of approvedIds) of owner != address (0) it also filters by owner
*/
function fetchPositions(
ISqwidMarketplace.PositionState state,
address owner,
uint256 startIndex,
uint256 limit,
bytes memory approvedIds
) external view returns (PositionResponse[] memory positions) {
require(limit >= 1 && limit <= 100, "SqwidMarketUtil: Invalid limit");
uint256 totalPositions = marketplace.currentPositionId();
if (startIndex == 0) {
startIndex = totalPositions;
}
require(
startIndex >= 1 && startIndex <= totalPositions,
"SqwidMarketUtil: Invalid start index"
);
require(approvedIds.length > 0, "SqwidMarketUtil: Invalid approvedIds");
if (startIndex < limit) {
limit = startIndex;
}
positions = new PositionResponse[](limit);
uint256 count;
for (uint256 i = startIndex; i > 0; i--) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i);
if (
(owner != address(0) ? position.owner == owner : true) &&
position.state == state &&
position.amount > 0 &&
_checkExistsBytes(position.itemId, approvedIds)
) {
positions[count] = fetchPosition(i);
if (positions[count].amount > 0) {
count++;
if (count == limit) break;
} else {
delete positions[count];
}
}
}
}
/**
* Returns items positions from an address paginated.
*/
function fetchAddressPositionsPage(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
)
external
view
pagination(pageSize, pageNumber)
returns (PositionResponse[] memory positions, uint256 totalPages)
{
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressPositionCount;
uint256 firstMatch;
for (uint256 i; i < totalPositionCount; i++) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i + 1);
if (position.owner == targetAddress) {
addressPositionCount++;
if (addressPositionCount == startIndex) {
firstMatch = i + 1;
}
}
}
if (addressPositionCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (positions, 0);
}
if (startIndex > addressPositionCount) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > addressPositionCount) {
endIndex = addressPositionCount;
}
uint256 size = endIndex - startIndex + 1;
// Fill array
positions = new PositionResponse[](size);
uint256 count;
for (uint256 i = firstMatch; count < size; i++) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i);
if (position.owner == targetAddress) {
positions[count] = fetchPosition(i);
count++;
}
}
// Set total number of pages
totalPages = (addressPositionCount + pageSize - 1) / pageSize;
}
/**
* Returns item positions for a given state paginated.
*/
function fetchPositionsByStatePage(
ISqwidMarketplace.PositionState state,
uint256 pageSize,
uint256 pageNumber
)
external
view
pagination(pageSize, pageNumber)
returns (PositionResponse[] memory positions, uint256 totalPages)
{
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalStatePositions = marketplace.fetchStateCount(state);
if (totalStatePositions == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (positions, 0);
}
if (startIndex > totalStatePositions) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > totalStatePositions) {
endIndex = totalStatePositions;
}
uint256 size = endIndex - startIndex + 1;
// Fill array
positions = new PositionResponse[](size);
uint256 count;
uint256 statePositionCount;
for (uint256 i = 1; count < size; i++) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i);
if (position.positionId > 0 && position.state == state) {
statePositionCount++;
if (statePositionCount >= startIndex) {
positions[count] = fetchPosition(i);
count++;
}
}
}
// Set total number pages
totalPages = (totalStatePositions + pageSize - 1) / pageSize;
}
/**
* Returns number of items positions from an address.
*/
function fetchAddressNumberPositions(address targetAddress) external view returns (uint256) {
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 positionCount = 0;
for (uint256 i; i < totalPositionCount; i++) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i + 1);
if (position.owner == targetAddress) {
positionCount++;
}
}
return positionCount;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// AUCTIONS /////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Returns addresses and bids of an active auction.
*/
function fetchAuctionBids(uint256 positionId)
public
view
returns (address[] memory, uint256[] memory)
{
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(positionId);
require(
position.state == ISqwidMarketplace.PositionState.Auction,
"SqwidMarketUtil: Position on wrong state"
);
uint256 totalAddresses = marketplace.fetchAuctionData(positionId).totalAddresses;
// Initialize array
address[] memory addresses = new address[](totalAddresses);
uint256[] memory amounts = new uint256[](totalAddresses);
// Fill arrays
for (uint256 i; i < totalAddresses; i++) {
(address addr, uint256 amount) = marketplace.fetchBid(positionId, i);
addresses[i] = addr;
amounts[i] = amount;
}
return (addresses, amounts);
}
/**
* Returns bids by an address paginated.
*/
function fetchAddressBidsPage(
address targetAddress,
uint256 pageSize,
uint256 pageNumber,
bool newestToOldest
)
external
view
pagination(pageSize, pageNumber)
returns (AuctionBidded[] memory bids, uint256 totalPages)
{
if (newestToOldest) {
return _fetchAddressBidsReverse(targetAddress, pageSize, pageNumber);
} else {
return _fetchAddressBids(targetAddress, pageSize, pageNumber);
}
}
/**
* Returns number of bids by an address.
*/
function fetchAddressNumberBids(address targetAddress) external view returns (uint256) {
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressBidCount;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Auction) {
(address[] memory addresses, ) = fetchAuctionBids(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressBidCount++;
}
}
}
}
return addressBidCount;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// RAFFLES //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Returns addresses and amounts of an active raffle.
*/
function fetchRaffleEntries(uint256 positionId)
public
view
returns (address[] memory, uint256[] memory)
{
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(positionId);
require(
position.state == ISqwidMarketplace.PositionState.Raffle,
"SqwidMarketUtil: Position on wrong state"
);
uint256 totalAddresses = marketplace.fetchRaffleData(positionId).totalAddresses;
// Initialize array
address[] memory addresses = new address[](totalAddresses);
uint256[] memory amounts = new uint256[](totalAddresses);
// Fill arrays
for (uint256 i; i < totalAddresses; i++) {
(address addr, uint256 amount) = marketplace.fetchRaffleEntry(positionId, i);
addresses[i] = addr;
amounts[i] = amount;
}
return (addresses, amounts);
}
/**
* Returns active raffles entered by an address paginated.
*/
function fetchAddressRafflesPage(
address targetAddress,
uint256 pageSize,
uint256 pageNumber,
bool newestToOldest
)
external
view
pagination(pageSize, pageNumber)
returns (RaffleEntered[] memory raffles, uint256 totalPages)
{
if (newestToOldest) {
return _fetchAddressRafflesReverse(targetAddress, pageSize, pageNumber);
} else {
return _fetchAddressRaffles(targetAddress, pageSize, pageNumber);
}
}
/**
* Returns number active raffles entered by an address.
*/
function fetchAddressNumberRaffles(address targetAddress) external view returns (uint256) {
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressRaffleCount;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Raffle) {
(address[] memory addresses, ) = fetchRaffleEntries(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressRaffleCount++;
}
}
}
}
return addressRaffleCount;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// LOANS ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Returns active loans funded by an address paginated.
*/
function fetchAddressLoansPage(
address targetAddress,
uint256 pageSize,
uint256 pageNumber,
bool newestToOldest
)
external
view
pagination(pageSize, pageNumber)
returns (PositionResponse[] memory loans, uint256 totalPages)
{
if (newestToOldest) {
return _fetchAddressLoansReverse(targetAddress, pageSize, pageNumber);
} else {
return _fetchAddressLoans(targetAddress, pageSize, pageNumber);
}
}
/**
* Returns number active loans funded by an address paginated.
*/
function fetchAddressNumberLoans(address targetAddress) external view returns (uint256) {
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressLoanCount;
for (uint256 i; i < totalPositionCount; i++) {
if (
marketplace.fetchLoanData(i + 1).lender == targetAddress &&
marketplace.fetchPosition(i + 1).positionId > 0
) {
addressLoanCount++;
}
}
return addressLoanCount;
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////// PRIVATE //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
function _fetchPositionsByItemId(uint256 itemId)
private
view
returns (ISqwidMarketplace.Position[] memory)
{
// Initialize array
ISqwidMarketplace.Position[] memory items = new ISqwidMarketplace.Position[](
marketplace.fetchItem(itemId).positionCount
);
// Fill array
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 currentIndex = 0;
for (uint256 i; i < totalPositionCount; i++) {
ISqwidMarketplace.Position memory position = marketplace.fetchPosition(i + 1);
if (position.itemId == itemId) {
items[currentIndex] = position;
currentIndex++;
}
}
return items;
}
/**
* Returns bids by an address paginated (starting from first element).
*/
function _fetchAddressBids(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (AuctionBidded[] memory bids, uint256 totalPages) {
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressBidCount;
uint256 firstMatch;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Auction) {
(address[] memory addresses, ) = fetchAuctionBids(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressBidCount++;
if (addressBidCount == startIndex) {
firstMatch = i + 1;
}
break;
}
}
}
}
if (addressBidCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (bids, 0);
}
if (startIndex > addressBidCount) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > addressBidCount) {
endIndex = addressBidCount;
}
// Fill array
bids = new AuctionBidded[](endIndex - startIndex + 1);
uint256 count;
for (uint256 i = firstMatch; count < endIndex - startIndex + 1; i++) {
if (marketplace.fetchPosition(i).state == ISqwidMarketplace.PositionState.Auction) {
(address[] memory addresses, uint256[] memory amounts) = fetchAuctionBids(i);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
bids[count] = AuctionBidded(fetchPosition(i), amounts[j]);
count++;
break;
}
}
}
}
// Set total number of pages
totalPages = (addressBidCount + pageSize - 1) / pageSize;
}
/**
* Returns bids by an address paginated in reverse order
* (starting from last element).
*/
function _fetchAddressBidsReverse(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (AuctionBidded[] memory bids, uint256 totalPages) {
// Get start and end index
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressBidCount;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Auction) {
(address[] memory addresses, ) = fetchAuctionBids(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressBidCount++;
break;
}
}
}
}
if (addressBidCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (bids, 0);
}
if ((pageSize * (pageNumber - 1)) >= addressBidCount) {
revert("SqwidMarketUtil: Invalid page number");
}
uint256 startIndex = addressBidCount - (pageSize * (pageNumber - 1));
uint256 endIndex = 1;
if (startIndex > pageSize) {
endIndex = startIndex - pageSize + 1;
}
uint256 size = startIndex - endIndex + 1;
// Fill array
bids = new AuctionBidded[](size);
uint256 count;
uint256 addressBidIndex = addressBidCount + 1;
for (uint256 i = totalPositionCount; count < size; i--) {
if (marketplace.fetchPosition(i).state == ISqwidMarketplace.PositionState.Auction) {
(address[] memory addresses, uint256[] memory amounts) = fetchAuctionBids(i);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressBidIndex--;
if (addressBidIndex <= startIndex) {
bids[count] = AuctionBidded(fetchPosition(i), amounts[j]);
count++;
}
break;
}
}
}
}
// Set total number of pages
totalPages = (addressBidCount + pageSize - 1) / pageSize;
}
/**
* Returns active raffles entered by an address paginated (starting from first element).
*/
function _fetchAddressRaffles(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (RaffleEntered[] memory raffles, uint256 totalPages) {
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressRaffleCount;
uint256 firstMatch;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Raffle) {
(address[] memory addresses, ) = fetchRaffleEntries(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressRaffleCount++;
if (addressRaffleCount == startIndex) {
firstMatch = i + 1;
}
break;
}
}
}
}
if (addressRaffleCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (raffles, 0);
}
if (startIndex > addressRaffleCount) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > addressRaffleCount) {
endIndex = addressRaffleCount;
}
// Fill array
raffles = new RaffleEntered[](endIndex - startIndex + 1);
uint256 count;
for (uint256 i = firstMatch; count < endIndex - startIndex + 1; i++) {
if (marketplace.fetchPosition(i).state == ISqwidMarketplace.PositionState.Raffle) {
(address[] memory addresses, uint256[] memory amounts) = fetchRaffleEntries(i);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
raffles[count] = RaffleEntered(fetchPosition(i), amounts[j]);
count++;
break;
}
}
}
}
// Set total number of pages
totalPages = (addressRaffleCount + pageSize - 1) / pageSize;
}
/**
* Returns active raffles entered by an address paginated in reverse order
* (starting from last element).
*/
function _fetchAddressRafflesReverse(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (RaffleEntered[] memory raffles, uint256 totalPages) {
// Get start and end index
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressRaffleCount;
for (uint256 i; i < totalPositionCount; i++) {
if (marketplace.fetchPosition(i + 1).state == ISqwidMarketplace.PositionState.Raffle) {
(address[] memory addresses, ) = fetchRaffleEntries(i + 1);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressRaffleCount++;
break;
}
}
}
}
if (addressRaffleCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (raffles, 0);
}
if ((pageSize * (pageNumber - 1)) >= addressRaffleCount) {
revert("SqwidMarketUtil: Invalid page number");
}
uint256 startIndex = addressRaffleCount - (pageSize * (pageNumber - 1));
uint256 endIndex = 1;
if (startIndex > pageSize) {
endIndex = startIndex - pageSize + 1;
}
uint256 size = startIndex - endIndex + 1;
// Fill array
raffles = new RaffleEntered[](size);
uint256 count;
uint256 addressRaffleIndex = addressRaffleCount + 1;
for (uint256 i = totalPositionCount; count < size; i--) {
if (marketplace.fetchPosition(i).state == ISqwidMarketplace.PositionState.Raffle) {
(address[] memory addresses, uint256[] memory amounts) = fetchRaffleEntries(i);
for (uint256 j; j < addresses.length; j++) {
if (addresses[j] == targetAddress) {
addressRaffleIndex--;
if (addressRaffleIndex <= startIndex) {
raffles[count] = RaffleEntered(fetchPosition(i), amounts[j]);
count++;
}
break;
}
}
}
}
// Set total number of pages
totalPages = (addressRaffleCount + pageSize - 1) / pageSize;
}
/**
* Returns active loans funded by an address paginated (starting from first element).
*/
function _fetchAddressLoans(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (PositionResponse[] memory loans, uint256 totalPages) {
// Get start and end index
uint256 startIndex = pageSize * (pageNumber - 1) + 1;
uint256 endIndex = startIndex + pageSize - 1;
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressLoanCount;
uint256 firstMatch;
for (uint256 i; i < totalPositionCount; i++) {
if (
marketplace.fetchLoanData(i + 1).lender == targetAddress &&
marketplace.fetchPosition(i + 1).positionId > 0
) {
addressLoanCount++;
if (addressLoanCount == startIndex) {
firstMatch = i + 1;
}
}
}
if (addressLoanCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (loans, 0);
}
if (startIndex > addressLoanCount) {
revert("SqwidMarketUtil: Invalid page number");
}
if (endIndex > addressLoanCount) {
endIndex = addressLoanCount;
}
// Fill array
loans = new PositionResponse[](endIndex - startIndex + 1);
uint256 count;
for (uint256 i = firstMatch; count < endIndex - startIndex + 1; i++) {
if (
marketplace.fetchLoanData(i).lender == targetAddress &&
marketplace.fetchPosition(i).positionId > 0
) {
loans[count] = fetchPosition(i);
count++;
}
}
// Set total number of pages
totalPages = (addressLoanCount + pageSize - 1) / pageSize;
}
/**
* Returns active loans funded by an address paginated in reverse order
* (starting from last element).
*/
function _fetchAddressLoansReverse(
address targetAddress,
uint256 pageSize,
uint256 pageNumber
) private view returns (PositionResponse[] memory loans, uint256 totalPages) {
// Get start and end index
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressLoanCount;
for (uint256 i; i < totalPositionCount; i++) {
if (
marketplace.fetchLoanData(i + 1).lender == targetAddress &&
marketplace.fetchPosition(i + 1).positionId > 0
) {
addressLoanCount++;
}
}
if (addressLoanCount == 0) {
if (pageNumber > 1) {
revert("SqwidMarketUtil: Invalid page number");
}
return (loans, 0);
}
if ((pageSize * (pageNumber - 1)) >= addressLoanCount) {
revert("SqwidMarketUtil: Invalid page number");
}
uint256 startIndex = addressLoanCount - (pageSize * (pageNumber - 1));
uint256 endIndex = 1;
if (startIndex > pageSize) {
endIndex = startIndex - pageSize + 1;
}
uint256 size = startIndex - endIndex + 1;
// Fill array
loans = new PositionResponse[](size);
uint256 count;
uint256 addressLoanIndex = addressLoanCount + 1;
for (uint256 i = totalPositionCount; count < size; i--) {
if (
marketplace.fetchLoanData(i).lender == targetAddress &&
marketplace.fetchPosition(i).positionId > 0
) {
addressLoanIndex--;
if (addressLoanIndex <= startIndex) {
loans[count] = fetchPosition(i);
count++;
}
}
}
// Set total number of pages
totalPages = (addressLoanCount + pageSize - 1) / pageSize;
}
/**
* Returns whether a certain id is set to true (exists) by checking the byte
* byte of its corresponding position inside the packedBooleans variable.
*/
function _checkExistsBytes(uint256 _id, bytes memory _packedBooleans)
private
pure
returns (bool)
{
if (_id >= _packedBooleans.length * 8) {
return false;
}
uint8 b = uint8(_packedBooleans[_id / 8]);
uint8 mask = uint8((1 << (_id % 8)));
uint8 flag = b & mask;
return (flag != 0);
}
}
| Returns number active loans funded by an address paginated./ | function fetchAddressNumberLoans(address targetAddress) external view returns (uint256) {
uint256 totalPositionCount = marketplace.currentPositionId();
uint256 addressLoanCount;
for (uint256 i; i < totalPositionCount; i++) {
if (
marketplace.fetchLoanData(i + 1).lender == targetAddress &&
marketplace.fetchPosition(i + 1).positionId > 0
) {
addressLoanCount++;
}
}
return addressLoanCount;
}
| 978,970 |
/*
* Copyright ©️ 2018 Galt•Space Society Construction and Terraforming Company
* (Founded by [Nikolai Popeka](https://github.com/npopeka),
* [Dima Starodubcev](https://github.com/xhipster),
* [Valery Litvin](https://github.com/litvintech) by
* [Basic Agreement](http://cyb.ai/QmSAWEG5u5aSsUyMNYuX2A2Eaz4kEuoYWUkVBRdmu9qmct:ipfs)).
*
* Copyright ©️ 2018 Galt•Core Blockchain Company
* (Founded by [Nikolai Popeka](https://github.com/npopeka) and
* Galt•Space Society Construction and Terraforming Company by
* [Basic Agreement](http://cyb.ai/QmaCiXUmSrP16Gz8Jdzq6AJESY1EAANmmwha15uR3c1bsS:ipfs)).
*/
pragma solidity 0.5.10;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "@galtproject/libs/contracts/collections/ArraySet.sol";
import "../pgg/PGGOracleStakeAccounting.sol";
import "../pgg/PGGMultiSig.sol";
import "../registries/PGGRegistry.sol";
import "./AbstractApplication.sol";
contract ArbitratorProposableApplication is AbstractApplication {
using SafeMath for uint256;
using ArraySet for ArraySet.AddressSet;
event NewApplication(address indexed applicant, bytes32 applicationId);
event NewProposal(address indexed arbitrator, bytes32 indexed applicationId, Action action, bytes32 proposalId);
event ApplicationStatusChanged(bytes32 indexed applicationId, ApplicationStatus indexed status);
event ArbitratorSlotTaken(bytes32 indexed applicationId, uint256 slotsTaken, uint256 totalSlots);
event ArbitratorRewardApplication(bytes32 indexed applicationId, address indexed oracle);
event GaltProtocolFeeAssigned(bytes32 indexed applicationId);
enum ApplicationStatus {
NOT_EXISTS,
SUBMITTED,
APPROVED,
REJECTED,
REVERTED
}
enum Action {
APPROVE,
REJECT
}
struct Application {
bytes32 id;
address payable pgg;
address applicant;
bytes32 chosenProposal;
uint256 createdAt;
uint256 m;
uint256 n;
ApplicationStatus status;
FeeDetails fees;
mapping(bytes32 => Proposal) proposals;
mapping(address => bytes32) votes;
bytes32[] proposalList;
ArraySet.AddressSet arbitrators;
}
struct FeeDetails {
Currency currency;
uint256 arbitratorsReward;
uint256 arbitratorReward;
uint256 galtProtocolFee;
bool galtProtocolFeePaidOut;
mapping(address => bool) arbitratorRewardPaidOut;
}
struct Proposal {
Action action;
ArraySet.AddressSet votesFor;
address from;
string message;
}
mapping(bytes32 => Application) internal applications;
mapping(address => bytes32[]) internal applicationByArbitrator;
constructor () public {}
function initialize(
GaltGlobalRegistry _ggr
)
public
isInitializer
{
ggr = _ggr;
}
function _execute(bytes32 _cId, bytes32 _pId) internal {
revert("#_execute() not implemented");
}
function _checkRewardCanBeClaimed(bytes32 _cId) internal returns (bool) {
revert("#_checkRewardCanBeClaimed() not implemented");
}
function minimalApplicationFeeEth(address _pgg) internal view returns (uint256) {
revert("#minimalApplicationFeeEth() not implemented");
}
function minimalApplicationFeeGalt(address _pgg) internal view returns (uint256) {
revert("#minimalApplicationFeeGalt() not implemented");
}
// arbitrators count required
function m(address _pgg) public view returns (uint256) {
revert("#m() not implemented");
}
// total arbitrators count able to lock the claim
function n(address _pgg) public view returns (uint256) {
revert("#n() not implemented");
}
function paymentMethod(address _pgg) public view returns (PaymentMethod);
/**
* @dev Submit a new claim.
*
* @param _pgg to submit a claim
* @param _applicationFeeInGalt or 0 for ETH payment method
* @return new claim id
*/
function _submit(
address payable _pgg,
uint256 _applicationFeeInGalt
)
internal
returns (bytes32)
{
pggRegistry().requireValidPgg(_pgg);
// Default is ETH
Currency currency;
uint256 fee;
// ETH
if (msg.value > 0) {
requireValidPaymentType(_pgg, PaymentType.ETH);
require(_applicationFeeInGalt == 0, "Could not accept both ETH and GALT");
require(msg.value >= minimalApplicationFeeEth(_pgg), "Incorrect fee passed in");
fee = msg.value;
// GALT
} else {
requireValidPaymentType(_pgg, PaymentType.GALT);
require(msg.value == 0, "Could not accept both ETH and GALT");
require(_applicationFeeInGalt >= minimalApplicationFeeGalt(_pgg), "Incorrect fee passed in");
ggr.getGaltToken().transferFrom(msg.sender, address(this), _applicationFeeInGalt);
fee = _applicationFeeInGalt;
currency = Currency.GALT;
}
bytes32 id = keccak256(
abi.encodePacked(
msg.sender,
blockhash(block.number - 1),
applicationsArray.length
)
);
Application storage c = applications[id];
require(applications[id].status == ApplicationStatus.NOT_EXISTS, "Application already exists");
c.status = ApplicationStatus.SUBMITTED;
c.id = id;
c.pgg = _pgg;
c.applicant = msg.sender;
c.fees.currency = currency;
c.n = n(_pgg);
c.m = m(_pgg);
c.createdAt = block.timestamp;
calculateAndStoreFee(c, fee);
applicationsArray.push(id);
applicationsByApplicant[msg.sender].push(id);
emit NewApplication(msg.sender, id);
emit ApplicationStatusChanged(id, ApplicationStatus.SUBMITTED);
return id;
}
/**
* @dev Arbitrator locks a claim to work on
* @param _cId Application ID
*/
function lock(bytes32 _cId) external {
Application storage c = applications[_cId];
require(pggConfig(c.pgg).getMultiSig().isOwner(msg.sender), "Invalid arbitrator");
require(c.status == ApplicationStatus.SUBMITTED, "SUBMITTED claim status required");
require(!c.arbitrators.has(msg.sender), "Arbitrator has already locked the application");
require(c.arbitrators.size() < n(c.pgg), "All arbitrator slots are locked");
c.arbitrators.add(msg.sender);
emit ArbitratorSlotTaken(_cId, c.arbitrators.size(), n(c.pgg));
}
/**
* @dev Arbitrator makes approve proposal
* @param _cId Application ID
*/
function _proposeApproval(bytes32 _cId, string memory _msg) internal returns (bytes32 pId) {
Application storage c = applications[_cId];
require(c.status == ApplicationStatus.SUBMITTED, "SUBMITTED claim status required");
require(c.arbitrators.has(msg.sender) == true, "Arbitrator not in locked list");
pId = keccak256(abi.encode(_cId, block.number, msg.sender));
Proposal storage p = c.proposals[pId];
require(p.from == address(0), "Proposal already exists");
// arbitrator immediately votes for the proposal
// as we have minimum n equal 2, a brand new proposal could not be executed in this step
_voteFor(c, pId);
p.from = msg.sender;
p.action = Action.APPROVE;
p.message = _msg;
c.proposalList.push(pId);
emit NewProposal(msg.sender, _cId, Action.APPROVE, pId);
}
/**
* @dev Arbitrator makes reject proposal
* @param _cId Application ID
*/
function proposeReject(bytes32 _cId, string calldata _msg) external {
Application storage c = applications[_cId];
require(c.status == ApplicationStatus.SUBMITTED, "SUBMITTED claim status required");
require(c.arbitrators.has(msg.sender) == true, "Arbitrator not in locked list");
bytes32 pId = keccak256(abi.encode(_cId, _msg, msg.sender));
Proposal storage p = c.proposals[pId];
require(p.from == address(0), "Proposal already exists");
c.proposalList.push(pId);
// arbitrator immediately votes for the proposal
_voteFor(c, pId);
// as we have minimum n equal 2, a brand new proposal could not be executed in this step
p.from = msg.sender;
p.message = _msg;
p.action = Action.REJECT;
emit NewProposal(msg.sender, _cId, Action.REJECT, pId);
}
/**
* @dev Arbitrator votes for a proposal
* @param _cId Application ID
* @param _pId Proposal ID
*/
function vote(bytes32 _cId, bytes32 _pId) external {
Application storage c = applications[_cId];
require(c.status == ApplicationStatus.SUBMITTED, "SUBMITTED claim status required");
require(c.arbitrators.has(msg.sender) == true, "Arbitrator not in locked list");
Proposal storage p = c.proposals[_pId];
require(p.from != address(0), "Proposal doesn't exists");
_voteFor(c, _pId);
if (p.votesFor.size() == c.m) {
c.chosenProposal = _pId;
calculateAndStoreAuditorRewards(c);
if (p.action == Action.APPROVE) {
changeApplicationStatus(c, ApplicationStatus.APPROVED);
_execute(_cId, _pId);
} else {
changeApplicationStatus(c, ApplicationStatus.REJECTED);
}
}
}
function claimArbitratorReward(bytes32 _cId) external {
Application storage c = applications[_cId];
require(
c.status == ApplicationStatus.APPROVED || c.status == ApplicationStatus.REJECTED,
"Application status should be APPROVED or REJECTED");
require(c.arbitrators.has(msg.sender) == true, "Arbitrator not in locked list");
require(c.fees.arbitratorRewardPaidOut[msg.sender] == false, "Reward already paid out");
if (c.status == ApplicationStatus.APPROVED) {
require(_checkRewardCanBeClaimed(_cId), "Transaction hasn't executed by multiSig yet");
}
c.fees.arbitratorRewardPaidOut[msg.sender] = true;
_assignGaltProtocolFee(c);
if (c.fees.currency == Currency.ETH) {
msg.sender.transfer(c.fees.arbitratorReward);
} else if (c.fees.currency == Currency.GALT) {
ggr.getGaltToken().transfer(msg.sender, c.fees.arbitratorReward);
}
emit ArbitratorRewardApplication(_cId, msg.sender);
}
function verifyOraclesAreValid(bytes32 _cId, address[] memory _oracles, bytes32[] memory _oracleTypes) internal {
Application storage c = applications[_cId];
require(
pggConfig(c.pgg)
.getOracles()
.oraclesHasTypesAssigned(_oracles, _oracleTypes),
"Some oracle types are invalid"
);
}
function _assignGaltProtocolFee(Application storage _a) internal {
if (_a.fees.galtProtocolFeePaidOut == false) {
if (_a.fees.currency == Currency.ETH) {
protocolFeesEth = protocolFeesEth.add(_a.fees.galtProtocolFee);
} else if (_a.fees.currency == Currency.GALT) {
protocolFeesGalt = protocolFeesGalt.add(_a.fees.galtProtocolFee);
}
_a.fees.galtProtocolFeePaidOut = true;
emit GaltProtocolFeeAssigned(_a.id);
}
}
function _voteFor(Application storage _c, bytes32 _pId) internal {
Proposal storage _p = _c.proposals[_pId];
if (_c.votes[msg.sender] != 0x0) {
_c.proposals[_c.votes[msg.sender]].votesFor.remove(msg.sender);
}
_c.votes[msg.sender] = _pId;
_p.votesFor.add(msg.sender);
}
function calculateAndStoreFee(
Application storage _c,
uint256 _fee
)
internal
{
uint256 share;
(uint256 ethFee, uint256 galtFee) = getProtocolShares();
if (_c.fees.currency == Currency.ETH) {
share = ethFee;
} else {
share = galtFee;
}
require(share > 0 && share <= 100, "Fee not properly set up");
uint256 galtProtocolFee = share.mul(_fee).div(100);
uint256 arbitratorsReward = _fee.sub(galtProtocolFee);
assert(arbitratorsReward.add(galtProtocolFee) == _fee);
_c.fees.arbitratorsReward = arbitratorsReward;
_c.fees.galtProtocolFee = galtProtocolFee;
}
// NOTICE: in case 100 ether / 3, each arbitrator will receive 33.33... ether and 1 wei will remain on contract
function calculateAndStoreAuditorRewards (Application storage c) internal {
uint256 len = c.arbitrators.size();
uint256 rewardSize = c.fees.arbitratorsReward.div(len);
c.fees.arbitratorReward = rewardSize;
}
function changeApplicationStatus(
Application storage _claim,
ApplicationStatus _status
)
internal
{
emit ApplicationStatusChanged(_claim.id, _status);
_claim.status = _status;
}
/** GETTERS **/
function getApplication(
bytes32 _cId
)
external
view
returns (
address applicant,
address pgg,
address[] memory arbitrators,
uint256 slotsTaken,
uint256 slotsThreshold,
uint256 totalSlots,
uint256 createdAt,
ApplicationStatus status
)
{
Application storage c = applications[_cId];
return (
c.applicant,
c.pgg,
c.arbitrators.elements(),
c.arbitrators.size(),
c.m,
c.n,
c.createdAt,
c.status
);
}
function getApplicationRewards(
bytes32 _cId
)
external
view
returns (
Currency currency,
uint256 arbitratorsReward,
uint256 galtProtocolFee,
uint256 arbitratorReward
)
{
FeeDetails storage f = applications[_cId].fees;
return (
f.currency,
f.arbitratorsReward,
f.galtProtocolFee,
f.arbitratorReward
);
}
function getProposalList(bytes32 _cId) external view returns (bytes32[] memory) {
return applications[_cId].proposalList;
}
/*
* @dev Get Proposal ID the arbitrator voted for
* @param _cId Application ID
* @param _v arbitrator address
*/
function getVotedFor(bytes32 _cId, address _v) external view returns (bytes32) {
return applications[_cId].votes[_v];
}
function getProposal(
bytes32 _cId,
bytes32 _pId
)
external
view
returns (
Action action,
address from,
string memory message
)
{
Proposal storage p = applications[_cId].proposals[_pId];
return (
p.action,
p.from,
p.message
);
}
function getProposalVotes(
bytes32 _cId,
bytes32 _pId
)
external
view
returns (
uint256 votesSize,
address[] memory votesFor
)
{
Proposal storage p = applications[_cId].proposals[_pId];
return (
p.votesFor.size(),
p.votesFor.elements()
);
}
}
| arbitrators count required | function m(address _pgg) public view returns (uint256) {
revert("#m() not implemented");
}
| 13,110,890 |
/**
*Submitted for verification at Etherscan.io on 2021-08-01
*/
// SPDX-License-Identifier: MIT
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
Copyright (c) 2020 Ditto Money
Copyright (c) 2021 Goes Up Higher
Copyright (c) 2021 Cryptographic Ultra Money
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity >=0.5.17 <0.8.0;
// SPDX-License-Identifier: MIT
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// SPDX-License-Identifier: MIT
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
/**
* @title Various utilities useful for uint256.
*/
library UInt256Lib {
uint256 private constant MAX_INT256 = ~(uint256(1) << 255);
/**
* @dev Safely converts a uint256 to an int256.
*/
function toInt256Safe(uint256 a)
internal
pure
returns (int256)
{
require(a <= MAX_INT256);
return int256(a);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event 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;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @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;
}
}
interface IOracle {
function getData() external view returns (uint256);
function update() external;
}
interface ICum {
function totalSupply() external view returns (uint256);
function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256);
}
/**
* @title Cum's Master
* @dev Controller for an elastic supply currency based on the uFragments Ideal Money protocol a.k.a. Ampleforth.
* uFragments operates symmetrically on expansion and contraction. It will both split and
* combine coins to maintain a stable unit price.
*
* This component regulates the token supply of the uFragments ERC20 token in response to
* market oracles.
*/
contract Master is Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
struct Transaction {
bool enabled;
address destination;
bytes data;
}
event TransactionFailed(address indexed destination, uint index, bytes data);
// Stable ordering is not guaranteed.
Transaction[] public transactions;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
ICum public cum;
// Market oracle provides the CUM/USD exchange rate as an 18 decimal fixed point number.
IOracle public marketOracle;
// If the current exchange rate is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the rate.
// (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change.
// DECIMALS Fixed point number.
uint256 public deviationThreshold;
// More than this much time must pass between rebase operations.
uint256 public rebaseCooldown;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
// The number of rebase cycles since inception
uint256 public epoch;
uint256 private constant DECIMALS = 18;
// Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256.
// Both are 18 decimals fixed point numbers.
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
// MAX_SUPPLY = MAX_INT256 / MAX_RATE
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
// Rebase will remain restricted to the owner until the final Oracle is deployed and battle-tested.
// Ownership will be renounced after this inital period.
// Start at $.000001
uint256 public targetRate;
bool public rebaseLocked;
constructor(address _cum) public {
deviationThreshold = 5 * 10 ** (DECIMALS-2);
// Start at .000001 cents
targetRate = (1 * 10 ** (DECIMALS-6));
rebaseCooldown = 24 hours;
lastRebaseTimestampSec = 1627848000;
epoch = 0;
rebaseLocked = true;
cum = ICum(_cum);
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Override to ensure that rebases aren't locked when this happens.
*/
function renounceOwnership() public onlyOwner {
require(!rebaseLocked, "Cannot renounce ownership if rebase is locked");
super.renounceOwnership();
}
function setRebaseLocked(bool _locked) external onlyOwner {
rebaseLocked = _locked;
}
/**
* @notice Returns true if the cooldown timer has expired since the last rebase.
*
*/
function canRebase() public view returns (bool) {
return ((!rebaseLocked || isOwner()) && lastRebaseTimestampSec.add(rebaseCooldown) < now);
}
function cooldownExpiryTimestamp() public view returns (uint256) {
return lastRebaseTimestampSec.add(rebaseCooldown);
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
*/
function rebase() external {
require(tx.origin == msg.sender);
require(canRebase(), "Rebase not allowed");
lastRebaseTimestampSec = now;
epoch = epoch.add(1);
(uint256 exchangeRate, int256 supplyDelta) = getRebaseValues();
uint256 supplyAfterRebase = cum.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
for (uint i = 0; i < transactions.length; i++) {
Transaction storage t = transactions[i];
if (t.enabled) {
bool result =
externalCall(t.destination, t.data);
if (!result) {
emit TransactionFailed(t.destination, i, t.data);
revert("Transaction Failed");
}
}
}
marketOracle.update();
if (epoch < 80) {
incrementTargetRate();
} else {
finalRate();
}
emit LogRebase(epoch, exchangeRate, supplyDelta, now);
}
// Increment by 42%
function incrementTargetRate() internal {
targetRate = targetRate.mul(71).div(50);
}
// Final rate of $1,000,000 per coin
function finalRate() internal {
targetRate = (1 * 10 ** (DECIMALS+6));
}
/**
* @notice Calculates the supplyDelta and returns the current set of values for the rebase
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
*
*/
function getRebaseValues() public view returns (uint256, int256) {
uint256 exchangeRate = marketOracle.getData();
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(exchangeRate);
// Apply the dampening factor.
if (supplyDelta < 0) {
supplyDelta = supplyDelta.div(2);
} else {
supplyDelta = supplyDelta.div(5);
}
if (supplyDelta > 0 && cum.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(cum.totalSupply())).toInt256Safe();
}
return (exchangeRate, supplyDelta);
}
/**
* @return Computes the total supply adjustment in response to the exchange rate
* and the targetRate.
*/
function computeSupplyDelta(uint256 rate)
internal
view
returns (int256)
{
if (withinDeviationThreshold(rate)) {
return 0;
}
int256 targetRateSigned = targetRate.toInt256Safe();
return cum.totalSupply().toInt256Safe()
.mul(rate.toInt256Safe().sub(targetRateSigned))
.div(targetRateSigned);
}
/**
* @param rate The current exchange rate, an 18 decimal fixed point number.
* @return If the rate is within the deviation threshold from the target rate, returns true.
* Otherwise, returns false.
*/
function withinDeviationThreshold(uint256 rate)
internal
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
.div(10 ** DECIMALS);
return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
|| (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
/**
* @notice Sets the reference to the market oracle.
* @param marketOracle_ The address of the market oracle contract.
*/
function setMarketOracle(IOracle marketOracle_)
external
onlyOwner
{
marketOracle = marketOracle_;
}
/**
* @notice Adds a transaction that gets called for a downstream receiver of rebases
* @param destination Address of contract destination
* @param data Transaction data payload
*/
function addTransaction(address destination, bytes calldata data)
external
onlyOwner
{
transactions.push(Transaction({
enabled: true,
destination: destination,
data: data
}));
}
/**
* @param index Index of transaction to remove.
* Transaction ordering may have changed since adding.
*/
function removeTransaction(uint index)
external
onlyOwner
{
require(index < transactions.length, "index out of bounds");
if (index < transactions.length - 1) {
transactions[index] = transactions[transactions.length - 1];
}
transactions.length--;
}
/**
* @param index Index of transaction. Transaction ordering may have changed since adding.
* @param enabled True for enabled, false for disabled.
*/
function setTransactionEnabled(uint index, bool enabled)
external
onlyOwner
{
require(index < transactions.length, "index must be in range of stored tx list");
transactions[index].enabled = enabled;
}
/**
* @return Number of transactions, both enabled and disabled, in transactions list.
*/
function transactionsSize()
external
view
returns (uint256)
{
return transactions.length;
}
/**
* @dev wrapper to call the encoded transactions on downstream consumers.
* @param destination Address of destination contract.
* @param data The encoded data payload.
* @return True on success
*/
function externalCall(address destination, bytes memory data)
internal
returns (bool)
{
bool result;
assembly { // solhint-disable-line no-inline-assembly
// "Allocate" memory for output
// (0x40 is where "free memory" pointer is stored by convention)
let outputAddress := mload(0x40)
// First 32 bytes are the padded length of data, so exclude that
let dataAddress := add(data, 32)
result := call(
sub(gas(), 34710),
destination,
0, // transfer value in wei
dataAddress,
mload(data), // Size of the input, in bytes. Stored in position 0 of the array.
outputAddress,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
} | return Computes the total supply adjustment in response to the exchange rate and the targetRate./ | function computeSupplyDelta(uint256 rate)
internal
view
returns (int256)
{
if (withinDeviationThreshold(rate)) {
return 0;
}
int256 targetRateSigned = targetRate.toInt256Safe();
return cum.totalSupply().toInt256Safe()
.mul(rate.toInt256Safe().sub(targetRateSigned))
.div(targetRateSigned);
}
| 6,754,696 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {FeeSharingSetter} from "./FeeSharingSetter.sol";
import {TokenSplitter} from "./TokenSplitter.sol";
/**
* @title OperatorControllerForRewards
* @notice It splits pending LOOKS and updates trading rewards.
*/
contract OperatorControllerForRewards is Ownable {
TokenSplitter public immutable tokenSplitter;
FeeSharingSetter public immutable feeSharingSetter;
address public immutable teamVesting;
address public immutable treasuryVesting;
address public immutable tradingRewardsDistributor;
/**
* @notice Constructor
* @param _feeSharingSetter address of the fee sharing setter contract
* @param _tokenSplitter address of the token splitter contract
* @param _teamVesting address of the team vesting contract
* @param _treasuryVesting address of the treasury vesting contract
* @param _tradingRewardsDistributor address of the trading rewards distributor contract
*/
constructor(
address _feeSharingSetter,
address _tokenSplitter,
address _teamVesting,
address _treasuryVesting,
address _tradingRewardsDistributor
) {
feeSharingSetter = FeeSharingSetter(_feeSharingSetter);
tokenSplitter = TokenSplitter(_tokenSplitter);
teamVesting = _teamVesting;
treasuryVesting = _treasuryVesting;
tradingRewardsDistributor = _tradingRewardsDistributor;
}
/**
* @notice Release LOOKS tokens from the TokenSplitter and update fee-sharing rewards
*/
function releaseTokensAndUpdateRewards() external onlyOwner {
try tokenSplitter.releaseTokens(teamVesting) {} catch {}
try tokenSplitter.releaseTokens(treasuryVesting) {} catch {}
try tokenSplitter.releaseTokens(tradingRewardsDistributor) {} catch {}
feeSharingSetter.updateRewards();
}
}
// 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
pragma solidity ^0.8.0;
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {FeeSharingSystem} from "./FeeSharingSystem.sol";
import {TokenDistributor} from "./TokenDistributor.sol";
import {IRewardConvertor} from "../interfaces/IRewardConvertor.sol";
/**
* @title FeeSharingSetter
* @notice It receives LooksRare protocol fees and owns the FeeSharingSystem contract.
* It can plug to AMMs for converting all received currencies to WETH.
*/
contract FeeSharingSetter is ReentrancyGuard, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
// Operator role
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
// Min duration for each fee-sharing period (in blocks)
uint256 public immutable MIN_REWARD_DURATION_IN_BLOCKS;
// Max duration for each fee-sharing period (in blocks)
uint256 public immutable MAX_REWARD_DURATION_IN_BLOCKS;
IERC20 public immutable looksRareToken;
IERC20 public immutable rewardToken;
FeeSharingSystem public feeSharingSystem;
TokenDistributor public immutable tokenDistributor;
// Reward convertor (tool to convert other currencies to rewardToken)
IRewardConvertor public rewardConvertor;
// Last reward block of distribution
uint256 public lastRewardDistributionBlock;
// Next reward duration in blocks
uint256 public nextRewardDurationInBlocks;
// Reward duration in blocks
uint256 public rewardDurationInBlocks;
// Set of addresses that are staking only the fee sharing
EnumerableSet.AddressSet private _feeStakingAddresses;
event ConversionToRewardToken(address indexed token, uint256 amountConverted, uint256 amountReceived);
event FeeStakingAddressesAdded(address[] feeStakingAddresses);
event FeeStakingAddressesRemoved(address[] feeStakingAddresses);
event NewFeeSharingSystemOwner(address newOwner);
event NewRewardDurationInBlocks(uint256 rewardDurationInBlocks);
event NewRewardConvertor(address rewardConvertor);
/**
* @notice Constructor
* @param _feeSharingSystem address of the fee sharing system
* @param _minRewardDurationInBlocks minimum reward duration in blocks
* @param _maxRewardDurationInBlocks maximum reward duration in blocks
* @param _rewardDurationInBlocks reward duration between two updates in blocks
*/
constructor(
address _feeSharingSystem,
uint256 _minRewardDurationInBlocks,
uint256 _maxRewardDurationInBlocks,
uint256 _rewardDurationInBlocks
) {
require(
(_rewardDurationInBlocks <= _maxRewardDurationInBlocks) &&
(_rewardDurationInBlocks >= _minRewardDurationInBlocks),
"Owner: Reward duration in blocks outside of range"
);
MIN_REWARD_DURATION_IN_BLOCKS = _minRewardDurationInBlocks;
MAX_REWARD_DURATION_IN_BLOCKS = _maxRewardDurationInBlocks;
feeSharingSystem = FeeSharingSystem(_feeSharingSystem);
rewardToken = feeSharingSystem.rewardToken();
looksRareToken = feeSharingSystem.looksRareToken();
tokenDistributor = feeSharingSystem.tokenDistributor();
rewardDurationInBlocks = _rewardDurationInBlocks;
nextRewardDurationInBlocks = _rewardDurationInBlocks;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
* @notice Update the reward per block (in rewardToken)
* @dev It automatically retrieves the number of pending WETH and adjusts
* based on the balance of LOOKS in fee-staking addresses that exist in the set.
*/
function updateRewards() external onlyRole(OPERATOR_ROLE) {
if (lastRewardDistributionBlock > 0) {
require(block.number > (rewardDurationInBlocks + lastRewardDistributionBlock), "Reward: Too early to add");
}
// Adjust for this period
if (rewardDurationInBlocks != nextRewardDurationInBlocks) {
rewardDurationInBlocks = nextRewardDurationInBlocks;
}
lastRewardDistributionBlock = block.number;
// Calculate the reward to distribute as the balance held by this address
uint256 reward = rewardToken.balanceOf(address(this));
require(reward != 0, "Reward: Nothing to distribute");
// Check if there is any address eligible for fee-sharing only
uint256 numberAddressesForFeeStaking = _feeStakingAddresses.length();
// If there are eligible addresses for fee-sharing only, calculate their shares
if (numberAddressesForFeeStaking > 0) {
uint256[] memory looksBalances = new uint256[](numberAddressesForFeeStaking);
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(feeSharingSystem));
for (uint256 i = 0; i < numberAddressesForFeeStaking; i++) {
uint256 looksBalance = looksRareToken.balanceOf(_feeStakingAddresses.at(i));
totalAmountStaked += looksBalance;
looksBalances[i] = looksBalance;
}
// Only apply the logic if the totalAmountStaked > 0 (to prevent division by 0)
if (totalAmountStaked > 0) {
uint256 adjustedReward = reward;
for (uint256 i = 0; i < numberAddressesForFeeStaking; i++) {
uint256 amountToTransfer = (looksBalances[i] * reward) / totalAmountStaked;
if (amountToTransfer > 0) {
adjustedReward -= amountToTransfer;
rewardToken.safeTransfer(_feeStakingAddresses.at(i), amountToTransfer);
}
}
// Adjust reward accordingly
reward = adjustedReward;
}
}
// Transfer tokens to fee sharing system
rewardToken.safeTransfer(address(feeSharingSystem), reward);
// Update rewards
feeSharingSystem.updateRewards(reward, rewardDurationInBlocks);
}
/**
* @notice Convert currencies to reward token
* @dev Function only usable only for whitelisted currencies (where no potential side effect)
* @param token address of the token to sell
* @param additionalData additional data (e.g., slippage)
*/
function convertCurrencyToRewardToken(address token, bytes calldata additionalData)
external
nonReentrant
onlyRole(OPERATOR_ROLE)
{
require(address(rewardConvertor) != address(0), "Convert: RewardConvertor not set");
require(token != address(rewardToken), "Convert: Cannot be reward token");
uint256 amountToConvert = IERC20(token).balanceOf(address(this));
require(amountToConvert != 0, "Convert: Amount to convert must be > 0");
// Adjust allowance for this transaction only
IERC20(token).safeIncreaseAllowance(address(rewardConvertor), amountToConvert);
// Exchange token to reward token
uint256 amountReceived = rewardConvertor.convert(token, address(rewardToken), amountToConvert, additionalData);
emit ConversionToRewardToken(token, amountToConvert, amountReceived);
}
/**
* @notice Add staking addresses
* @param _stakingAddresses array of addresses eligible for fee-sharing only
*/
function addFeeStakingAddresses(address[] calldata _stakingAddresses) external onlyRole(DEFAULT_ADMIN_ROLE) {
for (uint256 i = 0; i < _stakingAddresses.length; i++) {
require(!_feeStakingAddresses.contains(_stakingAddresses[i]), "Owner: Address already registered");
_feeStakingAddresses.add(_stakingAddresses[i]);
}
emit FeeStakingAddressesAdded(_stakingAddresses);
}
/**
* @notice Remove staking addresses
* @param _stakingAddresses array of addresses eligible for fee-sharing only
*/
function removeFeeStakingAddresses(address[] calldata _stakingAddresses) external onlyRole(DEFAULT_ADMIN_ROLE) {
for (uint256 i = 0; i < _stakingAddresses.length; i++) {
require(_feeStakingAddresses.contains(_stakingAddresses[i]), "Owner: Address not registered");
_feeStakingAddresses.remove(_stakingAddresses[i]);
}
emit FeeStakingAddressesRemoved(_stakingAddresses);
}
/**
* @notice Set new reward duration in blocks for next update
* @param _newRewardDurationInBlocks number of blocks for new reward period
*/
function setNewRewardDurationInBlocks(uint256 _newRewardDurationInBlocks) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(
(_newRewardDurationInBlocks <= MAX_REWARD_DURATION_IN_BLOCKS) &&
(_newRewardDurationInBlocks >= MIN_REWARD_DURATION_IN_BLOCKS),
"Owner: New reward duration in blocks outside of range"
);
nextRewardDurationInBlocks = _newRewardDurationInBlocks;
emit NewRewardDurationInBlocks(_newRewardDurationInBlocks);
}
/**
* @notice Set reward convertor contract
* @param _rewardConvertor address of the reward convertor (set to null to deactivate)
*/
function setRewardConvertor(address _rewardConvertor) external onlyRole(DEFAULT_ADMIN_ROLE) {
rewardConvertor = IRewardConvertor(_rewardConvertor);
emit NewRewardConvertor(_rewardConvertor);
}
/**
* @notice Transfer ownership of fee sharing system
* @param _newOwner address of the new owner
*/
function transferOwnershipOfFeeSharingSystem(address _newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_newOwner != address(0), "Owner: New owner cannot be null address");
feeSharingSystem.transferOwnership(_newOwner);
emit NewFeeSharingSystemOwner(_newOwner);
}
/**
* @notice See addresses eligible for fee-staking
*/
function viewFeeStakingAddresses() external view returns (address[] memory) {
uint256 length = _feeStakingAddresses.length();
address[] memory feeStakingAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
feeStakingAddresses[i] = _feeStakingAddresses.at(i);
}
return (feeStakingAddresses);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title TokenSplitter
* @notice It splits LOOKS to team/treasury/trading volume reward accounts based on shares.
*/
contract TokenSplitter is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
struct AccountInfo {
uint256 shares;
uint256 tokensDistributedToAccount;
}
uint256 public immutable TOTAL_SHARES;
IERC20 public immutable looksRareToken;
// Total LOOKS tokens distributed across all accounts
uint256 public totalTokensDistributed;
mapping(address => AccountInfo) public accountInfo;
event NewSharesOwner(address indexed oldRecipient, address indexed newRecipient);
event TokensTransferred(address indexed account, uint256 amount);
/**
* @notice Constructor
* @param _accounts array of accounts addresses
* @param _shares array of shares per account
* @param _looksRareToken address of the LOOKS token
*/
constructor(
address[] memory _accounts,
uint256[] memory _shares,
address _looksRareToken
) {
require(_accounts.length == _shares.length, "Splitter: Length differ");
require(_accounts.length > 0, "Splitter: Length must be > 0");
uint256 currentShares;
for (uint256 i = 0; i < _accounts.length; i++) {
require(_shares[i] > 0, "Splitter: Shares are 0");
currentShares += _shares[i];
accountInfo[_accounts[i]].shares = _shares[i];
}
TOTAL_SHARES = currentShares;
looksRareToken = IERC20(_looksRareToken);
}
/**
* @notice Release LOOKS tokens to the account
* @param account address of the account
*/
function releaseTokens(address account) external nonReentrant {
require(accountInfo[account].shares > 0, "Splitter: Account has no share");
// Calculate amount to transfer to the account
uint256 totalTokensReceived = looksRareToken.balanceOf(address(this)) + totalTokensDistributed;
uint256 pendingRewards = ((totalTokensReceived * accountInfo[account].shares) / TOTAL_SHARES) -
accountInfo[account].tokensDistributedToAccount;
// Revert if equal to 0
require(pendingRewards != 0, "Splitter: Nothing to transfer");
accountInfo[account].tokensDistributedToAccount += pendingRewards;
totalTokensDistributed += pendingRewards;
// Transfer funds to account
looksRareToken.safeTransfer(account, pendingRewards);
emit TokensTransferred(account, pendingRewards);
}
/**
* @notice Update share recipient
* @param _newRecipient address of the new recipient
* @param _currentRecipient address of the current recipient
*/
function updateSharesOwner(address _newRecipient, address _currentRecipient) external onlyOwner {
require(accountInfo[_currentRecipient].shares > 0, "Owner: Current recipient has no shares");
require(accountInfo[_newRecipient].shares == 0, "Owner: New recipient has existing shares");
// Copy shares to new recipient
accountInfo[_newRecipient].shares = accountInfo[_currentRecipient].shares;
accountInfo[_newRecipient].tokensDistributedToAccount = accountInfo[_currentRecipient]
.tokensDistributedToAccount;
// Reset existing shares
accountInfo[_currentRecipient].shares = 0;
accountInfo[_currentRecipient].tokensDistributedToAccount = 0;
emit NewSharesOwner(_currentRecipient, _newRecipient);
}
/**
* @notice Retrieve amount of LOOKS tokens that can be transferred
* @param account address of the account
*/
function calculatePendingRewards(address account) external view returns (uint256) {
if (accountInfo[account].shares == 0) {
return 0;
}
uint256 totalTokensReceived = looksRareToken.balanceOf(address(this)) + totalTokensDistributed;
uint256 pendingRewards = ((totalTokensReceived * accountInfo[account].shares) / TOTAL_SHARES) -
accountInfo[account].tokensDistributedToAccount;
return pendingRewards;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view 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 revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/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/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {TokenDistributor} from "./TokenDistributor.sol";
/**
* @title FeeSharingSystem
* @notice It handles the distribution of fees using
* WETH along with the auto-compounding of LOOKS.
*/
contract FeeSharingSystem is ReentrancyGuard, Ownable {
using SafeERC20 for IERC20;
struct UserInfo {
uint256 shares; // shares of token staked
uint256 userRewardPerTokenPaid; // user reward per token paid
uint256 rewards; // pending rewards
}
// Precision factor for calculating rewards and exchange rate
uint256 public constant PRECISION_FACTOR = 10**18;
IERC20 public immutable looksRareToken;
IERC20 public immutable rewardToken;
TokenDistributor public immutable tokenDistributor;
// Reward rate (block)
uint256 public currentRewardPerBlock;
// Last reward adjustment block number
uint256 public lastRewardAdjustment;
// Last update block for rewards
uint256 public lastUpdateBlock;
// Current end block for the current reward period
uint256 public periodEndBlock;
// Reward per token stored
uint256 public rewardPerTokenStored;
// Total existing shares
uint256 public totalShares;
mapping(address => UserInfo) public userInfo;
event Deposit(address indexed user, uint256 amount, uint256 harvestedAmount);
event Harvest(address indexed user, uint256 harvestedAmount);
event NewRewardPeriod(uint256 numberBlocks, uint256 rewardPerBlock, uint256 reward);
event Withdraw(address indexed user, uint256 amount, uint256 harvestedAmount);
/**
* @notice Constructor
* @param _looksRareToken address of the token staked (LOOKS)
* @param _rewardToken address of the reward token
* @param _tokenDistributor address of the token distributor contract
*/
constructor(
address _looksRareToken,
address _rewardToken,
address _tokenDistributor
) {
rewardToken = IERC20(_rewardToken);
looksRareToken = IERC20(_looksRareToken);
tokenDistributor = TokenDistributor(_tokenDistributor);
}
/**
* @notice Deposit staked tokens (and collect reward tokens if requested)
* @param amount amount to deposit (in LOOKS)
* @param claimRewardToken whether to claim reward tokens
* @dev There is a limit of 1 LOOKS per deposit to prevent potential manipulation of current shares
*/
function deposit(uint256 amount, bool claimRewardToken) external nonReentrant {
require(amount >= PRECISION_FACTOR, "Deposit: Amount must be >= 1 LOOKS");
// Auto compounds for everyone
tokenDistributor.harvestAndCompound();
// Update reward for user
_updateReward(msg.sender);
// Retrieve total amount staked by this contract
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this));
// Transfer LOOKS tokens to this address
looksRareToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 currentShares;
// Calculate the number of shares to issue for the user
if (totalShares != 0) {
currentShares = (amount * totalShares) / totalAmountStaked;
// This is a sanity check to prevent deposit for 0 shares
require(currentShares != 0, "Deposit: Fail");
} else {
currentShares = amount;
}
// Adjust internal shares
userInfo[msg.sender].shares += currentShares;
totalShares += currentShares;
uint256 pendingRewards;
if (claimRewardToken) {
// Fetch pending rewards
pendingRewards = userInfo[msg.sender].rewards;
if (pendingRewards > 0) {
userInfo[msg.sender].rewards = 0;
rewardToken.safeTransfer(msg.sender, pendingRewards);
}
}
// Verify LOOKS token allowance and adjust if necessary
_checkAndAdjustLOOKSTokenAllowanceIfRequired(amount, address(tokenDistributor));
// Deposit user amount in the token distributor contract
tokenDistributor.deposit(amount);
emit Deposit(msg.sender, amount, pendingRewards);
}
/**
* @notice Harvest reward tokens that are pending
*/
function harvest() external nonReentrant {
// Auto compounds for everyone
tokenDistributor.harvestAndCompound();
// Update reward for user
_updateReward(msg.sender);
// Retrieve pending rewards
uint256 pendingRewards = userInfo[msg.sender].rewards;
// If pending rewards are null, revert
require(pendingRewards > 0, "Harvest: Pending rewards must be > 0");
// Adjust user rewards and transfer
userInfo[msg.sender].rewards = 0;
// Transfer reward token to sender
rewardToken.safeTransfer(msg.sender, pendingRewards);
emit Harvest(msg.sender, pendingRewards);
}
/**
* @notice Withdraw staked tokens (and collect reward tokens if requested)
* @param shares shares to withdraw
* @param claimRewardToken whether to claim reward tokens
*/
function withdraw(uint256 shares, bool claimRewardToken) external nonReentrant {
require(
(shares > 0) && (shares <= userInfo[msg.sender].shares),
"Withdraw: Shares equal to 0 or larger than user shares"
);
_withdraw(shares, claimRewardToken);
}
/**
* @notice Withdraw all staked tokens (and collect reward tokens if requested)
* @param claimRewardToken whether to claim reward tokens
*/
function withdrawAll(bool claimRewardToken) external nonReentrant {
_withdraw(userInfo[msg.sender].shares, claimRewardToken);
}
/**
* @notice Update the reward per block (in rewardToken)
* @dev Only callable by owner. Owner is meant to be another smart contract.
*/
function updateRewards(uint256 reward, uint256 rewardDurationInBlocks) external onlyOwner {
// Adjust the current reward per block
if (block.number >= periodEndBlock) {
currentRewardPerBlock = reward / rewardDurationInBlocks;
} else {
currentRewardPerBlock =
(reward + ((periodEndBlock - block.number) * currentRewardPerBlock)) /
rewardDurationInBlocks;
}
lastUpdateBlock = block.number;
periodEndBlock = block.number + rewardDurationInBlocks;
emit NewRewardPeriod(rewardDurationInBlocks, currentRewardPerBlock, reward);
}
/**
* @notice Calculate pending rewards (WETH) for a user
* @param user address of the user
*/
function calculatePendingRewards(address user) external view returns (uint256) {
return _calculatePendingRewards(user);
}
/**
* @notice Calculate value of LOOKS for a user given a number of shares owned
* @param user address of the user
*/
function calculateSharesValueInLOOKS(address user) external view returns (uint256) {
// Retrieve amount staked
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this));
// Adjust for pending rewards
totalAmountStaked += tokenDistributor.calculatePendingRewards(address(this));
// Return user pro-rata of total shares
return userInfo[user].shares == 0 ? 0 : (totalAmountStaked * userInfo[user].shares) / totalShares;
}
/**
* @notice Calculate price of one share (in LOOKS token)
* Share price is expressed times 1e18
*/
function calculateSharePriceInLOOKS() external view returns (uint256) {
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this));
// Adjust for pending rewards
totalAmountStaked += tokenDistributor.calculatePendingRewards(address(this));
return totalShares == 0 ? PRECISION_FACTOR : (totalAmountStaked * PRECISION_FACTOR) / (totalShares);
}
/**
* @notice Return last block where trading rewards were distributed
*/
function lastRewardBlock() external view returns (uint256) {
return _lastRewardBlock();
}
/**
* @notice Calculate pending rewards for a user
* @param user address of the user
*/
function _calculatePendingRewards(address user) internal view returns (uint256) {
return
((userInfo[user].shares * (_rewardPerToken() - (userInfo[user].userRewardPerTokenPaid))) /
PRECISION_FACTOR) + userInfo[user].rewards;
}
/**
* @notice Check current allowance and adjust if necessary
* @param _amount amount to transfer
* @param _to token to transfer
*/
function _checkAndAdjustLOOKSTokenAllowanceIfRequired(uint256 _amount, address _to) internal {
if (looksRareToken.allowance(address(this), _to) < _amount) {
looksRareToken.approve(_to, type(uint256).max);
}
}
/**
* @notice Return last block where rewards must be distributed
*/
function _lastRewardBlock() internal view returns (uint256) {
return block.number < periodEndBlock ? block.number : periodEndBlock;
}
/**
* @notice Return reward per token
*/
function _rewardPerToken() internal view returns (uint256) {
if (totalShares == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored +
((_lastRewardBlock() - lastUpdateBlock) * (currentRewardPerBlock * PRECISION_FACTOR)) /
totalShares;
}
/**
* @notice Update reward for a user account
* @param _user address of the user
*/
function _updateReward(address _user) internal {
if (block.number != lastUpdateBlock) {
rewardPerTokenStored = _rewardPerToken();
lastUpdateBlock = _lastRewardBlock();
}
userInfo[_user].rewards = _calculatePendingRewards(_user);
userInfo[_user].userRewardPerTokenPaid = rewardPerTokenStored;
}
/**
* @notice Withdraw staked tokens (and collect reward tokens if requested)
* @param shares shares to withdraw
* @param claimRewardToken whether to claim reward tokens
*/
function _withdraw(uint256 shares, bool claimRewardToken) internal {
// Auto compounds for everyone
tokenDistributor.harvestAndCompound();
// Update reward for user
_updateReward(msg.sender);
// Retrieve total amount staked and calculated current amount (in LOOKS)
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this));
uint256 currentAmount = (totalAmountStaked * shares) / totalShares;
userInfo[msg.sender].shares -= shares;
totalShares -= shares;
// Withdraw amount equivalent in shares
tokenDistributor.withdraw(currentAmount);
uint256 pendingRewards;
if (claimRewardToken) {
// Fetch pending rewards
pendingRewards = userInfo[msg.sender].rewards;
if (pendingRewards > 0) {
userInfo[msg.sender].rewards = 0;
rewardToken.safeTransfer(msg.sender, pendingRewards);
}
}
// Transfer LOOKS tokens to sender
looksRareToken.safeTransfer(msg.sender, currentAmount);
emit Withdraw(msg.sender, currentAmount, pendingRewards);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ILooksRareToken} from "../interfaces/ILooksRareToken.sol";
/**
* @title TokenDistributor
* @notice It handles the distribution of LOOKS token.
* It auto-adjusts block rewards over a set number of periods.
*/
contract TokenDistributor is ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeERC20 for ILooksRareToken;
struct StakingPeriod {
uint256 rewardPerBlockForStaking;
uint256 rewardPerBlockForOthers;
uint256 periodLengthInBlock;
}
struct UserInfo {
uint256 amount; // Amount of staked tokens provided by user
uint256 rewardDebt; // Reward debt
}
// Precision factor for calculating rewards
uint256 public constant PRECISION_FACTOR = 10**12;
ILooksRareToken public immutable looksRareToken;
address public immutable tokenSplitter;
// Number of reward periods
uint256 public immutable NUMBER_PERIODS;
// Block number when rewards start
uint256 public immutable START_BLOCK;
// Accumulated tokens per share
uint256 public accTokenPerShare;
// Current phase for rewards
uint256 public currentPhase;
// Block number when rewards end
uint256 public endBlock;
// Block number of the last update
uint256 public lastRewardBlock;
// Tokens distributed per block for other purposes (team + treasury + trading rewards)
uint256 public rewardPerBlockForOthers;
// Tokens distributed per block for staking
uint256 public rewardPerBlockForStaking;
// Total amount staked
uint256 public totalAmountStaked;
mapping(uint256 => StakingPeriod) public stakingPeriod;
mapping(address => UserInfo) public userInfo;
event Compound(address indexed user, uint256 harvestedAmount);
event Deposit(address indexed user, uint256 amount, uint256 harvestedAmount);
event NewRewardsPerBlock(
uint256 indexed currentPhase,
uint256 startBlock,
uint256 rewardPerBlockForStaking,
uint256 rewardPerBlockForOthers
);
event Withdraw(address indexed user, uint256 amount, uint256 harvestedAmount);
/**
* @notice Constructor
* @param _looksRareToken LOOKS token address
* @param _tokenSplitter token splitter contract address (for team and trading rewards)
* @param _startBlock start block for reward program
* @param _rewardsPerBlockForStaking array of rewards per block for staking
* @param _rewardsPerBlockForOthers array of rewards per block for other purposes (team + treasury + trading rewards)
* @param _periodLengthesInBlocks array of period lengthes
* @param _numberPeriods number of periods with different rewards/lengthes (e.g., if 3 changes --> 4 periods)
*/
constructor(
address _looksRareToken,
address _tokenSplitter,
uint256 _startBlock,
uint256[] memory _rewardsPerBlockForStaking,
uint256[] memory _rewardsPerBlockForOthers,
uint256[] memory _periodLengthesInBlocks,
uint256 _numberPeriods
) {
require(
(_periodLengthesInBlocks.length == _numberPeriods) &&
(_rewardsPerBlockForStaking.length == _numberPeriods) &&
(_rewardsPerBlockForStaking.length == _numberPeriods),
"Distributor: Lengthes must match numberPeriods"
);
// 1. Operational checks for supply
uint256 nonCirculatingSupply = ILooksRareToken(_looksRareToken).SUPPLY_CAP() -
ILooksRareToken(_looksRareToken).totalSupply();
uint256 amountTokensToBeMinted;
for (uint256 i = 0; i < _numberPeriods; i++) {
amountTokensToBeMinted +=
(_rewardsPerBlockForStaking[i] * _periodLengthesInBlocks[i]) +
(_rewardsPerBlockForOthers[i] * _periodLengthesInBlocks[i]);
stakingPeriod[i] = StakingPeriod({
rewardPerBlockForStaking: _rewardsPerBlockForStaking[i],
rewardPerBlockForOthers: _rewardsPerBlockForOthers[i],
periodLengthInBlock: _periodLengthesInBlocks[i]
});
}
require(amountTokensToBeMinted == nonCirculatingSupply, "Distributor: Wrong reward parameters");
// 2. Store values
looksRareToken = ILooksRareToken(_looksRareToken);
tokenSplitter = _tokenSplitter;
rewardPerBlockForStaking = _rewardsPerBlockForStaking[0];
rewardPerBlockForOthers = _rewardsPerBlockForOthers[0];
START_BLOCK = _startBlock;
endBlock = _startBlock + _periodLengthesInBlocks[0];
NUMBER_PERIODS = _numberPeriods;
// Set the lastRewardBlock as the startBlock
lastRewardBlock = _startBlock;
}
/**
* @notice Deposit staked tokens and compounds pending rewards
* @param amount amount to deposit (in LOOKS)
*/
function deposit(uint256 amount) external nonReentrant {
require(amount > 0, "Deposit: Amount must be > 0");
// Update pool information
_updatePool();
// Transfer LOOKS tokens to this contract
looksRareToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 pendingRewards;
// If not new deposit, calculate pending rewards (for auto-compounding)
if (userInfo[msg.sender].amount > 0) {
pendingRewards =
((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) -
userInfo[msg.sender].rewardDebt;
}
// Adjust user information
userInfo[msg.sender].amount += (amount + pendingRewards);
userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR;
// Increase totalAmountStaked
totalAmountStaked += (amount + pendingRewards);
emit Deposit(msg.sender, amount, pendingRewards);
}
/**
* @notice Compound based on pending rewards
*/
function harvestAndCompound() external nonReentrant {
// Update pool information
_updatePool();
// Calculate pending rewards
uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) -
userInfo[msg.sender].rewardDebt;
// Return if no pending rewards
if (pendingRewards == 0) {
// It doesn't throw revertion (to help with the fee-sharing auto-compounding contract)
return;
}
// Adjust user amount for pending rewards
userInfo[msg.sender].amount += pendingRewards;
// Adjust totalAmountStaked
totalAmountStaked += pendingRewards;
// Recalculate reward debt based on new user amount
userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR;
emit Compound(msg.sender, pendingRewards);
}
/**
* @notice Update pool rewards
*/
function updatePool() external nonReentrant {
_updatePool();
}
/**
* @notice Withdraw staked tokens and compound pending rewards
* @param amount amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(
(userInfo[msg.sender].amount >= amount) && (amount > 0),
"Withdraw: Amount must be > 0 or lower than user balance"
);
// Update pool
_updatePool();
// Calculate pending rewards
uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) -
userInfo[msg.sender].rewardDebt;
// Adjust user information
userInfo[msg.sender].amount = userInfo[msg.sender].amount + pendingRewards - amount;
userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR;
// Adjust total amount staked
totalAmountStaked = totalAmountStaked + pendingRewards - amount;
// Transfer LOOKS tokens to the sender
looksRareToken.safeTransfer(msg.sender, amount);
emit Withdraw(msg.sender, amount, pendingRewards);
}
/**
* @notice Withdraw all staked tokens and collect tokens
*/
function withdrawAll() external nonReentrant {
require(userInfo[msg.sender].amount > 0, "Withdraw: Amount must be > 0");
// Update pool
_updatePool();
// Calculate pending rewards and amount to transfer (to the sender)
uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) -
userInfo[msg.sender].rewardDebt;
uint256 amountToTransfer = userInfo[msg.sender].amount + pendingRewards;
// Adjust total amount staked
totalAmountStaked = totalAmountStaked - userInfo[msg.sender].amount;
// Adjust user information
userInfo[msg.sender].amount = 0;
userInfo[msg.sender].rewardDebt = 0;
// Transfer LOOKS tokens to the sender
looksRareToken.safeTransfer(msg.sender, amountToTransfer);
emit Withdraw(msg.sender, amountToTransfer, pendingRewards);
}
/**
* @notice Calculate pending rewards for a user
* @param user address of the user
* @return Pending rewards
*/
function calculatePendingRewards(address user) external view returns (uint256) {
if ((block.number > lastRewardBlock) && (totalAmountStaked != 0)) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking;
uint256 adjustedEndBlock = endBlock;
uint256 adjustedCurrentPhase = currentPhase;
// Check whether to adjust multipliers and reward per block
while ((block.number > adjustedEndBlock) && (adjustedCurrentPhase < (NUMBER_PERIODS - 1))) {
// Update current phase
adjustedCurrentPhase++;
// Update rewards per block
uint256 adjustedRewardPerBlockForStaking = stakingPeriod[adjustedCurrentPhase].rewardPerBlockForStaking;
// Calculate adjusted block number
uint256 previousEndBlock = adjustedEndBlock;
// Update end block
adjustedEndBlock = previousEndBlock + stakingPeriod[adjustedCurrentPhase].periodLengthInBlock;
// Calculate new multiplier
uint256 newMultiplier = (block.number <= adjustedEndBlock)
? (block.number - previousEndBlock)
: stakingPeriod[adjustedCurrentPhase].periodLengthInBlock;
// Adjust token rewards for staking
tokenRewardForStaking += (newMultiplier * adjustedRewardPerBlockForStaking);
}
uint256 adjustedTokenPerShare = accTokenPerShare +
(tokenRewardForStaking * PRECISION_FACTOR) /
totalAmountStaked;
return (userInfo[user].amount * adjustedTokenPerShare) / PRECISION_FACTOR - userInfo[user].rewardDebt;
} else {
return (userInfo[user].amount * accTokenPerShare) / PRECISION_FACTOR - userInfo[user].rewardDebt;
}
}
/**
* @notice Update reward variables of the pool
*/
function _updatePool() internal {
if (block.number <= lastRewardBlock) {
return;
}
if (totalAmountStaked == 0) {
lastRewardBlock = block.number;
return;
}
// Calculate multiplier
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
// Calculate rewards for staking and others
uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking;
uint256 tokenRewardForOthers = multiplier * rewardPerBlockForOthers;
// Check whether to adjust multipliers and reward per block
while ((block.number > endBlock) && (currentPhase < (NUMBER_PERIODS - 1))) {
// Update rewards per block
_updateRewardsPerBlock(endBlock);
uint256 previousEndBlock = endBlock;
// Adjust the end block
endBlock += stakingPeriod[currentPhase].periodLengthInBlock;
// Adjust multiplier to cover the missing periods with other lower inflation schedule
uint256 newMultiplier = _getMultiplier(previousEndBlock, block.number);
// Adjust token rewards
tokenRewardForStaking += (newMultiplier * rewardPerBlockForStaking);
tokenRewardForOthers += (newMultiplier * rewardPerBlockForOthers);
}
// Mint tokens only if token rewards for staking are not null
if (tokenRewardForStaking > 0) {
// It allows protection against potential issues to prevent funds from being locked
bool mintStatus = looksRareToken.mint(address(this), tokenRewardForStaking);
if (mintStatus) {
accTokenPerShare = accTokenPerShare + ((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked);
}
looksRareToken.mint(tokenSplitter, tokenRewardForOthers);
}
// Update last reward block only if it wasn't updated after or at the end block
if (lastRewardBlock <= endBlock) {
lastRewardBlock = block.number;
}
}
/**
* @notice Update rewards per block
* @dev Rewards are halved by 2 (for staking + others)
*/
function _updateRewardsPerBlock(uint256 _newStartBlock) internal {
// Update current phase
currentPhase++;
// Update rewards per block
rewardPerBlockForStaking = stakingPeriod[currentPhase].rewardPerBlockForStaking;
rewardPerBlockForOthers = stakingPeriod[currentPhase].rewardPerBlockForOthers;
emit NewRewardsPerBlock(currentPhase, _newStartBlock, rewardPerBlockForStaking, rewardPerBlockForOthers);
}
/**
* @notice Return reward multiplier over the given "from" to "to" block.
* @param from block to start calculating reward
* @param to block to finish calculating reward
* @return the multiplier for the period
*/
function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) {
if (to <= endBlock) {
return to - from;
} else if (from >= endBlock) {
return 0;
} else {
return endBlock - from;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IRewardConvertor {
function convert(
address tokenToSell,
address tokenToBuy,
uint256 amount,
bytes calldata additionalData
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ILooksRareToken is IERC20 {
function SUPPLY_CAP() external view returns (uint256);
function mint(address account, uint256 amount) external returns (bool);
} | Add staking addresses _stakingAddresses array of addresses eligible for fee-sharing only/ | function addFeeStakingAddresses(address[] calldata _stakingAddresses) external onlyRole(DEFAULT_ADMIN_ROLE) {
for (uint256 i = 0; i < _stakingAddresses.length; i++) {
require(!_feeStakingAddresses.contains(_stakingAddresses[i]), "Owner: Address already registered");
_feeStakingAddresses.add(_stakingAddresses[i]);
}
emit FeeStakingAddressesAdded(_stakingAddresses);
}
| 514,861 |
./full_match/3/0x7295C2BE0Fabca03ED3514C3dd99658EbC25f3f3/sources/browser/Contract_Code_v2_Min.sol | Calculate the bonus (Elite) Start Step0-1/Step 1 Start TempVariable_Elite[0] = 1;task StepCalculate limitcountBonus_Elite Start TempVariable_Elite[0] = 2;task Stepinit task progressinitStep 1 end | function countBonus_EliteStart()
external
isHuman()
onlyIfWhitelisted
{
require(paramsMapping[10] >= paramsMapping[10002], "Jackpot Not Satisfied");
require(TempVariable_Elite[0] == 0, "Calculate Not End");
TempVariable_Elite[1000] = paramsMapping[10];
TempVariable_Elite[1] = 1;
TempVariable_Elite[2] = _getCurrentUserID();
TempVariable_Elite[101] = 0;
TempVariable_Elite[102] = 0;
TempVariable_Elite[103] = 0;
TempVariable_Elite[104] = 0;
}
| 8,114,425 |
./partial_match/97/0x75CB9B883958a2BC04d3a6bC9a5069048d1Ef87F/sources/MasterChef.sol | allow admin update, no risk of rug pull | function updateMultiplier(uint256 multiplierNumber) public {
require(msg.sender == governance || msg.sender == owner(), "governance-only");
BONUS_MULTIPLIER = multiplierNumber;
}
| 11,371,332 |
./full_match/5/0x06775aB363873FcCf9f4E5Bb15f6216235Adb10F/sources/_openzeppelin/contracts-upgradeable/utils/CheckpointsUpgradeable.sol | Returns the number of checkpoint./ | function length(History storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
| 1,855,185 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
// Creator: Chiru Labs
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @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;
}
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
/**
* @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 `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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);
}
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.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);
}
// OpenZeppelin Contracts (last updated v4.5.0) (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
* ====
*
* [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);
}
}
}
}
// OpenZeppelin Contracts v4.4.1 (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) {
return msg.data;
}
}
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @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);
}
}
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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;
}
}
/**
* @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 - 1 (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;
// 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;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; 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);
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
unchecked {
for (uint256 curr = tokenId; curr >= 0; 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 virtual override {
_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 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 Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
require(quantity != 0, "ERC721A: quantity must be greater than 0");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
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.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = 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].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = 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 {}
}
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* 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);
}
}
// OpenZeppelin Contracts v4.4.1 (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 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;
}
}
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
/// @title Hot Dougs
contract HotDougs is Ownable, ReentrancyGuard, ERC721A("Hot Dougs", "DOUGS") {
using Strings for uint256;
using MerkleProof for bytes32[];
/// @notice Max total supply.
uint256 public dougsMax = 6969;
/// @notice Max transaction amount.
uint256 public constant dougsPerTx = 10;
/// @notice Max Dougs per wallet in pre-sale
uint256 public constant dougsMintPerWalletPresale = 3;
/// @notice Total Dougs available in pre-sale
uint256 public constant maxPreSaleDougs = 3000;
/// @notice Dougs price.
uint256 public constant dougsPrice = 0.05 ether;
/// @notice 0 = closed, 1 = pre-sale, 2 = public
uint256 public saleState;
/// @notice Metadata baseURI.
string public baseURI;
/// @notice Metadata unrevealed uri.
string public unrevealedURI;
/// @notice Metadata baseURI extension.
string public baseExtension;
/// @notice OpenSea proxy registry.
address public opensea = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
/// @notice LooksRare marketplace transfer manager.
address public looksrare = 0xf42aa99F011A1fA7CDA90E5E98b277E306BcA83e;
/// @notice Check if marketplaces pre-approve is enabled.
bool public marketplacesApproved = true;
/// @notice Free mint merkle root.
bytes32 public freeMintRoot;
/// @notice Pre-sale merkle root.
bytes32 public preMintRoot;
/// @notice Amount minted by address on free mint.
mapping(address => uint256) public freeMintCount;
/// @notice Amount minted by address on pre access.
mapping(address => uint256) public preMintCount;
/// @notice Authorized callers mapping.
mapping(address => bool) public auth;
modifier canMintDougs(uint256 numberOfTokens) {
require(
totalSupply() + numberOfTokens <= dougsMax,
"Not enough Dougs remaining to mint"
);
_;
}
modifier preSaleActive() {
require(saleState == 1, "Pre sale is not open");
_;
}
modifier publicSaleActive() {
require(saleState == 2, "Public sale is not open");
_;
}
modifier isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root) {
require(
MerkleProof.verify(
merkleProof,
root,
keccak256(abi.encodePacked(msg.sender))
),
"Address does not exist in list"
);
_;
}
modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) {
require(
price * numberOfTokens == msg.value,
"Incorrect ETH value sent"
);
_;
}
modifier maxDougsPerTransaction(uint256 numberOfTokens) {
require(
numberOfTokens <= dougsPerTx,
"Max Dougs to mint per transaction is 10"
);
_;
}
constructor(string memory newUnrevealedURI) {
unrevealedURI = newUnrevealedURI;
}
/// @notice Mint one free token and up to 3 pre-sale tokens.
function mintFree(uint256 numberOfTokens, bytes32[] calldata merkleProof)
external
payable
nonReentrant
preSaleActive
isCorrectPayment(dougsPrice, numberOfTokens - 1)
isValidMerkleProof(merkleProof, freeMintRoot)
{
if (msg.sender != owner()) {
require(
freeMintCount[msg.sender] == 0,
"User already minted a free token"
);
uint256 numAlreadyMinted = preMintCount[msg.sender];
require(
numAlreadyMinted + numberOfTokens - 1 <=
dougsMintPerWalletPresale,
"Max Dougs to mint in pre-sale is three"
);
require(
totalSupply() + numberOfTokens <= maxPreSaleDougs,
"Not enough Dougs remaining in pre-sale"
);
preMintCount[msg.sender] = numAlreadyMinted + numberOfTokens;
freeMintCount[msg.sender]++;
}
_safeMint(msg.sender, numberOfTokens);
}
/// @notice Mint one or more tokens for address on pre-sale list.
function mintPreDoug(uint256 numberOfTokens, bytes32[] calldata merkleProof)
external
payable
nonReentrant
preSaleActive
isCorrectPayment(dougsPrice, numberOfTokens)
isValidMerkleProof(merkleProof, preMintRoot)
{
uint256 numAlreadyMinted = preMintCount[msg.sender];
require(
numAlreadyMinted + numberOfTokens <= dougsMintPerWalletPresale,
"Max Dougs to mint in pre-sale is three"
);
require(
totalSupply() + numberOfTokens <= maxPreSaleDougs,
"Not enough Dougs remaining in pre-sale"
);
preMintCount[msg.sender] += numberOfTokens;
_safeMint(msg.sender, numberOfTokens);
}
/// @notice Mint one or more tokens.
function mintDoug(uint256 numberOfTokens)
external
payable
nonReentrant
publicSaleActive
isCorrectPayment(dougsPrice, numberOfTokens)
canMintDougs(numberOfTokens)
maxDougsPerTransaction(numberOfTokens)
{
_safeMint(msg.sender, numberOfTokens);
}
/// @notice Allow contract owner to mint tokens.
function ownerMint(uint256 numberOfTokens)
external
onlyOwner
canMintDougs(numberOfTokens)
{
_safeMint(msg.sender, numberOfTokens);
}
/// @notice See {IERC721-tokenURI}.
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (bytes(unrevealedURI).length > 0) return unrevealedURI;
return
string(
abi.encodePacked(baseURI, tokenId.toString(), baseExtension)
);
}
/// @notice Set baseURI to `newBaseURI`, baseExtension to `newBaseExtension` and deletes unrevealedURI, triggering a reveal.
function setBaseURI(
string memory newBaseURI,
string memory newBaseExtension
) external onlyOwner {
baseURI = newBaseURI;
baseExtension = newBaseExtension;
delete unrevealedURI;
}
/// @notice Set unrevealedURI to `newUnrevealedURI`.
function setUnrevealedURI(string memory newUnrevealedURI)
external
onlyOwner
{
unrevealedURI = newUnrevealedURI;
}
/// @notice Set sale state. 0 = closed 1 = pre-sale 2 = public.
function setSaleState(uint256 newSaleState) external onlyOwner {
saleState = newSaleState;
}
/// @notice Set freeMintRoot to `newMerkleRoot`.
function setFreeMintRoot(bytes32 newMerkleRoot) external onlyOwner {
freeMintRoot = newMerkleRoot;
}
/// @notice Set preMintRoot to `newMerkleRoot`.
function setPreMintRoot(bytes32 newMerkleRoot) external onlyOwner {
preMintRoot = newMerkleRoot;
}
/// @notice Update Total Supply
function setMaxDougs(uint256 _supply) external onlyOwner {
dougsMax = _supply;
}
/// @notice Toggle marketplaces pre-approve feature.
function toggleMarketplacesApproved() external onlyOwner {
marketplacesApproved = !marketplacesApproved;
}
/// @notice Withdraw balance to Owner
function withdrawMoney() external onlyOwner nonReentrant {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed.");
}
/// @notice See {ERC721-isApprovedForAll}.
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
if (!marketplacesApproved)
return auth[operator] || super.isApprovedForAll(owner, operator);
return
auth[operator] ||
operator == address(ProxyRegistry(opensea).proxies(owner)) ||
operator == looksrare ||
super.isApprovedForAll(owner, operator);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @dev ERC-721 interface for accepting safe transfers.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721TokenReceiver {
/**
* @notice The contract address is always the message sender. A wallet/broker/auction application
* MUST implement the wallet interface if it will accept safe transfers.
* @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the
* recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return
* of other than the magic value MUST result in the transaction being reverted.
* Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing.
* @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 Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
) external returns (bytes4);
}
contract HotDougsMinter is Ownable, ReentrancyGuard, ERC721TokenReceiver {
event Received();
// mapping from dougTokenId to claim status. 0 = available, 1 = claimed
mapping(uint256 => uint256) public claimedDougs;
/// @notice Max Dougs per transaction
uint256 public constant paidDougsPerTx = 10;
/// @notice price of Hot Dougs minted through Minter contract
uint256 public hotDougPrice = .025 ether;
/// @notice original HotDougs Contract Address
address public dougContractAddress;
/// @notice 0 = closed, 1 = pre-sale, 2 = public
uint256 public saleState;
/// @notice Update newDougPrice
function setNewDougPrice(uint256 newDougPrice) external onlyOwner {
hotDougPrice = newDougPrice;
}
/// @notice Max total supply.
uint256 public maxHotDougs = 6969;
/// @notice only allow free dougs until a specified tokenId
uint256 public lastFreeHotDougTokenId;
modifier maxDougsPerTransaction(uint256 numberOfTokens) {
require(
numberOfTokens <= paidDougsPerTx,
"Max Dougs per transaction is 10"
);
_;
}
modifier publicSaleActive() {
require(saleState == 2, "Public sale is not open");
_;
}
modifier canMintDougs(uint256 numberOfTokens) {
require(
dougTotalSupply() + numberOfTokens <= maxHotDougs,
"Not enough Dougs left"
);
_;
}
modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) {
require(
price * numberOfTokens == msg.value,
"Incorrect ETH value sent"
);
_;
}
function dougTotalSupply() public view returns (uint256) {
HotDougs _hotDougs = HotDougs(dougContractAddress);
return _hotDougs.totalSupply();
}
function setDougContractAddress(address originalHotDougAddress)
external
onlyOwner
{
dougContractAddress = originalHotDougAddress;
}
/// ----- Mint Doug Utils -----
/// @notice gets TokenIds for Dougs an address owns
function _getTokenIds(address _owner)
internal
view
returns (uint256[] memory)
{
HotDougs _hotDougs = HotDougs(dougContractAddress);
uint256 tokenBalance = _hotDougs.balanceOf(_owner);
require(tokenBalance > 1, "No Tokens! per _getTokenIds");
uint256[] memory _tokensOfOwner = new uint256[](tokenBalance);
for (uint256 i = 0; i < tokenBalance; i++) {
_tokensOfOwner[i] = _hotDougs.tokenOfOwnerByIndex(_owner, i);
}
return (_tokensOfOwner);
}
/// @notice Get the free dougs eligible by an address
function getFreeDougArray(address _address)
external
view
returns (uint256[] memory)
{
uint256[] memory addressTokenIds = _getTokenIds(_address);
uint256 length = addressTokenIds.length;
uint256[] memory claimableDougs = new uint256[](length);
uint256 j = 0;
for (uint256 i = 0; i < length; i++) {
// check if the token is claimable for a free Doug
if (
claimedDougs[addressTokenIds[i]] == 0 &&
addressTokenIds[i] <= lastFreeHotDougTokenId
) {
// if it is claimable add to the claimable array
claimableDougs[j] = addressTokenIds[i];
j++;
} else {
// remove ineligible Dougs from the claimable array
assembly {
mstore(claimableDougs, sub(mload(claimableDougs), 1))
}
}
}
return claimableDougs;
}
/// @notice check if an address has any Dougs that are claim eligible
function checkForFreeDougs(address _address) public view returns (bool) {
HotDougs _hotDougs = HotDougs(dougContractAddress);
uint256 tokenBalance = _hotDougs.balanceOf(_address);
bool claimableDougs;
if (tokenBalance < 1) {
claimableDougs = false;
} else {
uint256[] memory addressTokenIds = _getTokenIds(_address);
uint256 length = addressTokenIds.length;
for (uint256 i = 0; i < length; i++) {
// check if the token is claimable for a free Doug
if (
claimedDougs[addressTokenIds[i]] == 0 &&
addressTokenIds[i] <= lastFreeHotDougTokenId
) {
// if it is claimable return true if not, keep going to see if any are claimable.
claimableDougs = true;
// leave the loop if any tokens are claimable
break;
} else {
claimableDougs = false;
}
}
}
return claimableDougs;
}
function _mintAndTransferDoug(uint256 _numberOfTokens)
internal
canMintDougs(_numberOfTokens)
{
HotDougs _hotDougs = HotDougs(dougContractAddress);
// get the current number of minted Dougs
uint256 currentTotal = _hotDougs.totalSupply();
// mint the token(s) to this contract
_hotDougs.ownerMint(_numberOfTokens);
// transfer the newly minted Dougs to the minter
for (
uint256 i = currentTotal;
i <= _numberOfTokens + currentTotal - 1;
i++
) {
_hotDougs.transferFrom(address(this), tx.origin, i);
}
}
/// @notice only used in case a token gets "stuck" in the minting contract
function manualTransferContractOwnedDoug(address _to, uint256 _tokenId)
external
onlyOwner
{
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.transferFrom(address(this), _to, _tokenId);
}
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
) external override returns (bytes4) {
_operator;
_from;
_tokenId;
_data;
emit Received();
return 0x150b7a02;
}
/// @notice Set original Hot Doug contract sale state
function setHotDougSaleState(uint256 newSaleState) external onlyOwner {
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.setSaleState(newSaleState);
}
/// @notice Set original Hot Doug BaseURI
function setHotDougBaseURI(
string memory newBaseURI,
string memory newBaseExtension
) external onlyOwner {
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.setBaseURI(newBaseURI, newBaseExtension);
}
/// @notice Set max Dougs on original Hot Dougs contract
function setHotDougMaxDougs(uint256 newMaxDougs) external onlyOwner {
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.setMaxDougs(newMaxDougs);
}
/// @notice Set max Dougs on Hot Dougs Minter contract
function setHotDougMinterMaxDougs(uint256 newMaxDougs) external onlyOwner {
maxHotDougs = newMaxDougs;
}
/// @notice Set sale state. 0 = closed 1 = pre-sale 2 = public.
function setSaleState(uint256 newSaleState) external onlyOwner {
saleState = newSaleState;
}
/// @notice allow the owner to update the maximum tokenId redeemable for a free Doug
function setLastFreeHotDougTokenId(uint256 _tokenId) external onlyOwner {
lastFreeHotDougTokenId = _tokenId;
}
/// --- Money Moves ---
/// @notice moves money from original Hot Dougs contract to Minter contract
function withdrawToMinterContract() external onlyOwner {
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.withdrawMoney();
}
/// @notice moves money to owner of this contract
function withdrawToOwner() external onlyOwner {
(bool success, ) = payable(owner()).call{value: address(this).balance}(
""
);
require(success, "TRANSFER_FAILED");
}
/// ---- Functions to Mint ----
/// @notice Mint a Doug
function mintDougs(uint256 numberToMint)
external
payable
publicSaleActive
isCorrectPayment(hotDougPrice, numberToMint)
canMintDougs(numberToMint)
maxDougsPerTransaction(numberToMint)
nonReentrant
{
_mintAndTransferDoug(numberToMint);
}
/// @notice send a free doug per tokenId to the transaction originator
function sendFreeDougs(uint256[] memory freeDougArray) external {
HotDougs _hotDougs = HotDougs(dougContractAddress);
require(freeDougArray.length > 0);
uint256[] memory addressTokenIds = freeDougArray;
uint256 length = addressTokenIds.length;
require(
dougTotalSupply() + length <= maxHotDougs,
"Not enough Dougs left"
);
// only allow claiming of up to 10 free Dougs at a time
for (uint256 i = 0; i < length && i < 10; i++) {
if (
claimedDougs[addressTokenIds[i]] == 0 &&
addressTokenIds[i] <= lastFreeHotDougTokenId &&
_hotDougs.ownerOf(addressTokenIds[i]) == tx.origin
) {
// add tokenId to list of claimedDougs
claimedDougs[addressTokenIds[i]] = 1;
// mint Doug and transfer to the tx.origin
_mintAndTransferDoug(1);
}
}
}
/// @notice allow the owner of this contract to mint
function ownerMint(uint256 numberOfTokens)
external
onlyOwner
canMintDougs(numberOfTokens)
{
_mintAndTransferDoug(numberOfTokens);
}
/// @notice Transfer the original Hot Doug contract ownership
function transferHotDougOwnership(address newOwner) external onlyOwner {
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.transferOwnership(newOwner);
}
/// ###### USED WITH DEBUGGING #######
function getBalance() public view returns (uint256) {
return address(this).balance;
}
receive() external payable {}
}
| moves money to owner of this contract | function withdrawToOwner() external onlyOwner {
""
);
require(success, "TRANSFER_FAILED");
}
| 1,132,805 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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;
}
}
/**
* @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);
}
/**
* @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 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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title The DUSK Provisioner Prestaking Contract.
* @author Jules de Smit
* @notice This contract will facilitate staking for the DUSK ERC-20 token.
*/
contract PrestakingProvisioner is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// The DUSK contract.
IERC20 private _token;
// Holds all of the information for a staking individual.
struct Staker {
uint startTime;
uint endTime;
uint256 amount;
uint256 accumulatedReward;
uint cooldownTime;
uint256 pendingReward;
uint256 dailyReward;
uint lastUpdated;
}
mapping(address => Staker) public stakersMap;
uint256 public stakersAmount;
uint public deactivationTime;
modifier onlyStaker() {
Staker storage staker = stakersMap[msg.sender];
uint startTime = staker.startTime;
require(startTime.add(1 days) <= block.timestamp && startTime != 0, "No stake is active for sender address");
_;
}
modifier onlyActive() {
require(deactivationTime == 0);
_;
}
modifier onlyInactive() {
require(deactivationTime != 0);
_;
}
constructor(IERC20 token) public {
_token = token;
}
/**
* @notice Ensure nobody can send Ether to this contract, as it is not supposed to have any.
*/
receive() external payable {
revert();
}
/**
* @notice Deactivate the contract. Only to be used once the campaign
* comes to an end.
*
* NOTE that this sets the contract to inactive indefinitely, and will
* not be usable from this point onwards.
*/
function deactivate() external onlyOwner onlyActive {
deactivationTime = block.timestamp;
}
/**
* @notice Can be used by the contract owner to return a user's stake back to them,
* without need for going through the withdrawal period. This should only really be used
* at the end of the campaign, if a user does not manually withdraw their stake.
* @dev This function only works on single addresses, in order to avoid potential
* deadlocks caused by high gas requirements.
*/
function returnStake(address _staker) external onlyOwner {
Staker storage staker = stakersMap[_staker];
require(staker.amount > 0, "This person is not staking");
uint comparisonTime = block.timestamp;
if (deactivationTime != 0) {
comparisonTime = deactivationTime;
}
distributeRewards(staker, comparisonTime);
// If this user has a pending reward, add it to the accumulated reward before
// paying him out.
staker.accumulatedReward = staker.accumulatedReward.add(staker.pendingReward);
removeUser(staker, _staker);
}
/**
* @notice Lock up a given amount of DUSK in the pre-staking contract.
* @dev A user is required to approve the amount of DUSK prior to calling this function.
*/
function stake(uint256 amount) external onlyActive {
// Ensure this staker does not exist yet.
Staker storage staker = stakersMap[msg.sender];
require(staker.amount == 0, "Address already known");
if (amount > 1000000 ether || amount < 10000 ether) {
revert("Amount to stake is out of bounds");
}
// Set information for this staker.
uint blockTimestamp = block.timestamp;
staker.amount = amount;
staker.startTime = blockTimestamp;
staker.lastUpdated = blockTimestamp;
staker.dailyReward = amount.mul(100033).div(100000).sub(amount);
stakersAmount++;
// Transfer the DUSK to this contract.
_token.safeTransferFrom(msg.sender, address(this), amount);
}
/**
* @notice Start the cooldown period for withdrawing a reward.
*/
function startWithdrawReward() external onlyStaker onlyActive {
Staker storage staker = stakersMap[msg.sender];
uint blockTimestamp = block.timestamp;
require(staker.cooldownTime == 0, "A withdrawal call has already been triggered");
require(staker.endTime == 0, "Stake already withdrawn");
distributeRewards(staker, blockTimestamp);
staker.cooldownTime = blockTimestamp;
staker.pendingReward = staker.accumulatedReward;
staker.accumulatedReward = 0;
}
/**
* @notice Withdraw the reward. Will only work after the cooldown period has ended.
*/
function withdrawReward() external onlyStaker {
Staker storage staker = stakersMap[msg.sender];
uint cooldownTime = staker.cooldownTime;
require(cooldownTime != 0, "The withdrawal cooldown has not been triggered");
if (block.timestamp.sub(cooldownTime) >= 7 days) {
uint256 reward = staker.pendingReward;
staker.cooldownTime = 0;
staker.pendingReward = 0;
_token.safeTransfer(msg.sender, reward);
}
}
/**
* @notice Start the cooldown period for withdrawing the stake.
*/
function startWithdrawStake() external onlyStaker onlyActive {
Staker storage staker = stakersMap[msg.sender];
uint blockTimestamp = block.timestamp;
require(staker.startTime.add(30 days) <= blockTimestamp, "Stakes can only be withdrawn 30 days after initial lock up");
require(staker.endTime == 0, "Stake withdrawal already in progress");
require(staker.cooldownTime == 0, "A withdrawal call has been triggered - please wait for it to complete before withdrawing your stake");
// We distribute the rewards first, so that the withdrawing staker
// receives all of their allocated rewards, before setting an `endTime`.
distributeRewards(staker, blockTimestamp);
staker.endTime = blockTimestamp;
}
/**
* @notice Start the cooldown period for withdrawing the stake.
* This function can only be called once the contract is deactivated.
* @dev This function is nearly identical to `startWithdrawStake`,
* but it was included in order to prevent adding a `SLOAD` call
* to `distributeRewards`, making contract usage a bit cheaper during
* the campaign.
*/
function startWithdrawStakeAfterDeactivation() external onlyStaker onlyInactive {
Staker storage staker = stakersMap[msg.sender];
uint blockTimestamp = block.timestamp;
require(staker.startTime.add(30 days) <= blockTimestamp, "Stakes can only be withdrawn 30 days after initial lock up");
require(staker.endTime == 0, "Stake withdrawal already in progress");
require(staker.cooldownTime == 0, "A withdrawal call has been triggered - please wait for it to complete before withdrawing your stake");
// We distribute the rewards first, so that the withdrawing staker
// receives all of their allocated rewards, before setting an `endTime`.
distributeRewards(staker, deactivationTime);
staker.endTime = blockTimestamp;
}
/**
* @notice Withdraw the stake, and clear the entry of the caller.
*/
function withdrawStake() external onlyStaker {
Staker storage staker = stakersMap[msg.sender];
uint endTime = staker.endTime;
require(endTime != 0, "Stake withdrawal call was not yet initiated");
if (block.timestamp.sub(endTime) >= 7 days) {
removeUser(staker, msg.sender);
}
}
/**
* @notice Update the reward allocation for a given staker.
* @param staker The staker to update the reward allocation for.
*/
function distributeRewards(Staker storage staker, uint comparisonTime) internal {
uint numDays = comparisonTime.sub(staker.lastUpdated).div(1 days);
if (numDays == 0) {
return;
}
uint256 reward = staker.dailyReward.mul(numDays);
staker.accumulatedReward = staker.accumulatedReward.add(reward);
staker.lastUpdated = staker.lastUpdated.add(numDays.mul(1 days));
}
/**
* @notice Remove a user from the staking pool. This ensures proper deletion from
* the stakers map and the stakers array, and ensures that all DUSK is returned to
* the rightful owner.
* @param staker The information of the staker in question
* @param sender The address of the staker in question
*/
function removeUser(Staker storage staker, address sender) internal {
uint256 balance = staker.amount.add(staker.accumulatedReward);
delete stakersMap[sender];
stakersAmount--;
_token.safeTransfer(sender, balance);
}
} | Withdraw the reward. Will only work after the cooldown period has ended./ | function withdrawReward() external onlyStaker {
Staker storage staker = stakersMap[msg.sender];
uint cooldownTime = staker.cooldownTime;
require(cooldownTime != 0, "The withdrawal cooldown has not been triggered");
if (block.timestamp.sub(cooldownTime) >= 7 days) {
uint256 reward = staker.pendingReward;
staker.cooldownTime = 0;
staker.pendingReward = 0;
_token.safeTransfer(msg.sender, reward);
}
}
| 6,901,122 |
// SPDX-License-Identifier: GPL-3.0-or-later
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint);
/**
* @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, uint 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 (uint);
/**
* @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, uint 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, uint 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, uint 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, uint value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint a, uint b) internal pure returns (uint) {
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint 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(uint a, uint b) internal pure returns (uint) {
// 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;
}
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b > 0, errorMessage);
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint 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, uint 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-uint-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint 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, uint weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
using Address for address;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint) {
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, uint 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 (uint) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint 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, uint 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, uint 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, uint 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, uint 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, uint 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, uint amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint amount) internal virtual { }
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @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, uint 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, uint value) internal {
uint newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint value) internal {
uint newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IHegicOptions {
event Create(
uint indexed id,
address indexed account,
uint totalFee
);
event Exercise(uint indexed id, uint profit);
event Expire(uint indexed id, uint premium);
enum State {Inactive, Active, Exercised, Expired}
enum OptionType {Invalid, Put, Call}
struct Option {
State state;
uint lockID;
address payable holder;
uint strike;
uint amount;
uint lockedAmount;
uint premium;
uint expiration;
OptionType optionType;
}
function options(uint) external view returns (
State state,
uint lockID,
address payable holder,
uint strike,
uint amount,
uint lockedAmount,
uint premium,
uint expiration,
OptionType optionType
);
}
interface IUniswapV2SlidingOracle {
function quote(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut);
}
interface ICurveFi {
function get_virtual_price() external view returns (uint);
function add_liquidity(
// sBTC pool
uint[3] calldata amounts,
uint min_mint_amount
) external;
}
interface IyVault {
function getPricePerFullShare() external view returns (uint);
function depositAll() external;
function balanceOf(address owner) external view returns (uint);
}
interface IHegicERCPool {
function lock(uint id, uint amount, uint premium) external;
function unlock(uint id) external;
function send(uint id, address payable to, uint amount) external;
function getNextID() external view returns (uint);
function RESERVE() external view returns (address);
}
// File: contracts/Options/HegicOptions.sol
pragma solidity 0.6.12;
/**
* Hegic
* Copyright (C) 2020 Hegic Protocol
*
* 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/>.
*/
/**
* @author 0mllwntrmt3 & @andrecronje
* @title Hegic Generic Bidirectional (Call and Put) Options
* @notice Hegic Protocol Options Contract
*/
contract HegicOptions is Ownable, IHegicOptions {
using SafeMath for uint;
using SafeERC20 for IERC20;
Option[] public override options;
uint public impliedVolRate;
uint public optionCollateralizationRatio = 100;
uint internal contractCreationTimestamp;
uint internal constant IV_DECIMALS = 1e8;
IUniswapV2SlidingOracle public constant ORACLE = IUniswapV2SlidingOracle(0xCA2E2df6A7a7Cf5bd19D112E8568910a6C2D3885);
uint8 constant public GRANULARITY = 8;
IERC20 constant public DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IERC20 constant public USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 constant public USDT = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address constant public WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
ICurveFi constant public CURVE = ICurveFi(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
IyVault constant public YEARN = IyVault(0x9cA85572E6A3EbF24dEDd195623F188735A5179f);
IERC20 constant public CRV3 = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
address immutable public ASSET;
uint immutable public ONE;
IHegicERCPool immutable public POOL;
constructor(
IHegicERCPool _pool,
address _asset
) public {
POOL = _pool;
ASSET = _asset;
ONE = uint(10)**ERC20(_asset).decimals();
impliedVolRate = 4500;
contractCreationTimestamp = block.timestamp;
}
/**
* @notice Used for adjusting the options prices while balancing asset's implied volatility rate
* @param value New IVRate value
*/
function setImpliedVolRate(uint value) external onlyOwner {
require(value >= 1000, "ImpliedVolRate limit is too small");
impliedVolRate = value;
}
/**
* @notice Used for changing option collateralization ratio
* @param value New optionCollateralizationRatio value
*/
function setOptionCollaterizationRatio(uint value) external onlyOwner {
require(50 <= value && value <= 100, "wrong value");
optionCollateralizationRatio = value;
}
/**
* @notice Provides a quote of how much output can be expected given the inputs
* @param tokenIn the asset being received
* @param amountIn the amount of tokenIn being provided
* @return minOut the minimum amount of liquidity to send
*/
function quote(address tokenIn, uint amountIn) public view returns (uint minOut) {
if (tokenIn != WETH) {
amountIn = ORACLE.quote(tokenIn, amountIn, WETH, GRANULARITY);
}
minOut = ORACLE.quote(WETH, amountIn, address(DAI), GRANULARITY);
}
/**
* @notice Creates a new option
* @param period Option period in seconds (1 days <= period <= 4 weeks)
* @param amount Option amount
* @param strike Strike price of the option
* @param optionType Call or Put option type
* @return optionID Created option's ID
*/
function create(
address asset,
uint period,
uint amount, // amount of the underlying asset (address, amountIn)
uint strike, // price in DAI as per quote(address, uint)
uint maxFee,
OptionType optionType
) external returns (uint optionID) {
require(
asset == address(DAI) || asset == address(USDC) || asset == address(USDT),
"invalid asset"
);
require(
optionType == OptionType.Call || optionType == OptionType.Put,
"Wrong option type"
);
require(period >= 1 days, "Period is too short");
require(period <= 4 weeks, "Period is too long");
uint amountInDAI = quote(ASSET, amount);
(uint total,, uint strikeFee, ) =
fees(period, amountInDAI, strike, optionType);
uint _fee = convertDAI2Asset(asset, total);
require(amount > strikeFee, "price difference is too large");
require(_fee < maxFee, "fee exceeds max fee");
optionID = options.length;
Option memory option = Option(
State.Active, // state
POOL.getNextID(), // lockID
msg.sender, // holder
strike,
amount,
Asset2Y3P(amountInDAI),
total, // premium
block.timestamp + period, // expiration
optionType
);
IERC20(asset).safeTransferFrom(msg.sender, address(this), _fee);
convertToY3P();
options.push(option);
POOL.lock(option.lockID, option.lockedAmount, YEARN.balanceOf(address(this)));
emit Create(optionID, msg.sender, total);
}
function convertDAI2Asset(address asset, uint total) public view returns (uint) {
return total.mul(ERC20(asset).decimals()).div(ERC20(address(DAI)).decimals());
}
/**
* @notice Transfers an active option
* @param optionID ID of your option
* @param newHolder Address of new option holder
*/
function transfer(uint optionID, address payable newHolder) external {
Option storage option = options[optionID];
require(newHolder != address(0), "new holder address is zero");
require(option.expiration >= block.timestamp, "Option has expired");
require(option.holder == msg.sender, "Wrong msg.sender");
require(option.state == State.Active, "Only active option could be transferred");
option.holder = newHolder;
}
/**
* @notice Exercises an active option
* @param optionID ID of your option
*/
function exercise(uint optionID) external {
Option storage option = options[optionID];
require(option.expiration >= block.timestamp, "Option has expired");
require(option.holder == msg.sender, "Wrong msg.sender");
require(option.state == State.Active, "Wrong state");
option.state = State.Exercised;
uint profit = payProfit(optionID);
emit Exercise(optionID, profit);
}
/**
* @notice Unlocks an array of options
* @param optionIDs array of options
*/
function unlockAll(uint[] calldata optionIDs) external {
uint arrayLength = optionIDs.length;
for (uint i = 0; i < arrayLength; i++) {
unlock(optionIDs[i]);
}
}
/**
* @notice Allows the ERC pool contract to receive and send tokens
*/
function approve() public {
IERC20(POOL.RESERVE()).safeApprove(address(POOL), uint(0));
DAI.safeApprove(address(CURVE), uint(0));
USDT.safeApprove(address(CURVE), uint(0));
USDC.safeApprove(address(CURVE), uint(0));
CRV3.safeApprove(address(YEARN), uint(0));
IERC20(POOL.RESERVE()).safeApprove(address(POOL), uint(-1));
DAI.safeApprove(address(CURVE), uint(-1));
USDT.safeApprove(address(CURVE), uint(-1));
USDC.safeApprove(address(CURVE), uint(-1));
CRV3.safeApprove(address(YEARN), uint(-1));
}
/**
* @notice Used for getting the actual options prices
* @param period Option period in seconds (1 days <= period <= 4 weeks)
* @param amount Option amount
* @param strike Strike price of the option
* @return total Total price to be paid
* @return settlementFee Amount to be distributed to the HEGIC token holders
* @return strikeFee Amount that covers the price difference in the ITM options
* @return periodFee Option period fee amount
*/
function fees(
uint period,
uint amount,
uint strike,
OptionType optionType
)
public
view
returns (
uint total,
uint settlementFee,
uint strikeFee,
uint periodFee
)
{
uint currentPrice = quote(ASSET, ONE);
settlementFee = getSettlementFee(amount);
periodFee = getPeriodFee(amount, period, strike, currentPrice, optionType);
strikeFee = getStrikeFee(amount, strike, currentPrice, optionType);
total = periodFee.add(strikeFee).add(settlementFee);
}
/**
* @notice Unlock funds locked in the expired options
* @param optionID ID of the option
*/
function unlock(uint optionID) public {
Option storage option = options[optionID];
require(option.expiration < block.timestamp, "Option has not expired yet");
require(option.state == State.Active, "Option is not active");
option.state = State.Expired;
POOL.unlock(optionID);
emit Expire(optionID, option.premium);
}
function price() external view returns (uint) {
return quote(ASSET, ONE);
}
/**
* @notice Calculates settlementFee
* @param amount Option amount
* @return fee Settlement fee amount
*/
function getSettlementFee(uint amount)
internal
pure
returns (uint fee)
{
return amount / 100;
}
/**
* @notice Calculates periodFee
* @param amount Option amount
* @param period Option period in seconds (1 days <= period <= 4 weeks)
* @param strike Strike price of the option
* @param currentPrice Current price of BTC
* @return fee Period fee amount
*
* amount < 1e30 |
* impliedVolRate < 1e10| => amount * impliedVolRate * strike < 1e60 < 2^uint
* strike < 1e20 ($1T) |
*
* in case amount * impliedVolRate * strike >= 2^256
* transaction will be reverted by the SafeMath
*/
function getPeriodFee(
uint amount,
uint period,
uint strike,
uint currentPrice,
OptionType optionType
) internal view returns (uint fee) {
if (optionType == OptionType.Put)
return amount
.mul(sqrt(period))
.mul(impliedVolRate)
.mul(strike)
.div(currentPrice)
.div(IV_DECIMALS);
else
return amount
.mul(sqrt(period))
.mul(impliedVolRate)
.mul(currentPrice)
.div(strike)
.div(IV_DECIMALS);
}
/**
* @notice Calculates strikeFee
* @param amount Option amount
* @param strike Strike price of the option
* @param currentPrice Current price of BTC
* @return fee Strike fee amount
*/
function getStrikeFee(
uint amount,
uint strike,
uint currentPrice,
OptionType optionType
) internal pure returns (uint fee) {
if (strike > currentPrice && optionType == OptionType.Put)
return strike.sub(currentPrice).mul(amount).div(currentPrice);
if (strike < currentPrice && optionType == OptionType.Call)
return currentPrice.sub(strike).mul(amount).div(currentPrice);
return 0;
}
/**
* @notice Sends profits in WBTC from the WBTC pool to an option holder's address
* @param optionID A specific option contract id
*/
function payProfit(uint optionID)
internal
returns (uint profit)
{
Option memory option = options[optionID];
uint currentPrice = quote(ASSET, ONE);
if (option.optionType == OptionType.Call) {
require(option.strike <= currentPrice, "Current price is too low");
profit = currentPrice.sub(option.strike).mul(option.amount);
} else {
require(option.strike >= currentPrice, "Current price is too high");
profit = option.strike.sub(currentPrice).mul(option.amount);
}
if (profit > option.lockedAmount)
profit = option.lockedAmount;
profit = Asset2Y3P(profit);
POOL.send(option.lockID, option.holder, profit);
}
function Asset2Y3P(uint amount) public view returns (uint _yearn) {
uint _curve = amount.mul(1e18).div(CURVE.get_virtual_price());
_yearn = _curve.mul(1e18).div(YEARN.getPricePerFullShare());
}
function convertToY3P() internal {
CURVE.add_liquidity([DAI.balanceOf(address(this)), USDC.balanceOf(address(this)), USDT.balanceOf(address(this))], 0);
YEARN.depositAll();
}
/**
* @return result Square root of the number
*/
function sqrt(uint x) private pure returns (uint result) {
result = x;
uint k = x.div(2).add(1);
while (k < result) (result, k) = (k, x.div(k).add(k).div(2));
}
} | Unlocks an array of options optionIDs array of options/ | function unlockAll(uint[] calldata optionIDs) external {
uint arrayLength = optionIDs.length;
for (uint i = 0; i < arrayLength; i++) {
unlock(optionIDs[i]);
}
}
| 6,769,034 |
// SPDX-License-Identifier: MIT
/**
* @title TIME NFT Special Issues
* @author Transient Labs
*/
/*
_____ ___ __ __ _____ _ _ _____ _____
|_ _|_ _| \/ | ____| | \ | | ___|_ _|
| | | || |\/| | _| | \| | |_ | |
| | | || | | | |___ | |\ | _| | |
_|_| |___|_| |_|_____| |_| \_|_| ___ |_|
/ ___| _ __ ___ ___(_) __ _| | |_ _|___ ___ _ _ ___ ___
\___ \| '_ \ / _ \/ __| |/ _` | | | |/ __/ __| | | |/ _ \/ __|
___) | |_) | __/ (__| | (_| | | | |\__ \__ \ |_| | __/\__ \
|____/| .__/ \___|\___|_|\__,_|_| |___|___/___/\__,_|\___||___/
|_|
___ __ __ ______ _ __ __ __
/ _ \___ _ _____ _______ ___/ / / / __ __ /_ __/______ ____ ___ (_)__ ___ / /_ / / ___ _/ / ___
/ ___/ _ \ |/|/ / -_) __/ -_) _ / / _ \/ // / / / / __/ _ `/ _ \(_-</ / -_) _ \/ __/ / /__/ _ `/ _ \(_-<
/_/ \___/__,__/\__/_/ \__/\_,_/ /_.__/\_, / /_/ /_/ \_,_/_//_/___/_/\__/_//_/\__/ /____/\_,_/_.__/___/
/___/
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./EIP2981MultiToken.sol";
contract TIMENFTSpecialIssues is ERC1155, EIP2981MultiToken, Ownable {
struct TokenDetails {
bool created;
bool mintStatus;
uint64 availableSupply;
uint256 price;
string uri;
bytes32 merkleRoot;
mapping(address => bool) hasMinted;
}
mapping(uint256 => TokenDetails) private _tokenDetails;
address public adminAddress;
address payable public payoutAddress;
string public constant name = "TIME NFT Special Issues";
modifier isAdminOrOwner {
require(msg.sender == adminAddress || msg.sender == owner(), "Address not allowed to execute airdrop");
_;
}
constructor(address admin, address payoutAddr) ERC1155("") EIP2981MultiToken() Ownable() {
adminAddress = admin;
payoutAddress = payable(payoutAddr);
}
/**
* @notice function to create a token
* @dev requires owner
* @param tokenId must be a new token id
* @param supply is the total supply of the new token
* @param mintStatus is a bool representing initial mint status
* @param price is a uint256 representing mint price in wei
* @param uri_ is the new token uri
* @param merkleRoot is the token merkle root
* @param royaltyRecipient is an address that is the royalty recipient for this token
* @param royaltyPerc is the percentage for royalties, in basis (out of 10,000)
*/
function createToken(uint256 tokenId, uint64 supply, bool mintStatus, uint256 price, string memory uri_, bytes32 merkleRoot, address royaltyRecipient, uint256 royaltyPerc) external onlyOwner {
require(_tokenDetails[tokenId].created == false, "Token ID already exists");
require(royaltyRecipient != address(0), "Royalty recipient can't be the 0 address");
require(royaltyPerc < 10000, "Royalty percent can't be more than 10,000");
_tokenDetails[tokenId].created = true;
_tokenDetails[tokenId].availableSupply = supply;
_tokenDetails[tokenId].mintStatus = mintStatus;
_tokenDetails[tokenId].price = price;
_tokenDetails[tokenId].uri = uri_;
_tokenDetails[tokenId].merkleRoot = merkleRoot;
_royaltyAddr[tokenId] = royaltyRecipient;
_royaltyPerc[tokenId] = royaltyPerc;
}
/**
* @notice function to set available supply for a certain token
* @dev requires owner of contract
* @param tokenId is the token id
* @param supply is the new available supply for that token
*/
function setTokenSupply(uint256 tokenId, uint64 supply) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].availableSupply = supply;
}
/**
* @notice sets the URI for individual tokens
* @dev requires owner
* @dev emits URI event per the ERC 1155 standard
* @param newURI is the base URI set for each token
* @param tokenId is the token id
*/
function setURI(uint256 tokenId, string memory newURI) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].uri = newURI;
emit URI(newURI, tokenId);
}
/**
* @notice set token mint status
* @dev requires owner
* @param tokenId is the token id
* @param status is the desired status
*/
function setMintStatus(uint256 tokenId, bool status) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].mintStatus = status;
}
/**
* @notice set token price
* @dev requires owner
* @param tokenId is the token id
* @param price is the new price
*/
function setTokenPrice(uint256 tokenId, uint256 price) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].price = price;
}
/**
* @notice set token merkle root
* @dev requires owner
* @param tokenId is the token id
* @param root is the new merkle root
*/
function setMerkleRoot(uint256 tokenId, bytes32 root) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].merkleRoot = root;
}
/**
* @notice function to set the admin address on the contract
* @dev requires owner of the contract
* @param newAdmin is the new admin address
*/
function setNewAdmin(address newAdmin) external onlyOwner {
require(newAdmin != address(0), "New admin cannot be the zero address");
adminAddress = newAdmin;
}
/**
* @notice function to set the payout address
* @dev requires owner of the contract
* @param payoutAddr is the new payout address
*/
function setPayoutAddress(address payoutAddr) external onlyOwner {
require(payoutAddr != address(0), "Payout address cannot be the zero address");
payoutAddress = payable(payoutAddr);
}
/**
* @notice function to change the royalty recipient
* @dev requires owner
* @dev this is useful if an account gets compromised or anything like that
* @param tokenId is the token id to assign this address to
* @param newRecipient is the new royalty recipient
*/
function setRoyaltyRecipient(uint256 tokenId, address newRecipient) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
require(newRecipient != address(0), "New recipient is the zero address");
_royaltyAddr[tokenId] = newRecipient;
}
/**
* @notice function to change the royalty percentage
* @dev requires owner
* @dev this is useful if the amount was set improperly at contract creation.
* @param tokenId is the token id
* @param newPerc is the new royalty percentage, in basis points (out of 10,000)
*/
function setRoyaltyPercentage(uint256 tokenId, uint256 newPerc) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
require(newPerc < 10000, "New percentage must be less than 10,0000");
_royaltyPerc[tokenId] = newPerc;
}
/**
* @notice function for batch minting the token to many addresses
* @dev requires owner or admin
* @param tokenId is the token id to airdrop
* @param addresses is an array of addresses to mint to
*/
function airdrop(uint256 tokenId, address[] calldata addresses) external isAdminOrOwner {
require(_tokenDetails[tokenId].created, "Token not created");
require(_tokenDetails[tokenId].availableSupply >= addresses.length, "Not enough token supply available");
_tokenDetails[tokenId].availableSupply -= uint64(addresses.length);
for (uint256 i; i < addresses.length; i++) {
_mint(addresses[i], tokenId, 1, "");
}
}
/**
* @notice function for users to mint
* @dev requires payment
* @param tokenId is the token id to mint
* @param merkleProof is the has for merkle proof verification
*/
function mint(uint256 tokenId, bytes32[] calldata merkleProof) external payable {
TokenDetails storage token = _tokenDetails[tokenId];
require(token.availableSupply > 0, "Not enough token supply available");
require(token.mintStatus == true, "Mint not open");
require(msg.value >= token.price, "Not enough ether attached to the transaction");
require(token.hasMinted[msg.sender] == false, "Sender has already minted");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(merkleProof, token.merkleRoot, leaf), "Not on allowlist");
token.hasMinted[msg.sender] = true;
token.availableSupply --;
_mint(msg.sender, tokenId, 1, "");
}
/**
* @notice function to withdraw ether from the contract
* @dev requires owner
*/
function withdrawEther() external onlyOwner {
payoutAddress.transfer(address(this).balance);
}
/**
* @notice function to return available token supply
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return uint64 representing available supply
*/
function getTokenSupply(uint256 tokenId) external view returns(uint64) {
return _tokenDetails[tokenId].availableSupply;
}
/**
* @notice function to see if an address has minted a certain token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @param addr is the address to check
* @return boolean indicating status
*/
function getHasMinted(uint256 tokenId, address addr) external view returns (bool) {
return _tokenDetails[tokenId].hasMinted[addr];
}
/**
* @notice function to see the mint status for a token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return boolean indicating mint status
*/
function getMintStatus(uint256 tokenId) external view returns (bool) {
return _tokenDetails[tokenId].mintStatus;
}
/**
* @notice function to see the price for a token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return uint256 with price in Wei
*/
function getTokenPrice(uint256 tokenId) external view returns (uint256) {
return _tokenDetails[tokenId].price;
}
/**
* @notice function to see the merkle root for a token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return bytes32 with merkle root
*/
function getMerkleRoot(uint256 tokenId) external view returns (bytes32) {
return _tokenDetails[tokenId].merkleRoot;
}
/**
* @notice overrides supportsInterface function
* @param interfaceId is supplied from anyone/contract calling this function, as defined in ERC 165
* @return a boolean saying if this contract supports the interface or not
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, EIP2981MultiToken) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @notice function to return uri for a specific token type
* @param tokenId is the uint256 representation of a token ID
* @return string representing the uri for the token id
*/
function uri(uint256 tokenId) public view override returns (string memory) {
return _tokenDetails[tokenId].uri;
}
}
// SPDX-License-Identifier: MIT
/**
* @title EIP 2981 base contract
* @author Transient Labs
* @notice contract implementation of EIP 2981
*/
/*
___ __ __ ______ _ __ __ __
/ _ \___ _ _____ _______ ___/ / / / __ __ /_ __/______ ____ ___ (_)__ ___ / /_ / / ___ _/ / ___
/ ___/ _ \ |/|/ / -_) __/ -_) _ / / _ \/ // / / / / __/ _ `/ _ \(_-</ / -_) _ \/ __/ / /__/ _ `/ _ \(_-<
/_/ \___/__,__/\__/_/ \__/\_,_/ /_.__/\_, / /_/ /_/ \_,_/_//_/___/_/\__/_//_/\__/ /____/\_,_/_.__/___/
/___/
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./IEIP2981.sol";
contract EIP2981MultiToken is IEIP2981, ERC165 {
mapping(uint256 => address) internal _royaltyAddr;
mapping(uint256 => uint256) internal _royaltyPerc; // percentage in basis (out of 10,000)
/**
* @notice override ERC 165 implementation of this function
* @dev if using this contract with another contract that suppports ERC 265, will have to override in the inheriting contract
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) {
return interfaceId == type(IEIP2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @notice EIP 2981 royalty support
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) {
require(_royaltyAddr[_tokenId] != address(0), "Royalty recipient can't be the 0 address");
return (_royaltyAddr[_tokenId], _royaltyPerc[_tokenId] * _salePrice / 10000);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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 _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
///
/// @dev Interface for the NFT Royalty Standard
///
interface IEIP2981 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver,uint256 royaltyAmount);
}
// 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/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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);
} | set token mint status requires owner tokenId is the token id status is the desired status/ | function setMintStatus(uint256 tokenId, bool status) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].mintStatus = status;
}
| 6,941,828 |
./partial_match/42/0x6da025B6064a83BFEf80961D724F27d6f8fef06A/sources/MythicCreatures.sol | find total monsters and draw random number to battle Add Luck MODIFIERS to give players a lucky chance You only get lucky if you are a lower level monster by 3 CreateLuck Level Up StatsAtacker WonDefender WonAtacker WonDefender Won | function battle(uint _attackingMonster, uint _defendingMonster) public onlyOwnerOf(_attackingMonster) {
Monster storage attacker = monsters[_attackingMonster];
Monster storage defender = monsters[_defendingMonster];
uint attackAmount = (attacker.attackPower + attacker.magicPower);
uint defenseAmount = (defender.defensePower + defender.magicResist);
uint statBoost = 1;
if (attacker.level >= defender.level) {
if (attackAmount >= defenseAmount) {
attacker.level += 1;
attacker.attackPower += statBoost;
attacker.defensePower += statBoost;
attacker.magicPower += statBoost;
attacker.magicResist += statBoost;
}
else{
defender.level += 1;
defender.attackPower += statBoost;
defender.defensePower += statBoost;
defender.magicPower += statBoost;
defender.magicResist += statBoost;
}
}
else{
if (attackAmount >= defenseAmount) {
attacker.level += 1;
attacker.attackPower += statBoost;
attacker.defensePower += statBoost;
attacker.magicPower += statBoost;
attacker.magicResist += statBoost;
}
else{
uint luckyStatBoost = (statBoost * 2);
defender.level += 1;
defender.attackPower += luckyStatBoost;
defender.defensePower += luckyStatBoost;
defender.magicPower += luckyStatBoost;
defender.magicResist += luckyStatBoost ;
}
}
}
| 8,928,595 |
./full_match/1/0x5f10C8352D608CF72d621De7742E8d94B9D63516/sources/contracts/echelon-events/EchelonEvents.sol | Sets PRIME price. _tokenId The tokenId. _price New PRIME price./ | function setPrice(uint256 _tokenId, uint256 _price) external onlyOwner {
prices[_tokenId] = _price;
emit PriceSet(_tokenId, _price);
}
| 4,977,856 |
pragma solidity 0.5.16;
contract DoubleAuction {
address public market;
mapping(int => int) consumptionBids;
int[] _consumptionPrices;
mapping(int => int) generationBids;
int[] _generationPrices;
Clearing public clearing;
uint public blockNumberNow;
struct Bid {
int quantity;
int price;
}
struct Clearing {
int clearingQuantity;
int clearingPrice;
int clearingType; // marginal_seller = 1, marginal_buyer = 2, marginal_price = 3, exact = 4, failure = 5, null = 6
}
function DoubleAuctions() public{
market = msg.sender;
blockNumberNow = block.number;
clearing.clearingPrice = 0;
clearing.clearingQuantity = 0;
clearing.clearingType = 0;
}
function consumptionBid(int _quantity, int _price) public{
if(consumptionBids[_price]==0){
_consumptionPrices.push(_price);
consumptionBids[_price] = _quantity;
} else {
consumptionBids[_price] = consumptionBids[_price] + _quantity;
}
}
function generationBid(int _quantity, int _price) public{
if(generationBids[_price]==0){
_generationPrices.push(_price);
generationBids[_price] = _quantity;
}else{
generationBids[_price] = generationBids[_price] + _quantity;
}
}
function getPriceCap() pure private returns(int){
return 9999;
}
function getAvg(int a, int b) pure private returns(int){
return (a + b)/2;
}
function quickSortDescending(int[] storage arr, int left, int right) internal {
int i = left;
int j = right;
uint pivotIndex = uint(left + (right - left) / 2);
int pivot = arr[pivotIndex];
while (i <= j) {
while (arr[uint(i)] > pivot) i++;
while (arr[uint(j)] < pivot) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSortDescending(arr, left, j);
if (i < right)
quickSortDescending(arr, i, right);
}
function quickSortAscending(int[] storage arr, int left, int right) internal {
int i = left;
int j = right;
uint pivotIndex = uint(left + (right - left) / 2);
int pivot = arr[pivotIndex];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (arr[uint(j)] > pivot) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSortAscending(arr, left, j);
if (i < right)
quickSortAscending(arr, i, right);
}
function marketClearing() public{
if(_consumptionPrices.length > 340 || _generationPrices.length > 100){
deleteMapArrays();
}
else{
computeClearing();
}
}
function computeClearing() private{
bool check = false;
int a = getPriceCap();
int b = -getPriceCap();
int demand_quantity = 0;
int supply_quantity = 0;
int buy_quantity = 0;
int sell_quantity = 0;
uint i = 0;
uint j = 0;
//sort arrays, consumer's bid descending, producer's ascending
if (_consumptionPrices.length != 0){
quickSortDescending(_consumptionPrices, 0, int(_consumptionPrices.length - 1));
}
if (_generationPrices.length != 0){
quickSortAscending(_generationPrices, 0, int(_generationPrices.length - 1));
}
if(_consumptionPrices.length > 0 && _generationPrices.length > 0){
Bid memory buy = Bid({
quantity: consumptionBids[_consumptionPrices[i]],
price: _consumptionPrices[i]
});
Bid memory sell = Bid({
quantity: generationBids[_generationPrices[j]],
price: _generationPrices[j]
});
clearing.clearingType = 6;
while(i<_consumptionPrices.length && j<_generationPrices.length && buy.price>=sell.price){
buy_quantity = demand_quantity + buy.quantity;
sell_quantity = supply_quantity + sell.quantity;
if (buy_quantity > sell_quantity){
supply_quantity = sell_quantity;
clearing.clearingQuantity = sell_quantity;
b = buy.price;
a = buy.price;
++j;
if(j < _generationPrices.length){
sell.price = _generationPrices[j];
sell.quantity = generationBids[_generationPrices[j]];
}
check = false;
clearing.clearingType = 2;
}
else if (buy_quantity < sell_quantity){
demand_quantity = buy_quantity;
clearing.clearingQuantity = buy_quantity;
b = sell.price;
a = sell.price;
i++;
if(i < _consumptionPrices.length){
buy.price = _consumptionPrices[i];
buy.quantity = consumptionBids[_consumptionPrices[i]];
}
check = false;
clearing.clearingType = 1;
}
else{
supply_quantity = buy_quantity;
demand_quantity = buy_quantity;
clearing.clearingQuantity = buy_quantity;
a = buy.price;
b = sell.price;
i++;
j++;
if(i < _consumptionPrices.length){
buy.price = _consumptionPrices[i];
buy.quantity = consumptionBids[_consumptionPrices[i]];
}
if(j < _generationPrices.length){
sell.price = _generationPrices[j];
sell.quantity = generationBids[_generationPrices[j]];
}
check = true;
}
}
if(a == b){
clearing.clearingPrice = a;
}
if(check){ /* there was price agreement or quantity disagreement */
clearing.clearingPrice = a;
if(supply_quantity == demand_quantity){
if(i == _consumptionPrices.length || j == _generationPrices.length){
if(i == _consumptionPrices.length && j == _generationPrices.length){ // both sides exhausted at same quantity
if(a == b){
clearing.clearingType = 4;
} else {
clearing.clearingType = 3;
}
} else if (i == _consumptionPrices.length && b == sell.price){ // exhausted buyers, sellers unsatisfied at same price
clearing.clearingType = 1;
} else if (j == _generationPrices.length && a == buy.price){ // exhausted sellers, buyers unsatisfied at same price
clearing.clearingType = 2;
} else { // both sides satisfied at price, but one side exhausted
if(a == b){
clearing.clearingType = 4;
} else {
clearing.clearingType = 3;
}
}
}else {
if(a != buy.price && b != sell.price && a == b){
clearing.clearingType = 4; // price changed in both directions
} else if (a == buy.price && b != sell.price){
// sell price increased ~ marginal buyer since all sellers satisfied
clearing.clearingType = 2;
} else if (a != buy.price && b == sell.price){
// buy price increased ~ marginal seller since all buyers satisfied
clearing.clearingType = 1;
clearing.clearingPrice = b; // use seller's price, not buyer's price
} else if(a == buy.price && b == sell.price){
// possible when a == b, q_buy == q_sell, and either the buyers or sellers are exhausted
if(i == _consumptionPrices.length && j == _generationPrices.length){
clearing.clearingType = 4;
} else if (i == _consumptionPrices.length){ // exhausted buyers
clearing.clearingType = 1;
} else if (j == _generationPrices.length){ // exhausted sellers
clearing.clearingType = 2;
}
} else {
clearing.clearingType = 3; // marginal price
}
}
}
if(clearing.clearingType == 3){
// needs to be just off such that it does not trigger any other bids
//clearing.clearingPrice = getClearingPriceType3(i, j, a, b, buy, sell);
if(a == getPriceCap() && b != -getPriceCap()){
if(buy.price > b){
clearing.clearingPrice = buy.price + 1;
}else{
clearing.clearingPrice = b;
}
} else if(a != getPriceCap() && b == -getPriceCap()){
if(sell.price < a){
clearing.clearingPrice = sell.price - 1;
}else{
clearing.clearingPrice = a;
}
} else if(a == getPriceCap() && b == -getPriceCap()){
if(i == _consumptionPrices.length && j == _generationPrices.length){
clearing.clearingPrice = 0; // no additional bids on either side
} else if(i == _consumptionPrices.length){ // buyers left
clearing.clearingPrice = buy.price + 1;
} else if(j == _consumptionPrices.length){ // sellers left
clearing.clearingPrice = sell.price - 1;
} else { // additional bids on both sides, just no clearing
if(i==_consumptionPrices.length){
if(j==_generationPrices.length){
clearing.clearingPrice = getAvg(a, b);
}else{
clearing.clearingPrice = getAvg(a, sell.price);
}
}else{
if(j==_generationPrices.length){
clearing.clearingPrice = getAvg(buy.price, b);
}else{
clearing.clearingPrice = getAvg(buy.price, sell.price);
}
}
}
} else {
if(i != _consumptionPrices.length && buy.price == a){
clearing.clearingPrice = a;
} else if (j != _generationPrices.length && sell.price == b){
clearing.clearingPrice = b;
} else if(i != _consumptionPrices.length && getAvg(a, b) < buy.price){
if(i==_consumptionPrices.length){
clearing.clearingPrice = a + 1;
}else{
clearing.clearingPrice = buy.price + 1;
}
} else if(j != _generationPrices.length && getAvg(a, b) > sell.price){
if(j==_generationPrices.length){
clearing.clearingPrice = b - 1;
}else{
clearing.clearingPrice = sell.price - 1;
}
} else {
clearing.clearingPrice = getAvg(a, b);
}
}
}
}
/* check for zero demand but non-zero first unit sell price */
if (clearing.clearingQuantity==0)
{
clearing.clearingType = 6;
clearing.clearingPrice = getClearingPriceDemandZero();
}else if(clearing.clearingQuantity < consumptionBids[getPriceCap()]){
clearing.clearingType = 5;
clearing.clearingPrice = getPriceCap();
}else if(clearing.clearingQuantity < generationBids[-getPriceCap()]){
clearing. clearingType = 5;
clearing.clearingPrice = -getPriceCap();
}else if(clearing.clearingQuantity == consumptionBids[getPriceCap()] && clearing.clearingQuantity == generationBids[-getPriceCap()]){
clearing.clearingType = 3;
clearing.clearingPrice = 0;
}
}else{
clearing.clearingPrice = getClearingPriceOneLengthZero();
clearing.clearingQuantity = 0;
clearing.clearingType = 6;
}
for (uint cleanConsumptionIndex = 0; cleanConsumptionIndex < _consumptionPrices.length; cleanConsumptionIndex++){
int consPrice = _consumptionPrices[cleanConsumptionIndex];
consumptionBids[consPrice] = 0;
}
for (uint cleanGenerationIndex = 0; cleanGenerationIndex < _generationPrices.length; cleanGenerationIndex++){
int genPrice = _generationPrices[cleanGenerationIndex];
generationBids[genPrice] = 0;
}
delete _consumptionPrices;
delete _generationPrices;
_consumptionPrices.length = 0;
_generationPrices.length = 0;
}
function getClearingPriceOneLengthZero() view private returns(int){
if( _generationPrices.length > 0 && _consumptionPrices.length == 0){
return _generationPrices[0]-1;
}else if( _generationPrices.length == 0 && _consumptionPrices.length > 0){
return _consumptionPrices[0]+1;
}else if( _generationPrices.length > 0 && _consumptionPrices.length > 0){
return _generationPrices[0] + (_consumptionPrices[0] - _generationPrices[0]) / 2;
}else if( _generationPrices.length == 0 && _consumptionPrices.length == 0){
return 0;
}
}
function getClearingPriceDemandZero() view private returns(int){
if(_generationPrices.length > 0 && _consumptionPrices.length == 0){
return _generationPrices[0]-1;
} else if(_generationPrices.length == 0 && _consumptionPrices.length > 0){
return _consumptionPrices[0]+1;
} else {
if(_generationPrices[0] == getPriceCap()){
return _consumptionPrices[0]+1;
} else if (_consumptionPrices[0] == -getPriceCap()){
return _generationPrices[0]-1;
} else {
return _generationPrices[0] + (_consumptionPrices[0] - _generationPrices[0]) / 2;
}
}
}
function getClearingPrice() view public returns(int){
return(clearing.clearingPrice);
}
function getClearingQuantity() view public returns(int){
return(clearing.clearingQuantity);
}
function getClearingType() view public returns(int){
return(clearing.clearingType);
}
function getGenerationsLength() view public returns(uint){
return(_generationPrices.length);
}
function getConsumptionsLength() view public returns(uint){
return(_consumptionPrices.length);
}
function deleteMapArrays() public{
for (uint cleanConsumptionIndex = 0; cleanConsumptionIndex < _consumptionPrices.length; cleanConsumptionIndex++){
int consPrice = _consumptionPrices[cleanConsumptionIndex];
consumptionBids[consPrice] = 0;
}
for (uint cleanGenerationIndex = 0; cleanGenerationIndex < _generationPrices.length; cleanGenerationIndex++){
int genPrice = _generationPrices[cleanGenerationIndex];
generationBids[genPrice] = 0;
}
delete _consumptionPrices;
delete _generationPrices;
_consumptionPrices.length = 0;
_generationPrices.length = 0;
}
}
| sort arrays, consumer's bid descending, producer's ascending sell price increased ~ marginal buyer since all sellers satisfied buy price increased ~ marginal seller since all buyers satisfied possible when a == b, q_buy == q_sell, and either the buyers or sellers are exhausted needs to be just off such that it does not trigger any other bidsclearing.clearingPrice = getClearingPriceType3(i, j, a, b, buy, sell); | function computeClearing() private{
bool check = false;
int a = getPriceCap();
int b = -getPriceCap();
int demand_quantity = 0;
int supply_quantity = 0;
int buy_quantity = 0;
int sell_quantity = 0;
uint i = 0;
uint j = 0;
if (_consumptionPrices.length != 0){
quickSortDescending(_consumptionPrices, 0, int(_consumptionPrices.length - 1));
}
if (_generationPrices.length != 0){
quickSortAscending(_generationPrices, 0, int(_generationPrices.length - 1));
}
if(_consumptionPrices.length > 0 && _generationPrices.length > 0){
Bid memory buy = Bid({
quantity: consumptionBids[_consumptionPrices[i]],
price: _consumptionPrices[i]
});
Bid memory sell = Bid({
quantity: generationBids[_generationPrices[j]],
price: _generationPrices[j]
});
clearing.clearingType = 6;
while(i<_consumptionPrices.length && j<_generationPrices.length && buy.price>=sell.price){
buy_quantity = demand_quantity + buy.quantity;
sell_quantity = supply_quantity + sell.quantity;
if (buy_quantity > sell_quantity){
supply_quantity = sell_quantity;
clearing.clearingQuantity = sell_quantity;
b = buy.price;
a = buy.price;
++j;
if(j < _generationPrices.length){
sell.price = _generationPrices[j];
sell.quantity = generationBids[_generationPrices[j]];
}
check = false;
clearing.clearingType = 2;
}
else if (buy_quantity < sell_quantity){
demand_quantity = buy_quantity;
clearing.clearingQuantity = buy_quantity;
b = sell.price;
a = sell.price;
i++;
if(i < _consumptionPrices.length){
buy.price = _consumptionPrices[i];
buy.quantity = consumptionBids[_consumptionPrices[i]];
}
check = false;
clearing.clearingType = 1;
}
else{
supply_quantity = buy_quantity;
demand_quantity = buy_quantity;
clearing.clearingQuantity = buy_quantity;
a = buy.price;
b = sell.price;
i++;
j++;
if(i < _consumptionPrices.length){
buy.price = _consumptionPrices[i];
buy.quantity = consumptionBids[_consumptionPrices[i]];
}
if(j < _generationPrices.length){
sell.price = _generationPrices[j];
sell.quantity = generationBids[_generationPrices[j]];
}
check = true;
}
}
if(a == b){
clearing.clearingPrice = a;
}
if(check){ /* there was price agreement or quantity disagreement */
clearing.clearingPrice = a;
if(supply_quantity == demand_quantity){
if(i == _consumptionPrices.length || j == _generationPrices.length){
if(a == b){
clearing.clearingType = 4;
clearing.clearingType = 3;
}
clearing.clearingType = 1;
clearing.clearingType = 2;
if(a == b){
clearing.clearingType = 4;
clearing.clearingType = 3;
}
}
if(a != buy.price && b != sell.price && a == b){
clearing.clearingType = 2;
clearing.clearingType = 1;
if(i == _consumptionPrices.length && j == _generationPrices.length){
clearing.clearingType = 4;
clearing.clearingType = 1;
clearing.clearingType = 2;
}
}
}
}
if(clearing.clearingType == 3){
if(a == getPriceCap() && b != -getPriceCap()){
if(buy.price > b){
clearing.clearingPrice = buy.price + 1;
clearing.clearingPrice = b;
}
if(sell.price < a){
clearing.clearingPrice = sell.price - 1;
clearing.clearingPrice = a;
}
if(i == _consumptionPrices.length && j == _generationPrices.length){
clearing.clearingPrice = buy.price + 1;
clearing.clearingPrice = sell.price - 1;
if(i==_consumptionPrices.length){
if(j==_generationPrices.length){
clearing.clearingPrice = getAvg(a, b);
clearing.clearingPrice = getAvg(a, sell.price);
}
if(j==_generationPrices.length){
clearing.clearingPrice = getAvg(buy.price, b);
clearing.clearingPrice = getAvg(buy.price, sell.price);
}
}
}
if(i != _consumptionPrices.length && buy.price == a){
clearing.clearingPrice = a;
clearing.clearingPrice = b;
if(i==_consumptionPrices.length){
clearing.clearingPrice = a + 1;
clearing.clearingPrice = buy.price + 1;
}
if(j==_generationPrices.length){
clearing.clearingPrice = b - 1;
clearing.clearingPrice = sell.price - 1;
}
clearing.clearingPrice = getAvg(a, b);
}
}
}
}
{
clearing.clearingType = 6;
clearing.clearingPrice = getClearingPriceDemandZero();
clearing.clearingType = 5;
clearing.clearingPrice = getPriceCap();
clearing. clearingType = 5;
clearing.clearingPrice = -getPriceCap();
clearing.clearingType = 3;
clearing.clearingPrice = 0;
}
clearing.clearingPrice = getClearingPriceOneLengthZero();
clearing.clearingQuantity = 0;
clearing.clearingType = 6;
}
| 6,436,628 |
./full_match/1/0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74/sources/lib/safe/contracts/handler/extensible/TokenCallbacks.sol | Handles ERC721 Token callback. return Standardized onERC721Received return value./ Else return the standard value | function onERC721Received(address, address, uint256, bytes calldata) external pure override returns (bytes4) {
return 0x150b7a02;
}
| 3,132,925 |
./partial_match/42/0x3c5406ddCE4836eA2E5817DCF021fE1E9B0796cC/sources/GebProxyIncentivesActions.sol | Withdraw LP tokens from liquidity mining pool incentives address - Liquidity mining pool value uint - value to withdraw | function withdrawFromMine(address incentives, uint value) external {
GebIncentivesLike incentivesContract = GebIncentivesLike(incentives);
DSTokenLike lpToken = DSTokenLike(incentivesContract.stakingToken());
incentivesContract.withdraw(value);
lpToken.transfer(msg.sender, lpToken.balanceOf(address(this)));
}
| 3,422,539 |
pragma solidity ^0.4.19;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract Owned {
address public owner;
address public proposedOwner = address(0);
event OwnershipTransferInitiated(address indexed _proposedOwner);
event OwnershipTransferCompleted(address indexed _newOwner);
event OwnershipTransferCanceled();
function Owned() public
{
owner = msg.sender;
}
modifier onlyOwner() {
require(isOwner(msg.sender));
_;
}
function isOwner(address _address) public view returns (bool) {
return (_address == owner);
}
function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) {
require(_proposedOwner != address(0));
require(_proposedOwner != address(this));
require(_proposedOwner != owner);
proposedOwner = _proposedOwner;
OwnershipTransferInitiated(proposedOwner);
return true;
}
function cancelOwnershipTransfer() public onlyOwner returns (bool) {
//if proposedOwner address already address(0) then it will return true.
if (proposedOwner == address(0)) {
return true;
}
//if not then first it will do address(0( then it will return true.
proposedOwner = address(0);
OwnershipTransferCanceled();
return true;
}
function completeOwnershipTransfer() public returns (bool) {
require(msg.sender == proposedOwner);
owner = msg.sender;
proposedOwner = address(0);
OwnershipTransferCompleted(owner);
return true;
}
}
contract TokenTransfer {
// minimal subset of ERC20
function transfer(address _to, uint256 _value) public returns (bool success);
function decimals() public view returns (uint8 tokenDecimals);
function balanceOf(address _owner) public view returns (uint256 balance);
}
contract FlexibleTokenSale is Owned {
using SafeMath for uint256;
//
// Lifecycle
//
bool public suspended;
//
// Pricing
//
uint256 public tokenPrice;
uint256 public tokenPerEther;
uint256 public contributionMin;
uint256 public tokenConversionFactor;
//
// Wallets
//
address public walletAddress;
//
// Token
//
TokenTransfer token;
//
// Counters
//
uint256 public totalTokensSold;
uint256 public totalEtherCollected;
//
// Price Update Address
//
address public priceUpdateAddress;
//
// Events
//
event Initialized();
event TokenPriceUpdated(uint256 _newValue);
event TokenPerEtherUpdated(uint256 _newValue);
event TokenMinUpdated(uint256 _newValue);
event WalletAddressUpdated(address indexed _newAddress);
event SaleSuspended();
event SaleResumed();
event TokensPurchased(address indexed _beneficiary, uint256 _cost, uint256 _tokens);
event TokensReclaimed(uint256 _amount);
event PriceAddressUpdated(address indexed _newAddress);
function FlexibleTokenSale(address _tokenAddress,address _walletAddress,uint _tokenPerEther,address _priceUpdateAddress) public
Owned()
{
require(_walletAddress != address(0));
require(_walletAddress != address(this));
require(address(token) == address(0));
require(address(_tokenAddress) != address(0));
require(address(_tokenAddress) != address(this));
require(address(_tokenAddress) != address(walletAddress));
walletAddress = _walletAddress;
priceUpdateAddress = _priceUpdateAddress;
token = TokenTransfer(_tokenAddress);
suspended = false;
tokenPrice = 100;
tokenPerEther = _tokenPerEther;
contributionMin = 5 * 10**18;//minimum 5 DOC token
totalTokensSold = 0;
totalEtherCollected = 0;
// This factor is used when converting cost <-> tokens.
// 18 is because of the ETH -> Wei conversion.
// 2 because toekn price and etherPerToken Price are expressed as 100 for $1.00 and 100000 for $1000.00 (with 2 decimals).
tokenConversionFactor = 10**(uint256(18).sub(token.decimals()).add(2));
assert(tokenConversionFactor > 0);
}
//
// Owner Configuation
//
// Allows the owner to change the wallet address which is used for collecting
// ether received during the token sale.
function setWalletAddress(address _walletAddress) external onlyOwner returns(bool) {
require(_walletAddress != address(0));
require(_walletAddress != address(this));
require(_walletAddress != address(token));
require(isOwner(_walletAddress) == false);
walletAddress = _walletAddress;
WalletAddressUpdated(_walletAddress);
return true;
}
//set token price in between $1 to $1000, pass 111 for $1.11, 100000 for $1000
function setTokenPrice(uint _tokenPrice) external onlyOwner returns (bool) {
require(_tokenPrice >= 100 && _tokenPrice <= 100000);
tokenPrice=_tokenPrice;
TokenPriceUpdated(_tokenPrice);
return true;
}
function setMinToken(uint256 _minToken) external onlyOwner returns(bool) {
require(_minToken > 0);
contributionMin = _minToken;
TokenMinUpdated(_minToken);
return true;
}
// Allows the owner to suspend the sale until it is manually resumed at a later time.
function suspend() external onlyOwner returns(bool) {
if (suspended == true) {
return false;
}
suspended = true;
SaleSuspended();
return true;
}
// Allows the owner to resume the sale.
function resume() external onlyOwner returns(bool) {
if (suspended == false) {
return false;
}
suspended = false;
SaleResumed();
return true;
}
//
// Contributions
//
// Default payable function which can be used to purchase tokens.
function () payable public {
buyTokens(msg.sender);
}
// Allows the caller to purchase tokens for a specific beneficiary (proxy purchase).
function buyTokens(address _beneficiary) public payable returns (uint256) {
require(!suspended);
require(address(token) != address(0));
require(_beneficiary != address(0));
require(_beneficiary != address(this));
require(_beneficiary != address(token));
// We don't want to allow the wallet collecting ETH to
// directly be used to purchase tokens.
require(msg.sender != address(walletAddress));
// Check how many tokens are still available for sale.
uint256 saleBalance = token.balanceOf(address(this));
assert(saleBalance > 0);
return buyTokensInternal(_beneficiary);
}
function updateTokenPerEther(uint _etherPrice) public returns(bool){
require(_etherPrice > 0);
require(msg.sender == priceUpdateAddress || msg.sender == owner);
tokenPerEther=_etherPrice;
TokenPerEtherUpdated(_etherPrice);
return true;
}
function updatePriceAddress(address _newAddress) public onlyOwner returns(bool){
require(_newAddress != address(0));
priceUpdateAddress=_newAddress;
PriceAddressUpdated(_newAddress);
return true;
}
function buyTokensInternal(address _beneficiary) internal returns (uint256) {
// Calculate how many tokens the contributor could purchase based on ETH received.
uint256 tokens =msg.value.mul(tokenPerEther.mul(100).div(tokenPrice)).div(tokenConversionFactor);
require(tokens >= contributionMin);
// This is the actual amount of ETH that can be sent to the wallet.
uint256 contribution =msg.value;
walletAddress.transfer(contribution);
totalEtherCollected = totalEtherCollected.add(contribution);
// Update our stats counters.
totalTokensSold = totalTokensSold.add(tokens);
// Transfer tokens to the beneficiary.
require(token.transfer(_beneficiary, tokens));
TokensPurchased(_beneficiary, msg.value, tokens);
return tokens;
}
// Allows the owner to take back the tokens that are assigned to the sale contract.
function reclaimTokens() external onlyOwner returns (bool) {
uint256 tokens = token.balanceOf(address(this));
if (tokens == 0) {
return false;
}
require(token.transfer(owner, tokens));
TokensReclaimed(tokens);
return true;
}
}
contract DOCTokenSaleConfig {
address WALLET_ADDRESS = 0xcd6b3d0c0dd850bad071cd20e428940d2e25120f;
address TOKEN_ADDRESS = 0x39a87Dc12a7199AA012c18F114B763e27D0decA4;
address UPDATE_PRICE_ADDRESS = 0x0fb285cae5dccddb4f8ea252a16876dd3dfb0f52;
uint ETHER_PRICE = 100000;//set current ether price. if current price 1000.00 then write 100000
}
contract DOCTokenSale is FlexibleTokenSale, DOCTokenSaleConfig {
function DOCTokenSale() public
FlexibleTokenSale(TOKEN_ADDRESS,WALLET_ADDRESS,ETHER_PRICE,UPDATE_PRICE_ADDRESS)
{
}
} | Allows the owner to change the wallet address which is used for collecting ether received during the token sale. | function setWalletAddress(address _walletAddress) external onlyOwner returns(bool) {
require(_walletAddress != address(0));
require(_walletAddress != address(this));
require(_walletAddress != address(token));
require(isOwner(_walletAddress) == false);
walletAddress = _walletAddress;
WalletAddressUpdated(_walletAddress);
return true;
}
| 6,518,404 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/IMigrator.sol";
import "./Checkpoints.sol";
// Note that LPMining is ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract
// and the community can show to govern itself.
contract LPMining is Ownable, Checkpoints {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of CVPs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCvpPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accCvpPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CVPs to distribute per block.
uint256 lastRewardBlock; // Last block number that CVPs distribution occurs.
uint256 accCvpPerShare; // Accumulated CVPs per share, times 1e12. See below.
bool votesEnabled; // Pool enabled to write votes
uint8 poolType; // Pool type (1 For Uniswap, 2 for Balancer)
}
// The CVP TOKEN!
IERC20 public cvp;
// Reservoir address.
address public reservoir;
// CVP tokens reward per block.
uint256 public cvpPerBlock;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigrator public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Pid of each pool by its address
mapping(address => uint256) public poolPidByAddress;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when CVP powerindex-mining starts.
uint256 public startBlock;
event AddLpToken(address indexed lpToken, uint256 indexed pid, uint256 allocPoint);
event SetLpToken(address indexed lpToken, uint256 indexed pid, uint256 allocPoint);
event SetMigrator(address indexed migrator);
event SetCvpPerBlock(uint256 cvpPerBlock);
event MigrateLpToken(address indexed oldLpToken, address indexed newLpToken, uint256 indexed pid);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event CheckpointPoolVotes(address indexed user, uint256 indexed pid, uint256 votes, uint256 price);
event CheckpointTotalVotes(address indexed user, uint256 votes);
constructor(
IERC20 _cvp,
address _reservoir,
uint256 _cvpPerBlock,
uint256 _startBlock
) public {
cvp = _cvp;
reservoir = _reservoir;
cvpPerBlock = _cvpPerBlock;
startBlock = _startBlock;
emit SetCvpPerBlock(_cvpPerBlock);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
uint8 _poolType,
bool _votesEnabled
) public onlyOwner {
require(!isLpTokenAdded(_lpToken), "add: Lp token already added");
massUpdatePools();
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
uint256 pid = poolInfo.length;
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCvpPerShare: 0,
votesEnabled: _votesEnabled,
poolType: _poolType
})
);
poolPidByAddress[address(_lpToken)] = pid;
emit AddLpToken(address(_lpToken), pid, _allocPoint);
}
// Update the given pool's CVP allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
uint8 _poolType,
bool _votesEnabled
) public onlyOwner {
massUpdatePools();
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].votesEnabled = _votesEnabled;
poolInfo[_pid].poolType = _poolType;
emit SetLpToken(address(poolInfo[_pid].lpToken), _pid, _allocPoint);
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigrator _migrator) public onlyOwner {
migrator = _migrator;
emit SetMigrator(address(_migrator));
}
// Set CVP reward per block. Can only be called by the owner.
function setCvpPerBlock(uint256 _cvpPerBlock) public onlyOwner {
cvpPerBlock = _cvpPerBlock;
emit SetCvpPerBlock(_cvpPerBlock);
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken, pool.poolType);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
delete poolPidByAddress[address(lpToken)];
poolPidByAddress[address(newLpToken)] = _pid;
emit MigrateLpToken(address(lpToken), address(newLpToken), _pid);
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
return _to.sub(_from);
}
// View function to see pending CVPs on frontend.
function pendingCvp(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCvpPerShare = pool.accCvpPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cvpReward = multiplier.mul(cvpPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCvpPerShare = accCvpPerShare.add(cvpReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCvpPerShare).div(1e12).sub(user.rewardDebt);
}
// Return bool - is Lp Token added or not
function isLpTokenAdded(IERC20 _lpToken) public view returns (bool) {
uint256 pid = poolPidByAddress[address(_lpToken)];
return poolInfo.length > pid && address(poolInfo[pid].lpToken) == address(_lpToken);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cvpReward = multiplier.mul(cvpPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
cvp.transferFrom(reservoir, address(this), cvpReward);
pool.accCvpPerShare = pool.accCvpPerShare.add(cvpReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to LPMining for CVP allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCvpPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeCvpTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCvpPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
checkpointVotes(msg.sender);
}
// Withdraw LP tokens from LPMining.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCvpPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeCvpTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCvpPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
checkpointVotes(msg.sender);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
checkpointVotes(msg.sender);
}
// Write votes at current block
function checkpointVotes(address _user) public {
uint256 length = poolInfo.length;
uint256 totalVotesBalance = 0;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
uint256 userLpTokenBalance = userInfo[pid][_user].amount;
if (userLpTokenBalance == 0 || !pool.votesEnabled) {
continue;
}
uint256 lpTokenTotalSupply = pool.lpToken.totalSupply();
if (lpTokenTotalSupply == 0) {
continue;
}
uint256 lpCvpBalance = cvp.balanceOf(address(pool.lpToken));
uint256 lpCvpPrice = lpCvpBalance.mul(1e12).div(lpTokenTotalSupply);
uint256 lpVotesBalance = userLpTokenBalance.mul(lpCvpPrice).div(1e12);
totalVotesBalance = totalVotesBalance.add(lpVotesBalance);
emit CheckpointPoolVotes(_user, pid, lpVotesBalance, lpCvpPrice);
}
emit CheckpointTotalVotes(_user, totalVotesBalance);
_writeBalance(_user, safe96(totalVotesBalance, "LPMining::checkpointVotes: Amount overflow"));
}
// Safe cvp transfer function, just in case if rounding error causes pool to not have enough CVPs.
function safeCvpTransfer(address _to, uint256 _amount) internal {
uint256 cvpBal = cvp.balanceOf(address(this));
if (_amount > cvpBal) {
cvp.transfer(_to, cvpBal);
} else {
cvp.transfer(_to, _amount);
}
}
}
| View function to see pending CVPs on frontend. | function pendingCvp(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCvpPerShare = pool.accCvpPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cvpReward = multiplier.mul(cvpPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCvpPerShare = accCvpPerShare.add(cvpReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCvpPerShare).div(1e12).sub(user.rewardDebt);
}
| 14,088,781 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./WhiteRabbitProducerPass.sol";
contract WhiteRabbit is Ownable, ERC1155Holder {
using Strings for uint256;
using SafeMath for uint256;
// The Producer Pass contract used for staking/voting on episodes
WhiteRabbitProducerPass private whiteRabbitProducerPass;
// The total number of episodes that make up the film
uint256 private _numberOfEpisodes;
// A mapping from episodeId to whether or not voting is enabled
mapping(uint256 => bool) public votingEnabledForEpisode;
// The address of the White Rabbit token ($WRAB)
address public whiteRabbitTokenAddress;
// The initial fixed supply of White Rabbit tokens
uint256 public tokenInitialFixedSupply;
// The wallet addresses of the two artists creating the film
address private _artist1Address;
address private _artist2Address;
// The percentage of White Rabbit tokens that will go to the artists
uint256 public artistTokenAllocationPercentage;
// The number of White Rabbit tokens to send to each artist per episode
uint256 public artistTokenPerEpisodePerArtist;
// A mapping from episodeId to a boolean indicating whether or not
// White Rabbit tokens have been transferred the artists yet
mapping(uint256 => bool) public hasTransferredTokensToArtistForEpisode;
// The percentage of White Rabbit tokens that will go to producers (via Producer Pass staking)
uint256 public producersTokenAllocationPercentage;
// The number of White Rabbit tokens to send to producers per episode
uint256 public producerPassTokenAllocationPerEpisode;
// The base number of White Rabbit tokens to allocate to producers per episode
uint256 public producerPassTokenBaseAllocationPerEpisode;
// The number of White Rabbit tokens to allocate to producers who stake early
uint256 public producerPassTokenEarlyStakingBonusAllocationPerEpisode;
// The number of White Rabbit tokens to allocate to producers who stake for the winning option
uint256 public producerPassTokenWinningBonusAllocationPerEpisode;
// The percentage of White Rabbit tokens that will go to the platform team
uint256 public teamTokenAllocationPercentage;
// Whether or not the team has received its share of White Rabbit tokens
bool public teamTokenAllocationDistributed;
// Event emitted when a Producer Pass is staked to vote for an episode option
event ProducerPassStaked(
address indexed account,
uint256 episodeId,
uint256 voteId,
uint256 amount,
uint256 tokenAmount
);
// Event emitted when a Producer Pass is unstaked after voting is complete
event ProducerPassUnstaked(
address indexed account,
uint256 episodeId,
uint256 voteId,
uint256 tokenAmount
);
// The list of episode IDs (e.g. [1, 2, 3, 4])
uint256[] public episodes;
// The voting option IDs by episodeId (e.g. 1 => [1, 2])
mapping(uint256 => uint256[]) private _episodeOptions;
// The total vote counts for each episode voting option, agnostic of users
// _episodeVotesByOptionId[episodeId][voteOptionId] => number of votes
mapping(uint256 => mapping(uint256 => uint256))
private _episodeVotesByOptionId;
// A mapping from episodeId to the winning vote option
// 0 means no winner has been declared yet
mapping(uint256 => uint256) public winningVoteOptionByEpisode;
// A mapping of how many Producer Passes have been staked per user per episode per option
// e.g. _usersStakedEpisodeVotingOptionsCount[address][episodeId][voteOptionId] => number staked
// These values will be updated/decremented when Producer Passes are unstaked
mapping(address => mapping(uint256 => mapping(uint256 => uint256)))
private _usersStakedEpisodeVotingOptionsCount;
// A mapping of the *history* how many Producer Passes have been staked per user per episode per option
// e.g. _usersStakedEpisodeVotingHistoryCount[address][episodeId][voteOptionId] => number staked
// Note: These values DO NOT change after Producer Passes are unstaked
mapping(address => mapping(uint256 => mapping(uint256 => uint256)))
private _usersStakedEpisodeVotingHistoryCount;
// The base URI for episode metadata
string private _episodeBaseURI;
// The base URI for episode voting option metadata
string private _episodeOptionBaseURI;
/**
* @dev Initializes the contract by setting up the Producer Pass contract to be used
*/
constructor(address whiteRabbitProducerPassContract) {
whiteRabbitProducerPass = WhiteRabbitProducerPass(
whiteRabbitProducerPassContract
);
}
/**
* @dev Sets the Producer Pass contract to be used
*/
function setWhiteRabbitProducerPassContract(
address whiteRabbitProducerPassContract
) external onlyOwner {
whiteRabbitProducerPass = WhiteRabbitProducerPass(
whiteRabbitProducerPassContract
);
}
/**
* @dev Sets the base URI for episode metadata
*/
function setEpisodeBaseURI(string memory baseURI) external onlyOwner {
_episodeBaseURI = baseURI;
}
/**
* @dev Sets the base URI for episode voting option metadata
*/
function setEpisodeOptionBaseURI(string memory baseURI) external onlyOwner {
_episodeOptionBaseURI = baseURI;
}
/**
* @dev Sets the list of episode IDs (e.g. [1, 2, 3, 4])
*
* This will be updated every time a new episode is added.
*/
function setEpisodes(uint256[] calldata _episodes) external onlyOwner {
episodes = _episodes;
}
/**
* @dev Sets the voting option IDs for a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function setEpisodeOptions(
uint256 episodeId,
uint256[] calldata episodeOptionIds
) external onlyOwner {
require(episodeId <= episodes.length, "Episode does not exist");
_episodeOptions[episodeId] = episodeOptionIds;
}
/**
* @dev Retrieves the voting option IDs for a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function getEpisodeOptions(uint256 episodeId)
public
view
returns (uint256[] memory)
{
require(episodeId <= episodes.length, "Episode does not exist");
return _episodeOptions[episodeId];
}
/**
* @dev Retrieves the number of episodes currently available.
*/
function getCurrentEpisodeCount() external view returns (uint256) {
return episodes.length;
}
/**
* @dev Constructs the metadata URI for a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function episodeURI(uint256 episodeId)
public
view
virtual
returns (string memory)
{
require(episodeId <= episodes.length, "Episode does not exist");
string memory baseURI = episodeBaseURI();
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(baseURI, episodeId.toString(), ".json")
)
: "";
}
/**
* @dev Constructs the metadata URI for a given episode voting option.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - The episode voting option ID is valid
*/
function episodeOptionURI(uint256 episodeId, uint256 episodeOptionId)
public
view
virtual
returns (string memory)
{
// TODO: DRY up these requirements? ("Episode does not exist", "Invalid voting option")
require(episodeId <= episodes.length, "Episode does not exist");
string memory baseURI = episodeOptionBaseURI();
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(
_episodeOptionBaseURI,
episodeId.toString(),
"/",
episodeOptionId.toString(),
".json"
)
)
: "";
}
/**
* @dev Getter for the `_episodeBaseURI`
*/
function episodeBaseURI() internal view virtual returns (string memory) {
return _episodeBaseURI;
}
/**
* @dev Getter for the `_episodeOptionBaseURI`
*/
function episodeOptionBaseURI()
internal
view
virtual
returns (string memory)
{
return _episodeOptionBaseURI;
}
/**
* @dev Retrieves the voting results for a given episode's voting option ID
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is no longer enabled for the given episode
* - Voting has completed and a winning option has been declared
*/
function episodeVotes(uint256 episodeId, uint256 episodeOptionId)
public
view
virtual
returns (uint256)
{
require(episodeId <= episodes.length, "Episode does not exist");
require(!votingEnabledForEpisode[episodeId], "Voting is still enabled");
require(
winningVoteOptionByEpisode[episodeId] > 0,
"Voting not finished"
);
return _episodeVotesByOptionId[episodeId][episodeOptionId];
}
/**
* @dev Retrieves the number of Producer Passes that the user has staked
* for a given episode and voting option at this point in time.
*
* Note that this number will change after a user has unstaked.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function userStakedProducerPassCount(
uint256 episodeId,
uint256 episodeOptionId
) public view virtual returns (uint256) {
require(episodeId <= episodes.length, "Episode does not exist");
return
_usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][
episodeOptionId
];
}
/**
* @dev Retrieves the historical number of Producer Passes that the user
* has staked for a given episode and voting option.
*
* Note that this number will not change as a result of unstaking.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function userStakedProducerPassCountHistory(
uint256 episodeId,
uint256 episodeOptionId
) public view virtual returns (uint256) {
require(episodeId <= episodes.length, "Episode does not exist");
return
_usersStakedEpisodeVotingHistoryCount[msg.sender][episodeId][
episodeOptionId
];
}
/**
* @dev Stakes Producer Passes for the given episode's voting option ID,
* with the ability to specify an `amount`. Staking is used to vote for the option
* that the user would like to see producers for the next episode.
*
* Emits a `ProducerPassStaked` event indicating that the staking was successful,
* including the total number of White Rabbit tokens allocated as a result.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is enabled for the given episode
* - The user is attempting to stake more than zero Producer Passes
* - The user has enough Producer Passes to stake
* - The episode voting option is valid
* - A winning option hasn't been declared yet
*/
function stakeProducerPass(
uint256 episodeId,
uint256 voteOptionId,
uint256 amount
) public {
require(episodeId <= episodes.length, "Episode does not exist");
require(votingEnabledForEpisode[episodeId], "Voting not enabled");
require(amount > 0, "Cannot stake 0");
require(
whiteRabbitProducerPass.balanceOf(msg.sender, episodeId) >= amount,
"Insufficient pass balance"
);
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
// vote options should be [1, 2], ID <= length
require(
votingOptionsForThisEpisode.length >= voteOptionId,
"Invalid voting option"
);
uint256 winningVoteOptionId = winningVoteOptionByEpisode[episodeId];
// rely on winningVoteOptionId to determine that this episode is valid for voting on
require(winningVoteOptionId == 0, "Winner already declared");
// user's vote count for selected episode & option
uint256 userCurrentVoteCount = _usersStakedEpisodeVotingOptionsCount[
msg.sender
][episodeId][voteOptionId];
// Get total vote count of this option user is voting/staking for
uint256 currentTotalVoteCount = _episodeVotesByOptionId[episodeId][
voteOptionId
];
// Get total vote count from every option of this episode for bonding curve calculation
uint256 totalVotesForEpisode = 0;
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentVotingOptionId = votingOptionsForThisEpisode[i];
totalVotesForEpisode += _episodeVotesByOptionId[episodeId][
currentVotingOptionId
];
}
// calculate token rewards here
uint256 tokensAllocated = getTokenAllocationForUserBeforeStaking(
episodeId,
amount
);
uint256 userNewVoteCount = userCurrentVoteCount + amount;
_usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][
voteOptionId
] = userNewVoteCount;
_usersStakedEpisodeVotingHistoryCount[msg.sender][episodeId][
voteOptionId
] = userNewVoteCount;
_episodeVotesByOptionId[episodeId][voteOptionId] =
currentTotalVoteCount +
amount;
// Take custody of producer passes from user
whiteRabbitProducerPass.safeTransferFrom(
msg.sender,
address(this),
episodeId,
amount,
""
);
// Distribute wr tokens to user
IERC20(whiteRabbitTokenAddress).transfer(msg.sender, tokensAllocated);
emit ProducerPassStaked(
msg.sender,
episodeId,
voteOptionId,
amount,
tokensAllocated
);
}
/**
* @dev Unstakes Producer Passes for the given episode's voting option ID and
* sends White Rabbit tokens to the user's wallet if they staked for the winning side.
*
*
* Emits a `ProducerPassUnstaked` event indicating that the unstaking was successful,
* including the total number of White Rabbit tokens allocated as a result.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is not enabled for the given episode
* - The episode voting option is valid
* - A winning option has been declared
*/
function unstakeProducerPasses(uint256 episodeId, uint256 voteOptionId)
public
{
require(!votingEnabledForEpisode[episodeId], "Voting is still enabled");
uint256 stakedProducerPassCount = _usersStakedEpisodeVotingOptionsCount[
msg.sender
][episodeId][voteOptionId];
require(stakedProducerPassCount > 0, "No producer passes staked");
uint256 winningBonus = getUserWinningBonus(episodeId, voteOptionId) *
stakedProducerPassCount;
_usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][
voteOptionId
] = 0;
if (winningBonus > 0) {
IERC20(whiteRabbitTokenAddress).transfer(msg.sender, winningBonus);
}
whiteRabbitProducerPass.safeTransferFrom(
address(this),
msg.sender,
episodeId,
stakedProducerPassCount,
""
);
emit ProducerPassUnstaked(
msg.sender,
episodeId,
voteOptionId,
winningBonus
);
}
/**
* @dev Calculates the number of White Rabbit tokens to award the user for unstaking
* their Producer Passes for a given episode's voting option ID.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - Voting is not enabled for the given episode
* - The episode voting option is valid
* - A winning option has been declared
*/
function getUserWinningBonus(uint256 episodeId, uint256 episodeOptionId)
public
view
returns (uint256)
{
uint256 winningVoteOptionId = winningVoteOptionByEpisode[episodeId];
require(winningVoteOptionId > 0, "Voting is not finished");
require(!votingEnabledForEpisode[episodeId], "Voting is still enabled");
bool isWinningOption = winningVoteOptionId == episodeOptionId;
uint256 numberOfWinningVotes = _episodeVotesByOptionId[episodeId][
episodeOptionId
];
uint256 winningBonus = 0;
if (isWinningOption && numberOfWinningVotes > 0) {
winningBonus =
producerPassTokenWinningBonusAllocationPerEpisode /
numberOfWinningVotes;
}
return winningBonus;
}
/**
* @dev This method is only for the owner since we want to hide the voting results from the public
* until after voting has ended. Users can verify the veracity of this via the `episodeVotes` method
* which can be called publicly after voting has finished for an episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function getTotalVotesForEpisode(uint256 episodeId)
external
view
onlyOwner
returns (uint256[] memory)
{
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
uint256[] memory totalVotes = new uint256[](
votingOptionsForThisEpisode.length
);
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentVotingOptionId = votingOptionsForThisEpisode[i];
uint256 votesForEpisode = _episodeVotesByOptionId[episodeId][
currentVotingOptionId
];
totalVotes[i] = votesForEpisode;
}
return totalVotes;
}
/**
* @dev Owner method to toggle the voting state of a given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
* - The voting state is different than the current state
* - A winning option has not yet been declared
*/
function setVotingEnabledForEpisode(uint256 episodeId, bool enabled)
public
onlyOwner
{
require(episodeId <= episodes.length, "Episode does not exist");
require(
votingEnabledForEpisode[episodeId] != enabled,
"Voting state unchanged"
);
// if winner already set, don't allow re-opening of voting
if (enabled) {
require(
winningVoteOptionByEpisode[episodeId] == 0,
"Winner for episode already set"
);
}
votingEnabledForEpisode[episodeId] = enabled;
}
/**
* @dev Sets up the distribution parameters for White Rabbit (WRAB) tokens.
*
* - We will create fractionalized NFT basket first, which will represent the finished film NFT
* - Tokens will be stored on platform and distributed to artists and producers as the film progresses
* - Artist distribution happens when new episodes are uploaded
* - Producer distribution happens when Producer Passes are staked and unstaked (with a bonus for winning the vote)
*
* Requirements:
*
* - The allocation percentages do not exceed 100%
*/
function startWhiteRabbitShowWithParams(
address tokenAddress,
address artist1Address,
address artist2Address,
uint256 numberOfEpisodes,
uint256 producersAllocationPercentage,
uint256 artistAllocationPercentage,
uint256 teamAllocationPercentage
) external onlyOwner {
require(
(producersAllocationPercentage +
artistAllocationPercentage +
teamAllocationPercentage) <= 100,
"Total percentage exceeds 100"
);
whiteRabbitTokenAddress = tokenAddress;
tokenInitialFixedSupply = IERC20(whiteRabbitTokenAddress).totalSupply();
_artist1Address = artist1Address;
_artist2Address = artist2Address;
_numberOfEpisodes = numberOfEpisodes;
producersTokenAllocationPercentage = producersAllocationPercentage;
artistTokenAllocationPercentage = artistAllocationPercentage;
teamTokenAllocationPercentage = teamAllocationPercentage;
// If total supply is 1000000 and pct is 40 => (1000000 * 40) / (7 * 100 * 2) => 28571
artistTokenPerEpisodePerArtist =
(tokenInitialFixedSupply * artistTokenAllocationPercentage) /
(_numberOfEpisodes * 100 * 2); // 2 for 2 artists
// If total supply is 1000000 and pct is 40 => (1000000 * 40) / (7 * 100) => 57142
producerPassTokenAllocationPerEpisode =
(tokenInitialFixedSupply * producersTokenAllocationPercentage) /
(_numberOfEpisodes * 100);
}
/**
* @dev Sets the White Rabbit (WRAB) token distrubution for producers.
* This distribution is broken into 3 categories:
* - Base allocation (every Producer Pass gets the same)
* - Early staking bonus (bonding curve distribution where earlier stakers are rewarded more)
* - Winning bonus (extra pot split among winning voters)
*
* Requirements:
*
* - The allocation percentages do not exceed 100%
*/
function setProducerPassWhiteRabbitTokensAllocationParameters(
uint256 earlyStakingBonus,
uint256 winningVoteBonus
) external onlyOwner {
require(
(earlyStakingBonus + winningVoteBonus) <= 100,
"Total percentage exceeds 100"
);
uint256 basePercentage = 100 - earlyStakingBonus - winningVoteBonus;
producerPassTokenBaseAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * basePercentage) /
100;
producerPassTokenEarlyStakingBonusAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * earlyStakingBonus) /
100;
producerPassTokenWinningBonusAllocationPerEpisode =
(producerPassTokenAllocationPerEpisode * winningVoteBonus) /
100;
}
/**
* @dev Calculates the number of White Rabbit tokens the user would receive if the
* provided `amount` of Producer Passes is staked for the given episode.
*
* Requirements:
*
* - The provided episode ID exists in our list of `episodes`
*/
function getTokenAllocationForUserBeforeStaking(
uint256 episodeId,
uint256 amount
) public view returns (uint256) {
ProducerPass memory pass = whiteRabbitProducerPass
.getEpisodeToProducerPass(episodeId);
uint256 maxSupply = pass.maxSupply;
uint256 basePerPass = SafeMath.div(
producerPassTokenBaseAllocationPerEpisode,
maxSupply
);
// Get total vote count from every option of this episode for bonding curve calculation
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
uint256 totalVotesForEpisode = 0;
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentVotingOptionId = votingOptionsForThisEpisode[i];
totalVotesForEpisode += _episodeVotesByOptionId[episodeId][
currentVotingOptionId
];
}
// Below calculates number of tokens user will receive if staked
// using a linear bonding curve where early stakers get more
// Y = aX (where X = number of stakers, a = Slope, Y = tokens each staker receives)
uint256 maxBonusY = 1000 *
((producerPassTokenEarlyStakingBonusAllocationPerEpisode * 2) /
maxSupply);
uint256 slope = SafeMath.div(maxBonusY, maxSupply);
uint256 y1 = (slope * (maxSupply - totalVotesForEpisode));
uint256 y2 = (slope * (maxSupply - totalVotesForEpisode - amount));
uint256 earlyStakingBonus = (amount * (y1 + y2)) / 2;
return basePerPass * amount + earlyStakingBonus / 1000;
}
function endVotingForEpisode(uint256 episodeId) external onlyOwner {
uint256[] memory votingOptionsForThisEpisode = _episodeOptions[
episodeId
];
uint256 winningOptionId = 0;
uint256 totalVotesForWinningOption = 0;
for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) {
uint256 currentOptionId = votingOptionsForThisEpisode[i];
uint256 votesForEpisode = _episodeVotesByOptionId[episodeId][
currentOptionId
];
if (votesForEpisode >= totalVotesForWinningOption) {
winningOptionId = currentOptionId;
totalVotesForWinningOption = votesForEpisode;
}
}
setVotingEnabledForEpisode(episodeId, false);
winningVoteOptionByEpisode[episodeId] = winningOptionId;
}
/**
* @dev Manually sets the winning voting option for a given episode.
* Only call this method to break a tie among voting options for an episode.
*
* Requirements:
*
* - This should only be called for ties
*/
function endVotingForEpisodeOverride(
uint256 episodeId,
uint256 winningOptionId
) external onlyOwner {
setVotingEnabledForEpisode(episodeId, false);
winningVoteOptionByEpisode[episodeId] = winningOptionId;
}
/**
* Token distribution for artists and team
*/
/**
* @dev Sends the artists their allocation of White Rabbit tokens after an episode is launched.
*
* Requirements:
*
* - The artists have not yet received their tokens for the given episode
*/
function sendArtistTokensForEpisode(uint256 episodeId) external onlyOwner {
require(
!hasTransferredTokensToArtistForEpisode[episodeId],
"Artist tokens distributed"
);
hasTransferredTokensToArtistForEpisode[episodeId] = true;
IERC20(whiteRabbitTokenAddress).transfer(
_artist1Address,
artistTokenPerEpisodePerArtist
);
IERC20(whiteRabbitTokenAddress).transfer(
_artist2Address,
artistTokenPerEpisodePerArtist
);
}
/**
* @dev Transfers White Rabbit tokens to the team based on the `teamTokenAllocationPercentage`
*
* Requirements:
*
* - The tokens have not yet been distributed to the team
*/
function withdrawTokensForTeamAllocation(address[] calldata teamAddresses)
external
onlyOwner
{
require(!teamTokenAllocationDistributed, "Team tokens distributed");
uint256 teamBalancePerMember = (teamTokenAllocationPercentage *
tokenInitialFixedSupply) / (100 * teamAddresses.length);
for (uint256 i = 0; i < teamAddresses.length; i++) {
IERC20(whiteRabbitTokenAddress).transfer(
teamAddresses[i],
teamBalancePerMember
);
}
teamTokenAllocationDistributed = true;
}
/**
* @dev Transfers White Rabbit tokens to the team based on the platform allocation
*
* Requirements:
*
* - All Episodes finished
* - Voting completed
*/
function withdrawPlatformReserveTokens() external onlyOwner {
require(episodes.length == _numberOfEpisodes, "Show not ended");
require(
!votingEnabledForEpisode[_numberOfEpisodes],
"Last episode still voting"
);
uint256 leftOverBalance = IERC20(whiteRabbitTokenAddress).balanceOf(
address(this)
);
IERC20(whiteRabbitTokenAddress).transfer(msg.sender, leftOverBalance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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 _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// 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 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Holder.sol)
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// 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/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 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 "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
struct ProducerPass {
uint256 price;
uint256 episodeId;
uint256 maxSupply;
uint256 maxPerWallet;
uint256 openMintTimestamp; // unix timestamp in seconds
bytes32 merkleRoot;
}
contract WhiteRabbitProducerPass is ERC1155, ERC1155Supply, Ownable {
using Strings for uint256;
// The name of the token ("White Rabbit Producer Pass")
string public name;
// The token symbol ("WRPP")
string public symbol;
// The wallet addresses of the two artists creating the film
address payable private artistAddress1;
address payable private artistAddress2;
// The wallet addresses of the three developers managing the film
address payable private devAddress1;
address payable private devAddress2;
address payable private devAddress3;
// The royalty percentages for the artists and developers
uint256 private constant ARTIST_ROYALTY_PERCENTAGE = 60;
uint256 private constant DEV_ROYALTY_PERCENTAGE = 40;
// A mapping of the number of Producer Passes minted per episodeId per user
// userPassesMintedPerTokenId[msg.sender][episodeId] => number of minted passes
mapping(address => mapping(uint256 => uint256))
private userPassesMintedPerTokenId;
// A mapping from episodeId to its Producer Pass
mapping(uint256 => ProducerPass) private episodeToProducerPass;
// Event emitted when a Producer Pass is bought
event ProducerPassBought(
uint256 episodeId,
address indexed account,
uint256 amount
);
/**
* @dev Initializes the contract by setting the name and the token symbol
*/
constructor(string memory baseURI) ERC1155(baseURI) {
name = "White Rabbit Producer Pass";
symbol = "WRPP";
}
/**
* @dev Checks if the provided Merkle Proof is valid for the given root hash.
*/
function isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root)
internal
view
returns (bool)
{
return
MerkleProof.verify(
merkleProof,
root,
keccak256(abi.encodePacked(msg.sender))
);
}
/**
* @dev Retrieves the Producer Pass for a given episode.
*/
function getEpisodeToProducerPass(uint256 episodeId)
external
view
returns (ProducerPass memory)
{
return episodeToProducerPass[episodeId];
}
/**
* @dev Contracts the metadata URI for the Producer Pass of the given episodeId.
*
* Requirements:
*
* - The Producer Pass exists for the given episode
*/
function uri(uint256 episodeId)
public
view
override
returns (string memory)
{
require(
episodeToProducerPass[episodeId].episodeId != 0,
"Invalid episode"
);
return
string(
abi.encodePacked(
super.uri(episodeId),
episodeId.toString(),
".json"
)
);
}
/**
* Owner-only methods
*/
/**
* @dev Sets the base URI for the Producer Pass metadata.
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_setURI(baseURI);
}
/**
* @dev Sets the parameters on the Producer Pass struct for the given episode.
*/
function setProducerPass(
uint256 price,
uint256 episodeId,
uint256 maxSupply,
uint256 maxPerWallet,
uint256 openMintTimestamp,
bytes32 merkleRoot
) external onlyOwner {
episodeToProducerPass[episodeId] = ProducerPass(
price,
episodeId,
maxSupply,
maxPerWallet,
openMintTimestamp,
merkleRoot
);
}
/**
* @dev Withdraws the balance and distributes it to the artists and developers
* based on the `ARTIST_ROYALTY_PERCENTAGE` and `DEV_ROYALTY_PERCENTAGE`.
*/
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
uint256 artistBalance = (balance * ARTIST_ROYALTY_PERCENTAGE) / 100;
uint256 balancePerArtist = artistBalance / 2;
uint256 devBalance = (balance * DEV_ROYALTY_PERCENTAGE) / 100;
uint256 balancePerDev = devBalance / 3;
bool success;
// Transfer artist balances
(success, ) = artistAddress1.call{value: balancePerArtist}("");
require(success, "Withdraw unsuccessful");
(success, ) = artistAddress2.call{value: balancePerArtist}("");
require(success, "Withdraw unsuccessful");
// Transfer dev balances
(success, ) = devAddress1.call{value: balancePerDev}("");
require(success, "Withdraw unsuccessful");
(success, ) = devAddress2.call{value: balancePerDev}("");
require(success, "Withdraw unsuccessful");
(success, ) = devAddress3.call{value: balancePerDev}("");
require(success, "Withdraw unsuccessful");
}
/**
* @dev Sets the royalty addresses for the two artists and three developers.
*/
function setRoyaltyAddresses(
address _a1,
address _a2,
address _d1,
address _d2,
address _d3
) external onlyOwner {
artistAddress1 = payable(_a1);
artistAddress2 = payable(_a2);
devAddress1 = payable(_d1);
devAddress2 = payable(_d2);
devAddress3 = payable(_d3);
}
/**
* @dev Creates a reserve of Producer Passes to set aside for gifting.
*
* Requirements:
*
* - There are enough Producer Passes to mint for the given episode
* - The supply for the given episode does not exceed the maxSupply of the Producer Pass
*/
function reserveProducerPassesForGifting(
uint256 episodeId,
uint256 amountEachAddress,
address[] calldata addresses
) public onlyOwner {
ProducerPass memory pass = episodeToProducerPass[episodeId];
require(amountEachAddress > 0, "Amount cannot be 0");
require(totalSupply(episodeId) < pass.maxSupply, "No passes to mint");
require(
totalSupply(episodeId) + amountEachAddress * addresses.length <=
pass.maxSupply,
"Cannot mint that many"
);
require(addresses.length > 0, "Need addresses");
for (uint256 i = 0; i < addresses.length; i++) {
address add = addresses[i];
_mint(add, episodeId, amountEachAddress, "");
}
}
/**
* @dev Mints a set number of Producer Passes for a given episode.
*
* Emits a `ProducerPassBought` event indicating the Producer Pass was minted successfully.
*
* Requirements:
*
* - The current time is within the minting window for the given episode
* - There are Producer Passes available to mint for the given episode
* - The user is not trying to mint more than the maxSupply
* - The user is not trying to mint more than the maxPerWallet
* - The user has enough ETH for the transaction
*/
function mintProducerPass(uint256 episodeId, uint256 amount)
external
payable
{
ProducerPass memory pass = episodeToProducerPass[episodeId];
require(
block.timestamp >= pass.openMintTimestamp,
"Mint is not available"
);
require(totalSupply(episodeId) < pass.maxSupply, "Sold out");
require(
totalSupply(episodeId) + amount <= pass.maxSupply,
"Cannot mint that many"
);
uint256 totalMintedPasses = userPassesMintedPerTokenId[msg.sender][
episodeId
];
require(
totalMintedPasses + amount <= pass.maxPerWallet,
"Exceeding maximum per wallet"
);
require(msg.value == pass.price * amount, "Not enough eth");
userPassesMintedPerTokenId[msg.sender][episodeId] =
totalMintedPasses +
amount;
_mint(msg.sender, episodeId, amount, "");
emit ProducerPassBought(episodeId, msg.sender, amount);
}
/**
* @dev For those on with early access (on the whitelist),
* mints a set number of Producer Passes for a given episode.
*
* Emits a `ProducerPassBought` event indicating the Producer Pass was minted successfully.
*
* Requirements:
*
* - Provides a valid Merkle proof, indicating the user is on the whitelist
* - There are Producer Passes available to mint for the given episode
* - The user is not trying to mint more than the maxSupply
* - The user is not trying to mint more than the maxPerWallet
* - The user has enough ETH for the transaction
*/
function earlyMintProducerPass(
uint256 episodeId,
uint256 amount,
bytes32[] calldata merkleProof
) external payable {
ProducerPass memory pass = episodeToProducerPass[episodeId];
require(
isValidMerkleProof(merkleProof, pass.merkleRoot),
"Not authorized to mint"
);
require(totalSupply(episodeId) < pass.maxSupply, "Sold out");
require(
totalSupply(episodeId) + amount <= pass.maxSupply,
"Cannot mint that many"
);
uint256 totalMintedPasses = userPassesMintedPerTokenId[msg.sender][
episodeId
];
require(
totalMintedPasses + amount <= pass.maxPerWallet,
"Exceeding maximum per wallet"
);
require(msg.value == pass.price * amount, "Not enough eth");
userPassesMintedPerTokenId[msg.sender][episodeId] =
totalMintedPasses +
amount;
_mint(msg.sender, episodeId, amount, "");
emit ProducerPassBought(episodeId, msg.sender, amount);
}
/**
* @dev Retrieves the number of Producer Passes a user has minted by episodeId.
*/
function userPassesMintedByEpisodeId(uint256 episodeId)
external
view
returns (uint256)
{
return userPassesMintedPerTokenId[msg.sender][episodeId];
}
/**
* @dev Boilerplate override for `_beforeTokenTransfer`
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override(ERC1155, ERC1155Supply) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) 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/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of ERC1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*/
abstract contract ERC1155Supply is ERC1155 {
mapping(uint256 => uint256) private _totalSupply;
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates whether any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return ERC1155Supply.totalSupply(id) > 0;
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (from == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
if (to == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] -= amounts[i];
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
} | Owner method to toggle the voting state of a given episode. Requirements: - The provided episode ID exists in our list of `episodes` - The voting state is different than the current state - A winning option has not yet been declared/ if winner already set, don't allow re-opening of voting | function setVotingEnabledForEpisode(uint256 episodeId, bool enabled)
public
onlyOwner
{
require(episodeId <= episodes.length, "Episode does not exist");
require(
votingEnabledForEpisode[episodeId] != enabled,
"Voting state unchanged"
);
if (enabled) {
require(
winningVoteOptionByEpisode[episodeId] == 0,
"Winner for episode already set"
);
}
votingEnabledForEpisode[episodeId] = enabled;
}
| 1,528,204 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
/*
O
_
---\ _|.|_ /---
---| | |---
|_/ \_|
| |
| |
|___|
| |
/ \
SNUFFY 500
*/
/**
* @title SNUFFY 500
* @author CXIP-Labs
* @notice A smart contract for minting and managing SNUFFY 500 ERC721 NFTs.
* @dev The entire logic and functionality of the smart contract is self-contained.
*/
contract SNUFFY500 {
/**
* @dev Stores default collection data: name, symbol, and royalties.
*/
CollectionData private _collectionData;
/**
* @dev Internal last minted token id, to allow for auto-increment.
*/
uint256 private _currentTokenId;
/**
* @dev Array of all token ids in collection.
*/
uint256[] private _allTokens;
/**
* @dev Map of token id to array index of _ownedTokens.
*/
mapping(uint256 => uint256) private _ownedTokensIndex;
/**
* @dev Token id to wallet (owner) address map.
*/
mapping(uint256 => address) private _tokenOwner;
/**
* @dev 1-to-1 map of token id that was assigned an approved operator address.
*/
mapping(uint256 => address) private _tokenApprovals;
/**
* @dev Map of total tokens owner by a specific address.
*/
mapping(address => uint256) private _ownedTokensCount;
/**
* @dev Map of array of token ids owned by a specific address.
*/
mapping(address => uint256[]) private _ownedTokens;
/**
* @notice Map of full operator approval for a particular address.
* @dev Usually utilised for supporting marketplace proxy wallets.
*/
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Token data mapped by token id.
*/
mapping(uint256 => TokenData) private _tokenData;
/**
* @dev Address of admin user. Primarily used as an additional recover address.
*/
address private _admin;
/**
* @dev Address of contract owner. This address can run all onlyOwner functions.
*/
address private _owner;
/**
* @dev Simple tracker of all minted (not-burned) tokens.
*/
uint256 private _totalTokens;
/**
* @dev Mapping from token id to position in the allTokens array.
*/
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @notice Event emitted when an token is minted, transfered, or burned.
* @dev If from is empty, it's a mint. If to is empty, it's a burn. Otherwise, it's a transfer.
* @param from Address from where token is being transfered.
* @param to Address to where token is being transfered.
* @param tokenId Token id that is being minted, Transfered, or burned.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @notice Event emitted when an address delegates power, for a token, to another address.
* @dev Emits event that informs of address approving a third-party operator for a particular token.
* @param wallet Address of the wallet configuring a token operator.
* @param operator Address of the third-party operator approved for interaction.
* @param tokenId A specific token id that is being authorised to operator.
*/
event Approval(address indexed wallet, address indexed operator, uint256 indexed tokenId);
/**
* @notice Event emitted when an address authorises an operator (third-party).
* @dev Emits event that informs of address approving/denying a third-party operator.
* @param wallet Address of the wallet configuring it's operator.
* @param operator Address of the third-party operator that interacts on behalf of the wallet.
* @param approved A boolean indicating whether approval was granted or revoked.
*/
event ApprovalForAll(address indexed wallet, address indexed operator, bool approved);
/**
* @notice Event emitted to signal to OpenSea that a permanent URI was created.
* @dev Even though OpenSea advertises support for this, they do not listen to this event, and do not respond to it.
* @param uri The permanent/static URL of the NFT. Cannot ever be changed again.
* @param id Token id of the NFT.
*/
event PermanentURI(string uri, uint256 indexed id);
/**
* @notice Constructor is empty and not utilised.
* @dev To make exact CREATE2 deployment possible, constructor is left empty. We utilize the "init" function instead.
*/
constructor() {}
/**
* @notice Gets the configs for each state.
* @dev Currently only max and limit are being utilised. Four more future values are reserved for later use.
* @return max maximum number of token states ever possible.
* @return limit currently imposed hardcap/limit of token states.
* @return future0 reserved for a future value.
* @return future1 reserved for a future value.
* @return future2 reserved for a future value.
* @return future3 reserved for a future value.
*/
function getStatesConfig() public view returns (uint256 max, uint256 limit, uint256 future0, uint256 future1, uint256 future2, uint256 future3) {
return SnuffyToken.getStatesConfig();
}
/**
* @notice Sets the configs for each state.
* @dev Currently only max and limit are being utilised. Four more future values are reserved for later use.
* @param max maximum number of token states ever possible.
* @param limit currently imposed hardcap/limit of token states.
* @param future0 reserved for a future value.
* @param future1 reserved for a future value.
* @param future2 reserved for a future value.
* @param future3 reserved for a future value.
*/
function setStatesConfig(uint256 max, uint256 limit, uint256 future0, uint256 future1, uint256 future2, uint256 future3) public onlyOwner {
SnuffyToken.setStatesConfig(max, limit, future0, future1, future2, future3);
}
/**
* @notice Gets the times that each state is valid for.
* @dev All state times are stacked to identify the current state based on last timestamp.
* @return UNIX timestamps in seconds for each state's time.
*/
function getStateTimestamps() public view returns (uint256[8] memory) {
return SnuffyToken.getStateTimestamps();
}
/**
* @notice Sets the times that each state is valid for.
* @dev All state times are stacked to identify the current state based on last timestamp.
* @param _timestamps UNIX timestamps in seconds for each state's time.
*/
function setStateTimestamps(uint256[8] memory _timestamps) public onlyOwner {
SnuffyToken.setStateTimestamps(_timestamps);
}
/**
* @notice Gets the mutation requirements for each state.
* @dev Each state has it's own required amount of tokens to stack before a mutation can be forced.
* @return An array with numbers of tokens to stack for each state's mutation.
*/
function getMutationRequirements() public view returns (uint256[8] memory) {
return SnuffyToken.getMutationRequirements();
}
/**
* @notice Sets the mutation requirements for each state.
* @dev Each state has it's own required amount of tokens to stack before a mutation can be forced.
* @param _limits An array with numbers of tokens to stack for each state's mutation.
*/
function setMutationRequirements(uint256[8] memory _limits) public onlyOwner {
SnuffyToken.setMutationRequirements(_limits);
}
/**
* @notice Gets the authorised broker for minting.
* @dev In order to allow for custom airdrop type minting/claims, an external broker smart contract is used.
* @return Address of wallet or smart contract that can mint tokens.
*/
function getBroker() public view returns (address) {
return SnuffyToken.getBroker();
}
/**
* @notice Sets the authorised broker for minting.
* @dev In order to allow for custom airdrop type minting/claims, an external broker smart contract is used.
* @param broker Address of wallet or smart contract that can mint tokens.
*/
function setBroker(address broker) public onlyOwner {
SnuffyToken.setBroker(broker);
}
function getTokenState(uint256 tokenId) public view returns (uint256) {
return SnuffyToken.getTokenState(tokenId);
}
function getTokenDataIndex(uint256 tokenId) public view returns (uint256) {
return SnuffyToken.calculateState(tokenId);
}
function getTokenData(uint256 tokenId) public view returns (uint256, uint256, uint256) {
return SnuffyToken.getTokenData(tokenId);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "CXIP: caller not an owner");
_;
}
/**
* @notice Left empty to accomodate old contracts with limited transfer gas amounts.
*/
receive() external payable {}
/**
* @notice Enables royaltiy functionality at the ERC721 level no other function matches the call.
* @dev See implementation of _royaltiesFallback.
*/
fallback() external {
_royaltiesFallback();
}
/**
* @notice Gets the URI of the NFT on Arweave.
* @dev Concatenates 2 sections of the arweave URI.
* @return string The URI.
*/
function arweaveURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = SnuffyToken.calculateState(tokenId);
return string(abi.encodePacked("https://arweave.net/", _tokenData[index].arweave, _tokenData[index].arweave2));
}
/**
* @notice Gets the URI of the NFT backup from CXIP.
* @dev Concatenates to https://nft.cxip.io/.
* @return string The URI.
*/
function contractURI() external view returns (string memory) {
return string(abi.encodePacked("https://nft.cxip.io/", Strings.toHexString(address(this)), "/"));
}
/**
* @notice Gets the creator's address.
* @dev If the token Id doesn't exist it will return zero address.
* @return address Creator's address.
*/
function creator(uint256 tokenId) external view returns (address) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = SnuffyToken.calculateState(tokenId);
return _tokenData[index].creator;
}
/**
* @notice Gets the HTTP URI of the token.
* @dev Concatenates to the baseURI.
* @return string The URI.
*/
function httpURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
return string(abi.encodePacked(baseURI(), "/", Strings.toHexString(tokenId)));
}
/**
* @notice Gets the IPFS URI
* @dev Concatenates to the IPFS domain.
* @return string The URI.
*/
function ipfsURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = SnuffyToken.calculateState(tokenId);
return string(abi.encodePacked("https://ipfs.io/ipfs/", _tokenData[index].ipfs, _tokenData[index].ipfs2));
}
/**
* @notice Gets the name of the collection.
* @dev Uses two names to extend the max length of the collection name in bytes
* @return string The collection name.
*/
function name() external view returns (string memory) {
return string(abi.encodePacked(Bytes.trim(_collectionData.name), Bytes.trim(_collectionData.name2)));
}
/**
* @notice Gets the hash of the NFT data used to create it.
* @dev Payload is used for verification.
* @param tokenId The Id of the token.
* @return bytes32 The hash.
*/
function payloadHash(uint256 tokenId) external view returns (bytes32) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = SnuffyToken.calculateState(tokenId);
return _tokenData[index].payloadHash;
}
/**
* @notice Gets the signature of the signed NFT data used to create it.
* @dev Used for signature verification.
* @param tokenId The Id of the token.
* @return Verification a struct containing v, r, s values of the signature.
*/
function payloadSignature(uint256 tokenId) external view returns (Verification memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = SnuffyToken.calculateState(tokenId);
return _tokenData[index].payloadSignature;
}
/**
* @notice Gets the address of the creator.
* @dev The creator signs a payload while creating the NFT.
* @param tokenId The Id of the token.
* @return address The creator.
*/
function payloadSigner(uint256 tokenId) external view returns (address) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = SnuffyToken.calculateState(tokenId);
return _tokenData[index].creator;
}
/**
* @notice Shows the interfaces the contracts support
* @dev Must add new 4 byte interface Ids here to acknowledge support
* @param interfaceId ERC165 style 4 byte interfaceId.
* @return bool True if supported.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
if (
interfaceId == 0x01ffc9a7 || // ERC165
interfaceId == 0x80ac58cd || // ERC721
interfaceId == 0x780e9d63 || // ERC721Enumerable
interfaceId == 0x5b5e139f || // ERC721Metadata
interfaceId == 0x150b7a02 || // ERC721TokenReceiver
interfaceId == 0xe8a3d485 || // contractURI()
IPA1D(getRegistry().getPA1D()).supportsInterface(interfaceId)
) {
return true;
} else {
return false;
}
}
/**
* @notice Gets the collection's symbol.
* @dev Trims the symbol.
* @return string The symbol.
*/
function symbol() external view returns (string memory) {
return string(Bytes.trim(_collectionData.symbol));
}
/**
* @notice Get's the URI of the token.
* @dev Defaults the the Arweave URI
* @return string The URI.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = SnuffyToken.calculateState(tokenId);
return string(abi.encodePacked("https://arweave.net/", _tokenData[index].arweave, _tokenData[index].arweave2));
}
/**
* @notice Get list of tokens owned by wallet.
* @param wallet The wallet address to get tokens for.
* @return uint256[] Returns an array of token ids owned by wallet.
*/
function tokensOfOwner(address wallet) external view returns (uint256[] memory) {
return _ownedTokens[wallet];
}
/**
* @notice Checks if a given hash matches a payload hash.
* @dev Uses sha256 instead of keccak.
* @param hash The hash to check.
* @param payload The payload prehashed.
* @return bool True if the hashes match.
*/
function verifySHA256(bytes32 hash, bytes calldata payload) external pure returns (bool) {
bytes32 thePayloadHash = sha256(payload);
return hash == thePayloadHash;
}
/**
* @notice Adds a new address to the token's approval list.
* @dev Requires the sender to be in the approved addresses.
* @param to The address to approve.
* @param tokenId The affected token.
*/
function approve(address to, uint256 tokenId) public {
address tokenOwner = _tokenOwner[tokenId];
require(to != tokenOwner, "CXIP: can't approve self");
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
_tokenApprovals[tokenId] = to;
emit Approval(tokenOwner, to, tokenId);
}
/**
* @notice Burns the token.
* @dev The sender must be the owner or approved.
* @param tokenId The token to burn.
*/
function burn(uint256 tokenId) public {
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
address wallet = _tokenOwner[tokenId];
_clearApproval(tokenId);
_tokenOwner[tokenId] = address(0);
emit Transfer(wallet, address(0), tokenId);
_removeTokenFromOwnerEnumeration(wallet, tokenId);
}
/**
* @notice Initializes the collection.
* @dev Special function to allow a one time initialisation on deployment. Also configures and deploys royalties.
* @param newOwner The owner of the collection.
* @param collectionData The collection data.
*/
function init(address newOwner, CollectionData calldata collectionData) public {
require(Address.isZero(_admin), "CXIP: already initialized");
_admin = msg.sender;
// temporary set to self, to pass rarible royalties logic trap
_owner = address(this);
_collectionData = collectionData;
IPA1D(address(this)).init (0, payable(collectionData.royalties), collectionData.bps);
// set to actual owner
_owner = newOwner;
}
/**
* @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.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must exist and be owned by `from`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @notice Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings.
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must exist and be owned by `from`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public payable {
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
_transferFrom(from, to, tokenId);
if (Address.isContract(to)) {
require(
ICxipERC721(to).onERC721Received(address(this), from, tokenId, data) == 0x150b7a02,
"CXIP: onERC721Received fail"
);
}
}
/**
* @notice Adds a new approved operator.
* @dev Allows platforms to sell/transfer all your NFTs. Used with proxy contracts like OpenSea/Rarible.
* @param to The address to approve.
* @param approved Turn on or off approval status.
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender, "CXIP: can't approve self");
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @notice Transfers `tokenId` token from `msg.sender` to `to`.
* @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* @param to cannot be the zero address.
* @param tokenId token must be owned by `from`.
*/
function transfer(
address to,
uint256 tokenId
) public payable {
transferFrom(msg.sender, to, tokenId, "");
}
/**
* @notice Transfers `tokenId` token from `from` to `to`.
* @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must be owned by `from`.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable {
transferFrom(from, to, tokenId, "");
}
/**
* @notice Transfers `tokenId` token from `from` to `to`.
* @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must be owned by `from`.
*/
function transferFrom(
address from,
address to,
uint256 tokenId,
bytes memory /*_data*/
) public payable {
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
_transferFrom(from, to, tokenId);
}
/**
* @notice Mints a token directly to creator wallet, or to a recipient.
* @dev Function can be called by the owner or by an authorised broker.
* @dev If a token limit is set, then it is enforced, and minting is closed on last mint.
* @param tokenId The specific token id to use. Mandatory.
* @param tokenData Array of details for each state of the token being minted.
* @param signer the address of the wallet that signed this.
* @param verification Broker has to include a signature made by any of the identity's wallets.
* @param recipient Optional parameter, to send the token to a recipient right after minting.
*/
function mint(uint256 state, uint256 tokenId, TokenData[] memory tokenData, address signer, Verification memory verification, address recipient) public {
require(isOwner() || msg.sender == getBroker(), "CXIP: only owner/broker can mint");
require(_allTokens.length < getTokenLimit(), "CXIP: over token limit");
require(isIdentityWallet(tokenData[0].creator), "CXIP: creator not in identity");
if (!isOwner()) {
require(isIdentityWallet(signer), "CXIP: invalid signer");
bytes memory encoded = abi.encode(
tokenData[0].creator,
tokenId,
tokenData
);
require(Signature.Valid(
signer,
verification.r,
verification.s,
verification.v,
encoded
), "CXIP: invalid signature");
}
if (!Address.isZero(recipient)) {
require(!_exists(tokenId), "CXIP: token already exists");
emit Transfer(address(0), tokenData[0].creator, tokenId);
emit Transfer(tokenData[0].creator, recipient, tokenId);
_tokenOwner[tokenId] = recipient;
_addTokenToOwnerEnumeration(recipient, tokenId);
} else {
_mint(tokenData[0].creator, tokenId);
}
if (_allTokens.length == getTokenLimit()) {
setMintingClosed();
}
(uint256 max,/* uint256 limit*/,/* uint256 future0*/,/* uint256 future1*/,/* uint256 future2*/,/* uint256 future3*/) = SnuffyToken.getStatesConfig();
require(tokenData.length <= max, "CXIP: token data states too long");
uint256 index = max * tokenId;
for (uint256 i = 0; i < tokenData.length; i++) {
_tokenData[index] = tokenData[i];
index++;
}
SnuffyToken.setTokenData(tokenId, state, block.timestamp, tokenId);
}
function evolve(uint256 tokenId, uint256[] calldata tokenIds) public {
uint256 state = SnuffyToken.getTokenState(tokenId);
(/*uint256 max*/, uint256 limit,/* uint256 future0*/,/* uint256 future1*/,/* uint256 future2*/,/* uint256 future3*/) = SnuffyToken.getStatesConfig();
require(state < (limit - 1), "CXIP: token evolved to max");
uint256[8] memory _limits = SnuffyToken.getMutationRequirements();
require(tokenIds.length == _limits[state], "CXIP: incorrect tokens amount");
bool included;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(ownerOf(tokenIds[i]) == msg.sender, "CXIP: not owner of token");
require(SnuffyToken.getTokenState(tokenIds[i]) >= state, "CXIP: token level too low");
if (!included && tokenId == tokenIds[i]) {
SnuffyToken.setTokenData(tokenId, state + 1, block.timestamp, tokenId);
included = true;
} else {
SnuffyToken.setTokenData(tokenIds[i], 0, block.timestamp, tokenIds[i]);
_transferFrom(msg.sender, SnuffyToken.getBroker(), tokenIds[i]);
}
}
require(included, "CXIP: missing evolving token");
}
/**
* @dev Gets the minting status from storage slot.
* @return mintingClosed Whether minting is open or closed permanently.
*/
function getMintingClosed() public view returns (bool mintingClosed) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SNUFFY500.mintingClosed')) - 1);
uint256 data;
assembly {
data := sload(
/* slot */
0x82d37688748a8833e0d222efdc792424f8a1acdd6c8351cb26b314a4ceee6a84
)
}
mintingClosed = (data == 1);
}
/**
* @dev Sets the minting status to closed in storage slot.
*/
function setMintingClosed() public onlyOwner {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SNUFFY500.mintingClosed')) - 1);
uint256 data = 1;
assembly {
sstore(
/* slot */
0x82d37688748a8833e0d222efdc792424f8a1acdd6c8351cb26b314a4ceee6a84,
data
)
}
}
/**
* @dev Gets the token limit from storage slot.
* @return tokenLimit Maximum number of tokens that can be minted.
*/
function getTokenLimit() public view returns (uint256 tokenLimit) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SNUFFY500.tokenLimit')) - 1);
assembly {
tokenLimit := sload(
/* slot */
0xd7cccb4858870420bddc578f86437fd66f8949091f61f21bd40e4390dc953953
)
}
if (tokenLimit == 0) {
tokenLimit = type(uint256).max;
}
}
/**
* @dev Sets the token limit to storage slot.
* @param tokenLimit Maximum number of tokens that can be minted.
*/
function setTokenLimit(uint256 tokenLimit) public onlyOwner {
require(getTokenLimit() == 0, "CXIP: token limit already set");
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SNUFFY500.tokenLimit')) - 1);
assembly {
sstore(
/* slot */
0xd7cccb4858870420bddc578f86437fd66f8949091f61f21bd40e4390dc953953,
tokenLimit
)
}
}
/**
* @notice Set an NFT state.
* @dev Time-based states will be retrieved by index.
* @param id The index of time slot to set for.
* @param tokenData The token data for the particular time slot.
*/
function prepareMintData(uint256 id, TokenData calldata tokenData) public onlyOwner {
require(Address.isZero(_tokenData[id].creator), "CXIP: token data already set");
_tokenData[id] = tokenData;
}
function prepareMintDataBatch(uint256[] calldata ids, TokenData[] calldata tokenData) public onlyOwner {
require(ids.length == tokenData.length, "CXIP: array lengths missmatch");
for (uint256 i = 0; i < ids.length; i++) {
require(Address.isZero(_tokenData[ids[i]].creator), "CXIP: token data already set");
_tokenData[ids[i]] = tokenData[i];
}
}
/**
* @notice Sets a name for the collection.
* @dev The name is split in two for gas optimization.
* @param newName First part of name.
* @param newName2 Second part of name.
*/
function setName(bytes32 newName, bytes32 newName2) public onlyOwner {
_collectionData.name = newName;
_collectionData.name2 = newName2;
}
/**
* @notice Set a symbol for the collection.
* @dev This is the ticker symbol for smart contract that shows up on EtherScan.
* @param newSymbol The ticker symbol to set for smart contract.
*/
function setSymbol(bytes32 newSymbol) public onlyOwner {
_collectionData.symbol = newSymbol;
}
/**
* @notice Transfers ownership of the collection.
* @dev Can't be the zero address.
* @param newOwner Address of new owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(!Address.isZero(newOwner), "CXIP: zero address");
_owner = newOwner;
}
/**
* @notice Get total number of tokens owned by wallet.
* @dev Used to see total amount of tokens owned by a specific wallet.
* @param wallet Address for which to get token balance.
* @return uint256 Returns an integer, representing total amount of tokens held by address.
*/
function balanceOf(address wallet) public view returns (uint256) {
require(!Address.isZero(wallet), "CXIP: zero address");
return _ownedTokensCount[wallet];
}
/**
* @notice Get a base URI for the token.
* @dev Concatenates with the CXIP domain name.
* @return string the token URI.
*/
function baseURI() public view returns (string memory) {
return string(abi.encodePacked("https://nft.cxip.io/", Strings.toHexString(address(this))));
}
function exists(uint256 tokenId) public view returns (bool) {
return !Address.isZero(_tokenOwner[tokenId]);
}
/**
* @notice Gets the approved address for the token.
* @dev Single operator set for a specific token. Usually used for one-time very specific authorisations.
* @param tokenId Token id to get approved operator for.
* @return address Approved address for token.
*/
function getApproved(uint256 tokenId) public view returns (address) {
return _tokenApprovals[tokenId];
}
/**
* @notice Get the associated identity for the collection.
* @dev Goes up the chain to read from the registry.
* @return address Identity contract address.
*/
function getIdentity() public view returns (address) {
return ICxipProvenance(getRegistry().getProvenance()).getWalletIdentity(_owner);
}
/**
* @notice Checks if the address is approved.
* @dev Includes references to OpenSea and Rarible marketplace proxies.
* @param wallet Address of the wallet.
* @param operator Address of the marketplace operator.
* @return bool True if approved.
*/
function isApprovedForAll(address wallet, address operator) public view returns (bool) {
// pre-approved OpenSea and Rarible proxies removed, per Nifty Gateway's request
return (_operatorApprovals[wallet][operator]/* ||
// Rarible Transfer Proxy
0x4feE7B061C97C9c496b01DbcE9CDb10c02f0a0Be == operator ||
// OpenSea Transfer Proxy
address(OpenSeaProxyRegistry(0xa5409ec958C83C3f309868babACA7c86DCB077c1).proxies(wallet)) == operator*/);
}
/**
* @notice Check if the sender is the owner.
* @dev The owner could also be the admin or identity contract of the owner.
* @return bool True if owner.
*/
function isOwner() public view returns (bool) {
return (msg.sender == _owner || msg.sender == _admin || isIdentityWallet(msg.sender));
}
/**
* @notice Gets the owner's address.
* @dev _owner is first set in init.
* @return address Of ower.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @notice Checks who the owner of a token is.
* @dev The token must exist.
* @param tokenId The token to look up.
* @return address Owner of the token.
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address tokenOwner = _tokenOwner[tokenId];
require(!Address.isZero(tokenOwner), "ERC721: token does not exist");
return tokenOwner;
}
/**
* @notice Get token by index.
* @dev Used in conjunction with totalSupply function to iterate over all tokens in collection.
* @param index Index of token in array.
* @return uint256 Returns the token id of token located at that index.
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "CXIP: index out of bounds");
return _allTokens[index];
}
/**
* @notice Get token from wallet by index instead of token id.
* @dev Helpful for wallet token enumeration where token id info is not yet available. Use in conjunction with balanceOf function.
* @param wallet Specific address for which to get token for.
* @param index Index of token in array.
* @return uint256 Returns the token id of token located at that index in specified wallet.
*/
function tokenOfOwnerByIndex(
address wallet,
uint256 index
) public view returns (uint256) {
require(index < balanceOf(wallet));
return _ownedTokens[wallet][index];
}
/**
* @notice Total amount of tokens in the collection.
* @dev Ignores burned tokens.
* @return uint256 Returns the total number of active (not burned) tokens.
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @notice Empty function that is triggered by external contract on NFT transfer.
* @dev We have this blank function in place to make sure that external contract sending in NFTs don't error out.
* @dev Since it's not being used, the _operator variable is commented out to avoid compiler warnings.
* @dev Since it's not being used, the _from variable is commented out to avoid compiler warnings.
* @dev Since it's not being used, the _tokenId variable is commented out to avoid compiler warnings.
* @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings.
* @return bytes4 Returns the interfaceId of onERC721Received.
*/
function onERC721Received(
address, /*_operator*/
address, /*_from*/
uint256, /*_tokenId*/
bytes calldata /*_data*/
) public pure returns (bytes4) {
return 0x150b7a02;
}
/**
* @notice Allows retrieval of royalties from the contract.
* @dev This is a default fallback to ensure the royalties are available.
*/
function _royaltiesFallback() internal {
address _target = getRegistry().getPA1D();
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), _target, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @notice Checks if an address is an identity contract.
* @dev It must also be registred.
* @param sender Address to check if registered to identity.
* @return bool True if registred identity.
*/
function isIdentityWallet(address sender) internal view returns (bool) {
address identity = getIdentity();
if (Address.isZero(identity)) {
return false;
}
return ICxipIdentity(identity).isWalletRegistered(sender);
}
/**
* @dev Get the top-level CXIP Registry smart contract. Function must always be internal to prevent miss-use/abuse through bad programming practices.
* @return ICxipRegistry The address of the top-level CXIP Registry smart contract.
*/
function getRegistry() internal pure returns (ICxipRegistry) {
return ICxipRegistry(0xC267d41f81308D7773ecB3BDd863a902ACC01Ade);
}
/**
* @dev Add a newly minted token into managed list of tokens.
* @param to Address of token owner for which to add the token.
* @param tokenId Id of token to add.
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokensCount[to];
_ownedTokensCount[to]++;
_ownedTokens[to].push(tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @notice Deletes a token from the approval list.
* @dev Removes from count.
* @param tokenId T.
*/
function _clearApproval(uint256 tokenId) private {
delete _tokenApprovals[tokenId];
}
/**
* @notice Mints an NFT.
* @dev Can to mint the token to the zero address and the token cannot already exist.
* @param to Address to mint to.
* @param tokenId The new token.
*/
function _mint(address to, uint256 tokenId) private {
require(!Address.isZero(to), "CXIP: can't mint a burn");
require(!_exists(tokenId), "CXIP: token already exists");
_tokenOwner[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId;
_allTokensIndex[lastTokenId] = tokenIndex;
delete _allTokensIndex[tokenId];
delete _allTokens[lastTokenIndex];
_allTokens.pop();
}
/**
* @dev Remove a token from managed list of tokens.
* @param from Address of token owner for which to remove the token.
* @param tokenId Id of token to remove.
*/
function _removeTokenFromOwnerEnumeration(
address from,
uint256 tokenId
) private {
_removeTokenFromAllTokensEnumeration(tokenId);
_ownedTokensCount[from]--;
uint256 lastTokenIndex = _ownedTokensCount[from];
uint256 tokenIndex = _ownedTokensIndex[tokenId];
if(tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId;
_ownedTokensIndex[lastTokenId] = tokenIndex;
}
if(lastTokenIndex == 0) {
delete _ownedTokens[from];
} else {
delete _ownedTokens[from][lastTokenIndex];
_ownedTokens[from].pop();
}
}
/**
* @dev Primary internal function that handles the transfer/mint/burn functionality.
* @param from Address from where token is being transferred. Zero address means it is being minted.
* @param to Address to whom the token is being transferred. Zero address means it is being burned.
* @param tokenId Id of token that is being transferred/minted/burned.
*/
function _transferFrom(
address from,
address to,
uint256 tokenId
) private {
require(_tokenOwner[tokenId] == from, "CXIP: not from's token");
require(!Address.isZero(to), "CXIP: use burn instead");
_clearApproval(tokenId);
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
SnuffyToken.setTokenData(tokenId, SnuffyToken.getTokenState(tokenId), block.timestamp, tokenId);
}
/**
* @notice Checks if the token owner exists.
* @dev If the address is the zero address no owner exists.
* @param tokenId The affected token.
* @return bool True if it exists.
*/
function _exists(uint256 tokenId) private view returns (bool) {
address tokenOwner = _tokenOwner[tokenId];
return !Address.isZero(tokenOwner);
}
/**
* @notice Checks if the address is an approved one.
* @dev Uses inlined checks for different usecases of approval.
* @param spender Address of the spender.
* @param tokenId The affected token.
* @return bool True if approved.
*/
function _isApproved(address spender, uint256 tokenId) private view returns (bool) {
require(_exists(tokenId));
address tokenOwner = _tokenOwner[tokenId];
return (
spender == tokenOwner ||
getApproved(tokenId) == spender ||
isApprovedForAll(tokenOwner, spender)
);
}
}
library SnuffyToken {
/*
// current hard cap for the states and amount of mutations possible
uint256 statesLimit = 6;
// hardware limit of maximum number of mutations possible
uint256 maxStates = 8;
*/
/**
* @notice Gets the configs for each state.
* @dev Currently only max and limit are being utilised. Four more future values are reserved for later use.
* @return max maximum number of token states ever possible.
* @return limit currently imposed hardcap/limit of token states.
* @return future0 reserved for a future value.
* @return future1 reserved for a future value.
* @return future2 reserved for a future value.
* @return future3 reserved for a future value.
*/
function getStatesConfig() internal view returns (uint256 max, uint256 limit, uint256 future0, uint256 future1, uint256 future2, uint256 future3) {
uint256 unpacked;
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SnuffyToken.statesConfig')) - 1);
assembly {
unpacked := sload(
/* slot */
0x320f7df63ad3c1fb03163fc8f47010f96d0a4b028d5ed2c9bdbc6b577caddacf
)
}
max = uint256(uint32(unpacked >> 0));
limit = uint256(uint32(unpacked >> 32));
future0 = uint256(uint32(unpacked >> 64));
future1 = uint256(uint32(unpacked >> 96));
future2 = uint256(uint32(unpacked >> 128));
future3 = uint256(uint32(unpacked >> 160));
}
/**
* @notice Sets the configs for each state.
* @dev Currently only max and limit are being utilised. Four more future values are reserved for later use.
* @param max maximum number of token states ever possible.
* @param limit currently imposed hardcap/limit of token states.
* @param future0 reserved for a future value.
* @param future1 reserved for a future value.
* @param future2 reserved for a future value.
* @param future3 reserved for a future value.
*/
function setStatesConfig(uint256 max, uint256 limit, uint256 future0, uint256 future1, uint256 future2, uint256 future3) internal {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SnuffyToken.statesConfig')) - 1);
uint256 packed;
packed = packed | max << 0;
packed = packed | limit << 32;
packed = packed | future0 << 64;
packed = packed | future1 << 96;
packed = packed | future2 << 128;
packed = packed | future3 << 160;
assembly {
sstore(
/* slot */
0x320f7df63ad3c1fb03163fc8f47010f96d0a4b028d5ed2c9bdbc6b577caddacf,
packed
)
}
}
/**
* @dev Gets the timestamps for duration of each state from storage slot.
* @return _timestamps UNIX timestamps for controlling each state's maximum duration.
*/
function getStateTimestamps() internal view returns (uint256[8] memory _timestamps) {
uint256 data;
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SnuffyToken.stateTimestamps')) - 1);
assembly {
data := sload(
/* slot */
0xb3272806717bb124fff9d338a5d6ec1182c08fc56784769d91b37c01055db8e2
)
}
for (uint256 i = 0; i < 8; i++) {
_timestamps[i] = uint256(uint32(data >> (32 * i)));
}
}
/**
* @dev Sets the timestamps for duration of each state to storage slot.
* @param _timestamps timestamps for controlling each state's maximum duration.
*/
function setStateTimestamps(uint256[8] memory _timestamps) internal {
uint256 packed;
for (uint256 i = 0; i < 8; i++) {
packed = packed | _timestamps[i] << (32 * i);
}
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SnuffyToken.stateTimestamps')) - 1);
assembly {
sstore(
/* slot */
0xb3272806717bb124fff9d338a5d6ec1182c08fc56784769d91b37c01055db8e2,
packed
)
}
}
/**
* @dev Gets the number of tokens needed for a forced mutation from storage slot.
* @return _limits An array of number of tokens required for a forced mutation.
*/
function getMutationRequirements() internal view returns (uint256[8] memory _limits) {
uint256 data;
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SnuffyToken.mutationRequirements')) - 1);
assembly {
data := sload(
/* slot */
0x6ab8a5e4f8314f5c905e9eb234db45800102f76ee29724ea1039076fe1c57441
)
}
for (uint256 i = 0; i < 8; i++) {
_limits[i] = uint256(uint32(data >> (32 * i)));
}
}
/**
* @dev Sets the number of tokens needed for a forced mutation to storage slot.
* @param _limits An array of number of tokens required for a forced mutation.
*/
function setMutationRequirements(uint256[8] memory _limits) internal {
uint256 packed;
for (uint256 i = 0; i < 8; i++) {
packed = packed | _limits[i] << (32 * i);
}
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SnuffyToken.mutationRequirements')) - 1);
assembly {
sstore(
/* slot */
0x6ab8a5e4f8314f5c905e9eb234db45800102f76ee29724ea1039076fe1c57441,
packed
)
}
}
/**
* @dev Gets the authorised broker from storage slot.
* @return broker Address of authorised broker.
*/
function getBroker() internal view returns (address broker) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SnuffyToken.broker')) - 1);
assembly {
broker := sload(
/* slot */
0x71ad4b54125645bc093479b790dba1d002be6ff1fc59f46b726e598257e1e3c1
)
}
}
/**
* @dev Sets authorised broker to storage slot.
* @param broker Address of authorised broker.
*/
function setBroker(address broker) internal {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.SnuffyToken.broker')) - 1);
assembly {
sstore(
/* slot */
0x71ad4b54125645bc093479b790dba1d002be6ff1fc59f46b726e598257e1e3c1,
broker
)
}
}
/**
* @dev Gets the configuration/mapping for tokenId to stencilId from storage slot.
* @return state The latest permanent state that the token was transferred with.
* @return timestamp The UNIX timestamp of when last transfer occurred.
* @return stencilId Mapping for which stencil the token id was assigned.
*/
function getTokenData(uint256 tokenId) internal view returns (uint256 state, uint256 timestamp, uint256 stencilId) {
uint256 unpacked;
bytes32 slot = bytes32(uint256(keccak256(abi.encodePacked("eip1967.CXIP.SnuffyToken.tokenData.", tokenId))) - 1);
assembly {
unpacked := sload(slot)
}
state = uint256(uint32(unpacked >> 0));
timestamp = uint256(uint32(unpacked >> 32));
stencilId = uint256(uint32(unpacked >> 64));
}
/**
* @dev Sets the configuration/mapping for tokenId to stencilId to storage slot.
* @param state The latest permanent state that the token was transferred with.
* @param timestamp The UNIX timestamp of when last transfer occurred.
* @param stencilId Mapping for which stencil the token id was assigned.
*/
function setTokenData(uint256 tokenId, uint256 state, uint256 timestamp, uint256 stencilId) internal {
bytes32 slot = bytes32(uint256(keccak256(abi.encodePacked("eip1967.CXIP.SnuffyToken.tokenData.", tokenId))) - 1);
uint256 packed;
packed = packed | state << 0;
packed = packed | timestamp << 32;
packed = packed | stencilId << 64;
assembly {
sstore(slot, packed)
}
}
function calculateState(uint256 tokenId) internal view returns (uint256 dataIndex) {
(uint256 max,/* uint256 limit*/,/* uint256 future0*/,/* uint256 future1*/,/* uint256 future2*/,/* uint256 future3*/) = getStatesConfig();
(/*uint256 state*/,/* uint256 timestamp*/, uint256 stencilId) = getTokenData(tokenId);
dataIndex = max * stencilId;
return dataIndex + getTokenState(tokenId);
}
function getTokenState(uint256 tokenId) internal view returns (uint256 dataIndex) {
(/*uint256 max*/, uint256 limit,/* uint256 future0*/,/* uint256 future1*/,/* uint256 future2*/,/* uint256 future3*/) = getStatesConfig();
(uint256[8] memory _timestamps) = getStateTimestamps();
(uint256 state, uint256 timestamp,/* uint256 stencilId*/) = getTokenData(tokenId);
uint256 duration = block.timestamp - timestamp;
for (uint256 i = state; i < limit; i++) {
if (duration < _timestamps[i]) {
return i;
}
duration -= _timestamps[i];
}
return limit - 1;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function isZero(address account) internal pure returns (bool) {
return (account == address(0));
}
}
library Bytes {
function getBoolean(uint192 _packedBools, uint192 _boolNumber) internal pure returns (bool) {
uint192 flag = (_packedBools >> _boolNumber) & uint192(1);
return (flag == 1 ? true : false);
}
function setBoolean(
uint192 _packedBools,
uint192 _boolNumber,
bool _value
) internal pure returns (uint192) {
if (_value) {
return _packedBools | (uint192(1) << _boolNumber);
} else {
return _packedBools & ~(uint192(1) << _boolNumber);
}
}
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
tempBytes := mload(0x40)
let lengthmod := and(_length, 31)
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
mstore(0x40, and(add(mc, 31), not(31)))
}
default {
tempBytes := mload(0x40)
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function trim(bytes32 source) internal pure returns (bytes memory) {
uint256 temp = uint256(source);
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return slice(abi.encodePacked(source), 32 - length, length);
}
}
library Signature {
function Derive(
bytes32 r,
bytes32 s,
uint8 v,
bytes memory encoded
)
internal
pure
returns (
address derived1,
address derived2,
address derived3,
address derived4
)
{
bytes32 encoded32;
assembly {
encoded32 := mload(add(encoded, 32))
}
derived1 = ecrecover(encoded32, v, r, s);
derived2 = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", encoded32)), v, r, s);
encoded32 = keccak256(encoded);
derived3 = ecrecover(encoded32, v, r, s);
encoded32 = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", encoded32));
derived4 = ecrecover(encoded32, v, r, s);
}
function PackMessage(bytes memory encoded, bool geth) internal pure returns (bytes32) {
bytes32 hash = keccak256(encoded);
if (geth) {
hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
return hash;
}
function Valid(
address target,
bytes32 r,
bytes32 s,
uint8 v,
bytes memory encoded
) internal pure returns (bool) {
bytes32 encoded32;
address derived;
if (encoded.length == 32) {
assembly {
encoded32 := mload(add(encoded, 32))
}
derived = ecrecover(encoded32, v, r, s);
if (target == derived) {
return true;
}
derived = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", encoded32)), v, r, s);
if (target == derived) {
return true;
}
}
bytes32 hash = keccak256(encoded);
derived = ecrecover(hash, v, r, s);
if (target == derived) {
return true;
}
hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
derived = ecrecover(hash, v, r, s);
return target == derived;
}
}
library Strings {
function toHexString(address account) internal pure returns (string memory) {
return toHexString(uint256(uint160(account)));
}
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);
}
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] = bytes16("0123456789abcdef")[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
struct CollectionData {
bytes32 name;
bytes32 name2;
bytes32 symbol;
address royalties;
uint96 bps;
}
struct Token {
address collection;
uint256 tokenId;
InterfaceType tokenType;
address creator;
}
struct TokenData {
bytes32 payloadHash;
Verification payloadSignature;
address creator;
bytes32 arweave;
bytes11 arweave2;
bytes32 ipfs;
bytes14 ipfs2;
}
struct Verification {
bytes32 r;
bytes32 s;
uint8 v;
}
// This is a 256 value limit (uint8)
enum InterfaceType {
NULL, // 0
ERC20, // 1
ERC721, // 2
ERC1155 // 3
}
// This is a 256 value limit (uint8)
enum UriType {
ARWEAVE, // 0
IPFS, // 1
HTTP // 2
}
interface ICxipERC721 {
function arweaveURI(uint256 tokenId) external view returns (string memory);
function contractURI() external view returns (string memory);
function creator(uint256 tokenId) external view returns (address);
function httpURI(uint256 tokenId) external view returns (string memory);
function ipfsURI(uint256 tokenId) external view returns (string memory);
function name() external view returns (string memory);
function payloadHash(uint256 tokenId) external view returns (bytes32);
function payloadSignature(uint256 tokenId) external view returns (Verification memory);
function payloadSigner(uint256 tokenId) external view returns (address);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
/* Disabled due to tokenEnumeration not enabled.
function tokensOfOwner(
address wallet
) external view returns (uint256[] memory);
*/
function verifySHA256(bytes32 hash, bytes calldata payload) external pure returns (bool);
function approve(address to, uint256 tokenId) external;
function burn(uint256 tokenId) external;
function init(address newOwner, CollectionData calldata collectionData) external;
/* Disabled since this flow has not been agreed on.
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) external payable;
function setApprovalForAll(address to, bool approved) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function transferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) external payable;
function cxipMint(uint256 id, TokenData calldata tokenData) external returns (uint256);
function setApprovalForAll(
address from,
address to,
bool approved
) external;
function setName(bytes32 newName, bytes32 newName2) external;
function setSymbol(bytes32 newSymbol) external;
function transferOwnership(address newOwner) external;
/*
// Disabled due to tokenEnumeration not enabled.
function balanceOf(address wallet) external view returns (uint256);
*/
function baseURI() external view returns (string memory);
function getApproved(uint256 tokenId) external view returns (address);
function getIdentity() external view returns (address);
function isApprovedForAll(address wallet, address operator) external view returns (bool);
function isOwner() external view returns (bool);
function owner() external view returns (address);
function ownerOf(uint256 tokenId) external view returns (address);
/* Disabled due to tokenEnumeration not enabled.
function tokenByIndex(uint256 index) external view returns (uint256);
*/
/* Disabled due to tokenEnumeration not enabled.
function tokenOfOwnerByIndex(
address wallet,
uint256 index
) external view returns (uint256);
*/
/* Disabled due to tokenEnumeration not enabled.
function totalSupply() external view returns (uint256);
*/
function totalSupply() external view returns (uint256);
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external pure returns (bytes4);
}
interface ICxipIdentity {
function addSignedWallet(
address newWallet,
uint8 v,
bytes32 r,
bytes32 s
) external;
function addWallet(address newWallet) external;
function connectWallet() external;
function createERC721Token(
address collection,
uint256 id,
TokenData calldata tokenData,
Verification calldata verification
) external returns (uint256);
function createERC721Collection(
bytes32 saltHash,
address collectionCreator,
Verification calldata verification,
CollectionData calldata collectionData
) external returns (address);
function createCustomERC721Collection(
bytes32 saltHash,
address collectionCreator,
Verification calldata verification,
CollectionData calldata collectionData,
bytes32 slot,
bytes memory bytecode
) external returns (address);
function init(address wallet, address secondaryWallet) external;
function getAuthorizer(address wallet) external view returns (address);
function getCollectionById(uint256 index) external view returns (address);
function getCollectionType(address collection) external view returns (InterfaceType);
function getWallets() external view returns (address[] memory);
function isCollectionCertified(address collection) external view returns (bool);
function isCollectionRegistered(address collection) external view returns (bool);
function isNew() external view returns (bool);
function isOwner() external view returns (bool);
function isTokenCertified(address collection, uint256 tokenId) external view returns (bool);
function isTokenRegistered(address collection, uint256 tokenId) external view returns (bool);
function isWalletRegistered(address wallet) external view returns (bool);
function listCollections(uint256 offset, uint256 length) external view returns (address[] memory);
function nextNonce(address wallet) external view returns (uint256);
function totalCollections() external view returns (uint256);
function isCollectionOpen(address collection) external pure returns (bool);
}
interface ICxipProvenance {
function createIdentity(
bytes32 saltHash,
address wallet,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256, address);
function createIdentityBatch(
bytes32 saltHash,
address[] memory wallets,
uint8[] memory V,
bytes32[] memory RS
) external returns (uint256, address);
function getIdentity() external view returns (address);
function getWalletIdentity(address wallet) external view returns (address);
function informAboutNewWallet(address newWallet) external;
function isIdentityValid(address identity) external view returns (bool);
function nextNonce(address wallet) external view returns (uint256);
}
interface ICxipRegistry {
function getAsset() external view returns (address);
function getAssetSigner() external view returns (address);
function getAssetSource() external view returns (address);
function getCopyright() external view returns (address);
function getCopyrightSource() external view returns (address);
function getCustomSource(bytes32 name) external view returns (address);
function getCustomSourceFromString(string memory name) external view returns (address);
function getERC1155CollectionSource() external view returns (address);
function getERC721CollectionSource() external view returns (address);
function getIdentitySource() external view returns (address);
function getPA1D() external view returns (address);
function getPA1DSource() external view returns (address);
function getProvenance() external view returns (address);
function getProvenanceSource() external view returns (address);
function owner() external view returns (address);
function setAsset(address proxy) external;
function setAssetSigner(address source) external;
function setAssetSource(address source) external;
function setCopyright(address proxy) external;
function setCopyrightSource(address source) external;
function setCustomSource(string memory name, address source) external;
function setERC1155CollectionSource(address source) external;
function setERC721CollectionSource(address source) external;
function setIdentitySource(address source) external;
function setPA1D(address proxy) external;
function setPA1DSource(address source) external;
function setProvenance(address proxy) external;
function setProvenanceSource(address source) external;
}
interface IPA1D {
function init(
uint256 tokenId,
address payable receiver,
uint256 bp
) external;
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
} | Gets the authorised broker for minting. In order to allow for custom airdrop type minting/claims, an external broker smart contract is used. return Address of wallet or smart contract that can mint tokens./ | function getBroker() public view returns (address) {
return SnuffyToken.getBroker();
}
| 1,517,323 |
// 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: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./ContextUpgradeable.sol";
import "../proxy/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.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.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @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.7.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.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
/**
* Based on https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/v3.4.0-solc-0.7/contracts/access/OwnableUpgradeable.sol
*
* Changes:
* - Added owner argument to initializer
* - Reformatted styling in line with this repository.
*/
/*
The MIT License (MIT)
Copyright (c) 2016-2020 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* solhint-disable func-name-mixedcase */
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/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(address owner_) internal initializer {
__Context_init_unchained();
__Ownable_init_unchained(owner_);
}
function __Ownable_init_unchained(address owner_) internal initializer {
_owner = owner_;
emit OwnershipTransferred(address(0), owner_);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @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
/**
* Based on https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0-solc-0.7/contracts/utils/EnumerableMap.sol
*
* Changes:
* - Replaced UintToAddressMap with AddressToUintMap
* - Reformatted styling in line with this repository.
*/
/*
The MIT License (MIT)
Copyright (c) 2016-2020 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.7.6;
/**
* @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];
// Equivalent to !contains(map, key)
if (keyIndex == 0) {
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];
// Equivalent to contains(map, key)
if (keyIndex != 0) {
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// AddressToUintMap
struct AddressToUintMap {
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(
AddressToUintMap storage map,
address key,
uint256 value
) internal returns (bool) {
return _set(map._inner, bytes32(uint256(key)), bytes32(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(AddressToUintMap storage map, address key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(uint256(key)));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToUintMap storage map, address key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(uint256(key)));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToUintMap 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(AddressToUintMap storage map, uint256 index)
internal
view
returns (address, uint256)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (address(uint256(key)), uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToUintMap storage map, address key)
internal
view
returns (uint256)
{
return uint256(_get(map._inner, bytes32(uint256(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(
AddressToUintMap storage map,
address key,
string memory errorMessage
) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(key)), errorMessage));
}
}
// SPDX-License-Identifier: Apache-2.0
/**
* Copyright 2021 weiWard LLC
*
* 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.7.6;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./LPRewardsData.sol";
import "../../libraries/EnumerableMap.sol";
import "../interfaces/ILPRewards.sol";
import "../interfaces/IValuePerToken.sol";
import "../../tokens/interfaces/IWETH.sol";
import "../../access/OwnableUpgradeable.sol";
contract LPRewards is
Initializable,
ContextUpgradeable,
OwnableUpgradeable,
PausableUpgradeable,
LPRewardsData,
ILPRewards
{
using Address for address payable;
using EnumerableMap for EnumerableMap.AddressToUintMap;
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/* Immutable Internal State */
uint256 internal constant _MULTIPLIER = 1e36;
/* Constructor */
constructor(address owner_) {
init(owner_);
}
/* Initializers */
function init(address owner_) public virtual initializer {
__Context_init_unchained();
__Ownable_init_unchained(owner_);
__Pausable_init_unchained();
}
/* Fallbacks */
receive() external payable {
// Only accept ETH via fallback from the WETH contract
require(msg.sender == _rewardsToken);
}
/* Modifiers */
modifier supportsToken(address token) {
require(supportsStakingToken(token), "LPRewards: unsupported token");
_;
}
/* Public Views */
function accruedRewardsPerTokenFor(address token)
public
view
virtual
override
returns (uint256)
{
return _tokenData[token].arpt;
}
function accruedRewardsPerTokenLastFor(address account, address token)
public
view
virtual
override
returns (uint256)
{
return _users[account].rewardsFor[token].arptLast;
}
function lastRewardsBalanceOf(address account)
public
view
virtual
override
returns (uint256 total)
{
UserData storage user = _users[account];
EnumerableSet.AddressSet storage tokens = user.tokensWithRewards;
for (uint256 i = 0; i < tokens.length(); i++) {
total += user.rewardsFor[tokens.at(i)].pending;
}
}
function lastRewardsBalanceOfFor(address account, address token)
public
view
virtual
override
returns (uint256)
{
return _users[account].rewardsFor[token].pending;
}
function lastTotalRewardsAccrued()
external
view
virtual
override
returns (uint256)
{
return _lastTotalRewardsAccrued;
}
function lastTotalRewardsAccruedFor(address token)
external
view
virtual
override
returns (uint256)
{
return _tokenData[token].lastRewardsAccrued;
}
function numStakingTokens()
external
view
virtual
override
returns (uint256)
{
return _tokens.length();
}
function rewardsBalanceOf(address account)
external
view
virtual
override
returns (uint256)
{
return lastRewardsBalanceOf(account) + _allPendingRewardsFor(account);
}
function rewardsBalanceOfFor(address account, address token)
external
view
virtual
override
returns (uint256)
{
uint256 rewards = lastRewardsBalanceOfFor(account, token);
uint256 amountStaked = stakedBalanceOf(account, token);
if (amountStaked != 0) {
rewards += _pendingRewardsFor(account, token, amountStaked);
}
return rewards;
}
function rewardsForToken(address token)
external
view
virtual
override
returns (uint256)
{
return _tokenData[token].rewards;
}
function rewardsToken() public view virtual override returns (address) {
return _rewardsToken;
}
function sharesFor(address account, address token)
external
view
virtual
override
returns (uint256)
{
return _shares(token, stakedBalanceOf(account, token));
}
function sharesPerToken(address token)
external
view
virtual
override
returns (uint256)
{
return _shares(token, 1e18);
}
function stakedBalanceOf(address account, address token)
public
view
virtual
override
returns (uint256)
{
EnumerableMap.AddressToUintMap storage staked = _users[account].staked;
if (staked.contains(token)) {
return staked.get(token);
}
return 0;
}
function stakingTokenAt(uint256 index)
external
view
virtual
override
returns (address)
{
return _tokens.at(index);
}
function supportsStakingToken(address token)
public
view
virtual
override
returns (bool)
{
return _tokens.contains(token);
}
function totalRewardsAccrued()
public
view
virtual
override
returns (uint256)
{
// Overflow is OK
return _currentRewardsBalance() + _totalRewardsRedeemed;
}
function totalRewardsAccruedFor(address token)
public
view
virtual
override
returns (uint256)
{
TokenData storage td = _tokenData[token];
// Overflow is OK
return td.rewards + td.rewardsRedeemed;
}
function totalRewardsRedeemed()
external
view
virtual
override
returns (uint256)
{
return _totalRewardsRedeemed;
}
function totalRewardsRedeemedFor(address token)
external
view
virtual
override
returns (uint256)
{
return _tokenData[token].rewardsRedeemed;
}
function totalShares()
external
view
virtual
override
returns (uint256 total)
{
for (uint256 i = 0; i < _tokens.length(); i++) {
total = total.add(_totalSharesForToken(_tokens.at(i)));
}
}
function totalSharesFor(address account)
external
view
virtual
override
returns (uint256 total)
{
EnumerableMap.AddressToUintMap storage staked = _users[account].staked;
for (uint256 i = 0; i < staked.length(); i++) {
(address token, uint256 amount) = staked.at(i);
total = total.add(_shares(token, amount));
}
}
function totalSharesForToken(address token)
external
view
virtual
override
returns (uint256)
{
return _totalSharesForToken(token);
}
function totalStaked(address token)
public
view
virtual
override
returns (uint256)
{
return _tokenData[token].totalStaked;
}
function unredeemableRewards()
external
view
virtual
override
returns (uint256)
{
return _unredeemableRewards;
}
function valuePerTokenImpl(address token)
public
view
virtual
override
returns (address)
{
return _tokenData[token].valueImpl;
}
/* Public Mutators */
function addToken(address token, address tokenValueImpl)
external
virtual
override
onlyOwner
{
require(!supportsStakingToken(token), "LPRewards: token already added");
require(
tokenValueImpl != address(0),
"LPRewards: tokenValueImpl cannot be zero address"
);
_tokens.add(token);
// Only update implementation in case this was previously used and removed
_tokenData[token].valueImpl = tokenValueImpl;
emit TokenAdded(_msgSender(), token, tokenValueImpl);
}
function changeTokenValueImpl(address token, address tokenValueImpl)
external
virtual
override
onlyOwner
supportsToken(token)
{
require(
tokenValueImpl != address(0),
"LPRewards: tokenValueImpl cannot be zero address"
);
_tokenData[token].valueImpl = tokenValueImpl;
emit TokenValueImplChanged(_msgSender(), token, tokenValueImpl);
}
function exit(bool asWETH) external virtual override {
unstakeAll();
redeemAllRewards(asWETH);
}
function exitFrom(address token, bool asWETH) external virtual override {
unstakeAllFrom(token);
redeemAllRewardsFrom(token, asWETH);
}
function pause() external virtual override onlyOwner {
_pause();
}
function recoverUnredeemableRewards(address to, uint256 amount)
external
virtual
override
onlyOwner
{
require(
amount <= _unredeemableRewards,
"LPRewards: recovery amount > unredeemable"
);
_unredeemableRewards -= amount;
IERC20(_rewardsToken).safeTransfer(to, amount);
emit RecoveredUnredeemableRewards(_msgSender(), to, amount);
}
function recoverUnstaked(
address token,
address to,
uint256 amount
) external virtual override onlyOwner {
require(token != _rewardsToken, "LPRewards: cannot recover rewardsToken");
uint256 unstaked =
IERC20(token).balanceOf(address(this)).sub(totalStaked(token));
require(amount <= unstaked, "LPRewards: recovery amount > unstaked");
IERC20(token).safeTransfer(to, amount);
emit RecoveredUnstaked(_msgSender(), token, to, amount);
}
function redeemAllRewards(bool asWETH) public virtual override {
address account = _msgSender();
_updateAllRewardsFor(account);
UserData storage user = _users[account];
EnumerableSet.AddressSet storage tokens = user.tokensWithRewards;
uint256 redemption = 0;
for (uint256 length = tokens.length(); length > 0; length--) {
address token = tokens.at(0);
TokenData storage td = _tokenData[token];
UserTokenRewards storage rewards = user.rewardsFor[token];
uint256 pending = rewards.pending; // Save gas
redemption += pending;
rewards.pending = 0;
td.rewards = td.rewards.sub(pending);
td.rewardsRedeemed += pending;
emit RewardPaid(account, token, pending);
tokens.remove(token);
}
_totalRewardsRedeemed += redemption;
_sendRewards(account, redemption, asWETH);
}
function redeemAllRewardsFrom(address token, bool asWETH)
public
virtual
override
{
address account = _msgSender();
_updateRewardFor(account, token);
uint256 pending = _users[account].rewardsFor[token].pending;
if (pending != 0) {
_redeemRewardFrom(token, pending, asWETH);
}
}
function redeemReward(uint256 amount, bool asWETH)
external
virtual
override
{
require(amount != 0, "LPRewards: cannot redeem zero");
address account = _msgSender();
_updateAllRewardsFor(account);
require(
amount <= lastRewardsBalanceOf(account),
"LPRewards: cannot redeem more rewards than earned"
);
UserData storage user = _users[account];
EnumerableSet.AddressSet storage tokens = user.tokensWithRewards;
uint256 amountLeft = amount;
for (uint256 length = tokens.length(); length > 0; length--) {
address token = tokens.at(0);
TokenData storage td = _tokenData[token];
UserTokenRewards storage rewards = user.rewardsFor[token];
uint256 pending = rewards.pending; // Save gas
uint256 taken = 0;
if (pending <= amountLeft) {
taken = pending;
tokens.remove(token);
} else {
taken = amountLeft;
}
rewards.pending = pending - taken;
td.rewards = td.rewards.sub(taken);
td.rewardsRedeemed += taken;
amountLeft -= taken;
emit RewardPaid(account, token, taken);
if (amountLeft == 0) {
break;
}
}
_totalRewardsRedeemed += amount;
_sendRewards(account, amount, asWETH);
}
function redeemRewardFrom(
address token,
uint256 amount,
bool asWETH
) external virtual override {
require(amount != 0, "LPRewards: cannot redeem zero");
address account = _msgSender();
_updateRewardFor(account, token);
require(
amount <= _users[account].rewardsFor[token].pending,
"LPRewards: cannot redeem more rewards than earned"
);
_redeemRewardFrom(token, amount, asWETH);
}
function removeToken(address token)
external
virtual
override
onlyOwner
supportsToken(token)
{
_tokens.remove(token);
// Clean up. Keep totalStaked and rewards since those will be cleaned up by
// users unstaking and redeeming.
_tokenData[token].valueImpl = address(0);
emit TokenRemoved(_msgSender(), token);
}
function setRewardsToken(address token) public virtual override onlyOwner {
_rewardsToken = token;
emit RewardsTokenSet(_msgSender(), token);
}
function stake(address token, uint256 amount)
external
virtual
override
whenNotPaused
supportsToken(token)
{
require(amount != 0, "LPRewards: cannot stake zero");
address account = _msgSender();
_updateRewardFor(account, token);
UserData storage user = _users[account];
TokenData storage td = _tokenData[token];
td.totalStaked += amount;
user.staked.set(token, amount + stakedBalanceOf(account, token));
IERC20(token).safeTransferFrom(account, address(this), amount);
emit Staked(account, token, amount);
}
function unpause() external virtual override onlyOwner {
_unpause();
}
function unstake(address token, uint256 amount) external virtual override {
require(amount != 0, "LPRewards: cannot unstake zero");
address account = _msgSender();
// Prevent making calls to any addresses that were never supported.
uint256 staked = stakedBalanceOf(account, token);
require(
amount <= staked,
"LPRewards: cannot unstake more than staked balance"
);
_unstake(token, amount);
}
function unstakeAll() public virtual override {
UserData storage user = _users[_msgSender()];
for (uint256 length = user.staked.length(); length > 0; length--) {
(address token, uint256 amount) = user.staked.at(0);
_unstake(token, amount);
}
}
function unstakeAllFrom(address token) public virtual override {
_unstake(token, stakedBalanceOf(_msgSender(), token));
}
function updateAccrual() external virtual override {
// Gas savings
uint256 totalRewardsAccrued_ = totalRewardsAccrued();
uint256 pending = totalRewardsAccrued_ - _lastTotalRewardsAccrued;
if (pending == 0) {
return;
}
_lastTotalRewardsAccrued = totalRewardsAccrued_;
// Iterate once to know totalShares
uint256 totalShares_ = 0;
// Store some math for current shares to save on gas and revert ASAP.
uint256[] memory pendingSharesFor = new uint256[](_tokens.length());
for (uint256 i = 0; i < _tokens.length(); i++) {
uint256 share = _totalSharesForToken(_tokens.at(i));
pendingSharesFor[i] = pending.mul(share);
totalShares_ = totalShares_.add(share);
}
if (totalShares_ == 0) {
_unredeemableRewards = _unredeemableRewards.add(pending);
emit AccrualUpdated(_msgSender(), pending);
return;
}
// Iterate twice to allocate rewards to each token.
for (uint256 i = 0; i < _tokens.length(); i++) {
address token = _tokens.at(i);
TokenData storage td = _tokenData[token];
td.rewards += pendingSharesFor[i] / totalShares_;
uint256 rewardsAccrued = totalRewardsAccruedFor(token);
td.arpt = _accruedRewardsPerTokenFor(token, rewardsAccrued);
td.lastRewardsAccrued = rewardsAccrued;
}
emit AccrualUpdated(_msgSender(), pending);
}
function updateReward() external virtual override {
_updateAllRewardsFor(_msgSender());
}
function updateRewardFor(address token) external virtual override {
_updateRewardFor(_msgSender(), token);
}
/* Internal Views */
function _accruedRewardsPerTokenFor(address token, uint256 rewardsAccrued)
internal
view
virtual
returns (uint256)
{
TokenData storage td = _tokenData[token];
// Gas savings
uint256 totalStaked_ = td.totalStaked;
if (totalStaked_ == 0) {
return td.arpt;
}
// Overflow is OK
uint256 delta = rewardsAccrued - td.lastRewardsAccrued;
if (delta == 0) {
return td.arpt;
}
// Use multiplier for better rounding
uint256 rewardsPerToken = delta.mul(_MULTIPLIER) / totalStaked_;
// Overflow is OK
return td.arpt + rewardsPerToken;
}
function _allPendingRewardsFor(address account)
internal
view
virtual
returns (uint256 total)
{
EnumerableMap.AddressToUintMap storage staked = _users[account].staked;
for (uint256 i = 0; i < staked.length(); i++) {
(address token, uint256 amount) = staked.at(i);
total += _pendingRewardsFor(account, token, amount);
}
}
function _currentRewardsBalance() internal view virtual returns (uint256) {
return IERC20(_rewardsToken).balanceOf(address(this));
}
function _pendingRewardsFor(
address account,
address token,
uint256 amountStaked
) internal view virtual returns (uint256) {
uint256 arpt = accruedRewardsPerTokenFor(token);
uint256 arptLast = accruedRewardsPerTokenLastFor(account, token);
// Overflow is OK
uint256 arptDelta = arpt - arptLast;
return amountStaked.mul(arptDelta) / _MULTIPLIER;
}
function _shares(address token, uint256 amountStaked)
internal
view
virtual
returns (uint256)
{
if (!supportsStakingToken(token)) {
return 0;
}
IValuePerToken vptHandle = IValuePerToken(valuePerTokenImpl(token));
(uint256 numerator, uint256 denominator) = vptHandle.valuePerToken();
if (denominator == 0) {
return 0;
}
// Return a 1:1 ratio for value to shares
return amountStaked.mul(numerator) / denominator;
}
function _totalSharesForToken(address token)
internal
view
virtual
returns (uint256)
{
return _shares(token, _tokenData[token].totalStaked);
}
/* Internal Mutators */
function _redeemRewardFrom(
address token,
uint256 amount,
bool asWETH
) internal virtual {
address account = _msgSender();
UserData storage user = _users[account];
UserTokenRewards storage rewards = user.rewardsFor[token];
TokenData storage td = _tokenData[token];
uint256 rewardLeft = rewards.pending - amount;
rewards.pending = rewardLeft;
if (rewardLeft == 0) {
user.tokensWithRewards.remove(token);
}
td.rewards = td.rewards.sub(amount);
td.rewardsRedeemed += amount;
_totalRewardsRedeemed += amount;
_sendRewards(account, amount, asWETH);
emit RewardPaid(account, token, amount);
}
function _sendRewards(
address to,
uint256 amount,
bool asWETH
) internal virtual {
if (asWETH) {
IERC20(_rewardsToken).safeTransfer(to, amount);
} else {
IWETH(_rewardsToken).withdraw(amount);
payable(to).sendValue(amount);
}
}
function _unstake(address token, uint256 amount) internal virtual {
address account = _msgSender();
_updateRewardFor(account, token);
TokenData storage td = _tokenData[token];
td.totalStaked = td.totalStaked.sub(amount);
UserData storage user = _users[account];
EnumerableMap.AddressToUintMap storage staked = user.staked;
uint256 stakeLeft = staked.get(token).sub(amount);
if (stakeLeft == 0) {
staked.remove(token);
user.rewardsFor[token].arptLast = 0;
} else {
staked.set(token, stakeLeft);
}
IERC20(token).safeTransfer(account, amount);
emit Unstaked(account, token, amount);
}
function _updateRewardFor(address account, address token)
internal
virtual
returns (uint256)
{
UserData storage user = _users[account];
UserTokenRewards storage rewards = user.rewardsFor[token];
uint256 total = rewards.pending; // Save gas
uint256 amountStaked = stakedBalanceOf(account, token);
uint256 pending = _pendingRewardsFor(account, token, amountStaked);
if (pending != 0) {
total += pending;
rewards.pending = total;
user.tokensWithRewards.add(token);
}
rewards.arptLast = accruedRewardsPerTokenFor(token);
return total;
}
function _updateAllRewardsFor(address account) internal virtual {
EnumerableMap.AddressToUintMap storage staked = _users[account].staked;
for (uint256 i = 0; i < staked.length(); i++) {
(address token, ) = staked.at(i);
_updateRewardFor(account, token);
}
}
}
// SPDX-License-Identifier: Apache-2.0
/**
* Copyright 2021 weiWard LLC
*
* 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.7.6;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../libraries/EnumerableMap.sol";
abstract contract LPRewardsData {
/* Structs */
struct TokenData {
uint256 arpt;
uint256 lastRewardsAccrued;
uint256 rewards;
uint256 rewardsRedeemed;
uint256 totalStaked;
address valueImpl;
}
struct UserTokenRewards {
uint256 pending;
uint256 arptLast;
}
struct UserData {
EnumerableSet.AddressSet tokensWithRewards;
mapping(address => UserTokenRewards) rewardsFor;
EnumerableMap.AddressToUintMap staked;
}
/* State */
address internal _rewardsToken;
uint256 internal _lastTotalRewardsAccrued;
uint256 internal _totalRewardsRedeemed;
uint256 internal _unredeemableRewards;
EnumerableSet.AddressSet internal _tokens;
mapping(address => TokenData) internal _tokenData;
mapping(address => UserData) internal _users;
uint256[43] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
/**
* Copyright 2021 weiWard LLC
*
* 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.7.6;
interface ILPRewards {
/* Views */
function accruedRewardsPerTokenFor(address token)
external
view
returns (uint256);
function accruedRewardsPerTokenLastFor(address account, address token)
external
view
returns (uint256);
function lastRewardsBalanceOf(address account)
external
view
returns (uint256);
function lastRewardsBalanceOfFor(address account, address token)
external
view
returns (uint256);
function lastTotalRewardsAccrued() external view returns (uint256);
function lastTotalRewardsAccruedFor(address token)
external
view
returns (uint256);
function numStakingTokens() external view returns (uint256);
function rewardsBalanceOf(address account) external view returns (uint256);
function rewardsBalanceOfFor(address account, address token)
external
view
returns (uint256);
function rewardsForToken(address token) external view returns (uint256);
function rewardsToken() external view returns (address);
function sharesFor(address account, address token)
external
view
returns (uint256);
function sharesPerToken(address token) external view returns (uint256);
function stakedBalanceOf(address account, address token)
external
view
returns (uint256);
function stakingTokenAt(uint256 index) external view returns (address);
function supportsStakingToken(address token) external view returns (bool);
function totalRewardsAccrued() external view returns (uint256);
function totalRewardsAccruedFor(address token)
external
view
returns (uint256);
function totalRewardsRedeemed() external view returns (uint256);
function totalRewardsRedeemedFor(address token)
external
view
returns (uint256);
function totalShares() external view returns (uint256);
function totalSharesFor(address account) external view returns (uint256);
function totalSharesForToken(address token) external view returns (uint256);
function totalStaked(address token) external view returns (uint256);
function unredeemableRewards() external view returns (uint256);
function valuePerTokenImpl(address token) external view returns (address);
/* Mutators */
function addToken(address token, address tokenValueImpl) external;
function changeTokenValueImpl(address token, address tokenValueImpl)
external;
function exit(bool asWETH) external;
function exitFrom(address token, bool asWETH) external;
function pause() external;
function recoverUnredeemableRewards(address to, uint256 amount) external;
function recoverUnstaked(
address token,
address to,
uint256 amount
) external;
function redeemAllRewards(bool asWETH) external;
function redeemAllRewardsFrom(address token, bool asWETH) external;
function redeemReward(uint256 amount, bool asWETH) external;
function redeemRewardFrom(
address token,
uint256 amount,
bool asWETH
) external;
function removeToken(address token) external;
function setRewardsToken(address token) external;
function stake(address token, uint256 amount) external;
function unpause() external;
function unstake(address token, uint256 amount) external;
function unstakeAll() external;
function unstakeAllFrom(address token) external;
function updateAccrual() external;
function updateReward() external;
function updateRewardFor(address token) external;
/* Events */
event AccrualUpdated(address indexed author, uint256 accruedRewards);
event RecoveredUnredeemableRewards(
address indexed author,
address indexed to,
uint256 amount
);
event RecoveredUnstaked(
address indexed author,
address indexed token,
address indexed to,
uint256 amount
);
event RewardPaid(
address indexed account,
address indexed token,
uint256 amount
);
event RewardsTokenSet(address indexed author, address indexed token);
event Staked(address indexed account, address indexed token, uint256 amount);
event TokenAdded(
address indexed author,
address indexed token,
address indexed tokenValueImpl
);
event TokenRemoved(address indexed author, address indexed token);
event TokenValueImplChanged(
address indexed author,
address indexed token,
address indexed tokenValueImpl
);
event Unstaked(
address indexed account,
address indexed token,
uint256 amount
);
}
// SPDX-License-Identifier: Apache-2.0
/**
* Copyright 2021 weiWard LLC
*
* 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.7.6;
interface IValuePerToken {
/* Views */
function token() external view returns (address);
function valuePerToken()
external
view
returns (uint256 numerator, uint256 denominator);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
| Returns the value associated with `key`. O(1). Requirements: - `key` must be in the map./ | function get(AddressToUintMap storage map, address key)
internal
view
returns (uint256)
{
return uint256(_get(map._inner, bytes32(uint256(key))));
}
| 5,926,034 |
./full_match/1/0xbdf5B4AEd51d9f77B5e808802355ebeCAb823185/sources/contracts/MyContract.sol | fetches and sorts the reserves for a pair | function getReserves(address pairAddress, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairAddress).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
| 17,099,074 |
//pragma solidity ^0.4.0;
contract Grammar18{
function testAddmod() public returns (uint z) {
//计算(x + y)%k,其中以任意精度执行加法,并且不在2 ** 256处围绕
z=addmod(2, 2, 3);
return z;
}
function testMulmod() public returns (uint z) {
//计算(x * y)%k,其中乘法以任意精度执行,并且不会在2 ** 256处循环。
z=mulmod(2, 3, 4);
return z;
}
function testKeccak256() public returns(bytes32){
//计算的(紧凑)参数的Ethereum-SHA-3(Keccak-256)的散列
return keccak256("11");
}
function testSha256() public returns(bytes32){
//计算(紧密包装)参数的SHA-256散列
return sha256("11");
}
function testSha3() public returns(bytes32){
//计算(紧密包装)参数的SHA-256散列
//return sha3("11");
return keccak256("11");
}
function testRipemd160() public returns(bytes32){
//计算(紧密包装)参数的RIPEMD-160哈希值
return ripemd160("11");
}
} | 计算的(紧凑)参数的Ethereum-SHA-3(Keccak-256)的散列 | function testKeccak256() public returns(bytes32){
return keccak256("11");
}
| 12,567,403 |
./partial_match/1/0xBA4C1c4AeD5d664588557546F5090e45aae99394/sources/MeiMachina.sol | remove limits after token is stable | function _removeSwapLimits() external onlyOwner returns (bool) {
_limitsInEffect = false;
return true;
}
| 15,980,749 |
/**
*Submitted for verification at Etherscan.io on 2021-11-01
*/
// Sources flattened with hardhat v2.6.7 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/security/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
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);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @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);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library 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");
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File contracts/interfaces/IAccessControl.sol
pragma solidity ^0.8.7;
/// @title IAccessControl
/// @author Forked from OpenZeppelin
/// @notice Interface for `AccessControl` contracts
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// File contracts/external/AccessControlUpgradeable.sol
pragma solidity ^0.8.7;
/**
* @dev This contract is fully forked from OpenZeppelin `AccessControlUpgradeable`.
* The only difference is the removal of the ERC165 implementation as it's not
* needed in Angle.
*
* Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, IAccessControl {
function __AccessControl_init() internal initializer {
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, msg.sender);
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external override {
require(account == msg.sender, "71");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) internal {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
function _revokeRole(bytes32 role, address account) internal {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
uint256[49] private __gap;
}
// File contracts/interfaces/IFeeManager.sol
pragma solidity ^0.8.7;
/// @title IFeeManagerFunctions
/// @author Angle Core Team
/// @dev Interface for the `FeeManager` contract
interface IFeeManagerFunctions is IAccessControl {
// ================================= Keepers ===================================
function updateUsersSLP() external;
function updateHA() external;
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
address _perpetualManager
) external;
function setFees(
uint256[] memory xArray,
uint64[] memory yArray,
uint8 typeChange
) external;
function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external;
}
/// @title IFeeManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev We need these getters as they are used in other contracts of the protocol
interface IFeeManager is IFeeManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
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 contracts/interfaces/IERC721.sol
pragma solidity ^0.8.7;
interface IERC721 is IERC165 {
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File contracts/interfaces/IOracle.sol
pragma solidity ^0.8.7;
/// @title IOracle
/// @author Angle Core Team
/// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink
/// from just UniswapV3 or from just Chainlink
interface IOracle {
function read() external view returns (uint256);
function readAll() external view returns (uint256 lowerRate, uint256 upperRate);
function readLower() external view returns (uint256);
function readUpper() external view returns (uint256);
function readQuote(uint256 baseAmount) external view returns (uint256);
function readQuoteLower(uint256 baseAmount) external view returns (uint256);
function inBase() external view returns (uint256);
}
// File contracts/interfaces/IPerpetualManager.sol
pragma solidity ^0.8.7;
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev Front interface, meaning only user-facing functions
interface IPerpetualManagerFront is IERC721Metadata {
function openPerpetual(
address owner,
uint256 amountBrought,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin
) external returns (uint256 perpetualID);
function closePerpetual(
uint256 perpetualID,
address to,
uint256 minCashOutAmount
) external;
function addToPerpetual(uint256 perpetualID, uint256 amount) external;
function removeFromPerpetual(
uint256 perpetualID,
uint256 amount,
address to
) external;
function liquidatePerpetuals(uint256[] memory perpetualIDs) external;
function forceClosePerpetuals(uint256[] memory perpetualIDs) external;
// ========================= External View Functions =============================
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256);
function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool);
}
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev This interface does not contain user facing functions, it just has functions that are
/// interacted with in other parts of the protocol
interface IPerpetualManagerFunctions is IAccessControl {
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
IFeeManager feeManager,
IOracle oracle_
) external;
function setFeeManager(IFeeManager feeManager_) external;
function setHAFees(
uint64[] memory _xHAFees,
uint64[] memory _yHAFees,
uint8 deposit
) external;
function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external;
function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external;
function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external;
function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external;
function setLockTime(uint64 _lockTime) external;
function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external;
function pause() external;
function unpause() external;
// ==================================== Keepers ================================
function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external;
// =============================== StableMaster ================================
function setOracle(IOracle _oracle) external;
}
/// @title IPerpetualManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables
interface IPerpetualManager is IPerpetualManagerFunctions {
function poolManager() external view returns (address);
function oracle() external view returns (address);
function targetHAHedge() external view returns (uint64);
function totalHedgeAmount() external view returns (uint256);
}
// File contracts/interfaces/IPoolManager.sol
pragma solidity ^0.8.7;
// Struct for the parameters associated to a strategy interacting with a collateral `PoolManager`
// contract
struct StrategyParams {
// Timestamp of last report made by this strategy
// It is also used to check if a strategy has been initialized
uint256 lastReport;
// Total amount the strategy is expected to have
uint256 totalStrategyDebt;
// The share of the total assets in the `PoolManager` contract that the `strategy` can access to.
uint256 debtRatio;
}
/// @title IPoolManagerFunctions
/// @author Angle Core Team
/// @notice Interface for the collateral poolManager contracts handling each one type of collateral for
/// a given stablecoin
/// @dev Only the functions used in other contracts of the protocol are left here
interface IPoolManagerFunctions {
// ============================ Constructor ====================================
function deployCollateral(
address[] memory governorList,
address guardian,
IPerpetualManager _perpetualManager,
IFeeManager feeManager,
IOracle oracle
) external;
// ============================ Yield Farming ==================================
function creditAvailable() external view returns (uint256);
function debtOutstanding() external view returns (uint256);
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external;
// ============================ Governance =====================================
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address _guardian, address guardian) external;
function revokeGuardian(address guardian) external;
function setFeeManager(IFeeManager _feeManager) external;
// ============================= Getters =======================================
function getBalance() external view returns (uint256);
function getTotalAsset() external view returns (uint256);
}
/// @title IPoolManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev Used in other contracts of the protocol
interface IPoolManager is IPoolManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
function token() external view returns (address);
function feeManager() external view returns (address);
function totalDebt() external view returns (uint256);
function strategies(address _strategy) external view returns (StrategyParams memory);
}
// File contracts/interfaces/IStakingRewards.sol
pragma solidity ^0.8.7;
/// @title IStakingRewardsFunctions
/// @author Angle Core Team
/// @notice Interface for the staking rewards contract that interact with the `RewardsDistributor` contract
interface IStakingRewardsFunctions {
function notifyRewardAmount(uint256 reward) external;
function recoverERC20(
address tokenAddress,
address to,
uint256 tokenAmount
) external;
function setNewRewardsDistribution(address newRewardsDistribution) external;
}
/// @title IStakingRewards
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables
interface IStakingRewards is IStakingRewardsFunctions {
function rewardToken() external view returns (IERC20);
}
// File contracts/interfaces/IRewardsDistributor.sol
pragma solidity ^0.8.7;
/// @title IRewardsDistributor
/// @author Angle Core Team, inspired from Fei protocol
/// (https://github.com/fei-protocol/fei-protocol-core/blob/master/contracts/staking/IRewardsDistributor.sol)
/// @notice Rewards Distributor interface
interface IRewardsDistributor {
// ========================= Public Parameter Getter ===========================
function rewardToken() external view returns (IERC20);
// ======================== External User Available Function ===================
function drip(IStakingRewards stakingContract) external returns (uint256);
// ========================= Governor Functions ================================
function governorWithdrawRewardToken(uint256 amount, address governance) external;
function governorRecover(
address tokenAddress,
address to,
uint256 amount,
IStakingRewards stakingContract
) external;
function setUpdateFrequency(uint256 _frequency, IStakingRewards stakingContract) external;
function setIncentiveAmount(uint256 _incentiveAmount, IStakingRewards stakingContract) external;
function setAmountToDistribute(uint256 _amountToDistribute, IStakingRewards stakingContract) external;
function setDuration(uint256 _duration, IStakingRewards stakingContract) external;
function setStakingContract(
address _stakingContract,
uint256 _duration,
uint256 _incentiveAmount,
uint256 _dripFrequency,
uint256 _amountToDistribute
) external;
function setNewRewardsDistributor(address newRewardsDistributor) external;
function removeStakingContract(IStakingRewards stakingContract) external;
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
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);
}
// File contracts/interfaces/ISanToken.sol
pragma solidity ^0.8.7;
/// @title ISanToken
/// @author Angle Core Team
/// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs
/// contributing to a collateral for a given stablecoin
interface ISanToken is IERC20Upgradeable {
// ================================== StableMaster =============================
function mint(address account, uint256 amount) external;
function burnFrom(
uint256 amount,
address burner,
address sender
) external;
function burnSelf(uint256 amount, address burner) external;
function stableMaster() external view returns (address);
function poolManager() external view returns (address);
}
// File contracts/interfaces/IStableMaster.sol
pragma solidity ^0.8.7;
// Normally just importing `IPoolManager` should be sufficient, but for clarity here
// we prefer to import all concerned interfaces
// Struct to handle all the parameters to manage the fees
// related to a given collateral pool (associated to the stablecoin)
struct MintBurnData {
// Values of the thresholds to compute the minting fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeMint;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeMint;
// Values of the thresholds to compute the burning fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeBurn;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeBurn;
// Max proportion of collateral from users that can be covered by HAs
// It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated
// the other changes accordingly
uint64 targetHAHedge;
// Minting fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusMint;
// Burning fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusBurn;
// Parameter used to limit the number of stablecoins that can be issued using the concerned collateral
uint256 capOnStableMinted;
}
// Struct to handle all the variables and parameters to handle SLPs in the protocol
// including the fraction of interests they receive or the fees to be distributed to
// them
struct SLPData {
// Last timestamp at which the `sanRate` has been updated for SLPs
uint256 lastBlockUpdated;
// Fees accumulated from previous blocks and to be distributed to SLPs
uint256 lockedInterests;
// Max interests used to update the `sanRate` in a single block
// Should be in collateral token base
uint256 maxInterestsDistributed;
// Amount of fees left aside for SLPs and that will be distributed
// when the protocol is collateralized back again
uint256 feesAside;
// Part of the fees normally going to SLPs that is left aside
// before the protocol is collateralized back again (depends on collateral ratio)
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippageFee;
// Portion of the fees from users minting and burning
// that goes to SLPs (the rest goes to surplus)
uint64 feesForSLPs;
// Slippage factor that's applied to SLPs exiting (depends on collateral ratio)
// If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippage;
// Portion of the interests from lending
// that goes to SLPs (the rest goes to surplus)
uint64 interestsForSLPs;
}
/// @title IStableMasterFunctions
/// @author Angle Core Team
/// @notice Interface for the `StableMaster` contract
interface IStableMasterFunctions {
function deploy(
address[] memory _governorList,
address _guardian,
address _agToken
) external;
// ============================== Lending ======================================
function accumulateInterest(uint256 gain) external;
function signalLoss(uint256 loss) external;
// ============================== HAs ==========================================
function getStocksUsers() external view returns (uint256 maxCAmountInStable);
function convertToSLP(uint256 amount, address user) external;
// ============================== Keepers ======================================
function getCollateralRatio() external returns (uint256);
function setFeeKeeper(
uint64 feeMint,
uint64 feeBurn,
uint64 _slippage,
uint64 _slippageFee
) external;
// ============================== AgToken ======================================
function updateStocksUsers(uint256 amount, address poolManager) external;
// ============================= Governance ====================================
function setCore(address newCore) external;
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address newGuardian, address oldGuardian) external;
function revokeGuardian(address oldGuardian) external;
function setCapOnStableAndMaxInterests(
uint256 _capOnStableMinted,
uint256 _maxInterestsDistributed,
IPoolManager poolManager
) external;
function setIncentivesForSLPs(
uint64 _feesForSLPs,
uint64 _interestsForSLPs,
IPoolManager poolManager
) external;
function setUserFees(
IPoolManager poolManager,
uint64[] memory _xFee,
uint64[] memory _yFee,
uint8 _mint
) external;
function setTargetHAHedge(uint64 _targetHAHedge) external;
function pause(bytes32 agent, IPoolManager poolManager) external;
function unpause(bytes32 agent, IPoolManager poolManager) external;
}
/// @title IStableMaster
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
interface IStableMaster is IStableMasterFunctions {
function agToken() external view returns (address);
function collateralMap(IPoolManager poolManager)
external
view
returns (
IERC20 token,
ISanToken sanToken,
IPerpetualManager perpetualManager,
IOracle oracle,
uint256 stocksUsers,
uint256 sanRate,
uint256 collatBase,
SLPData memory slpData,
MintBurnData memory feeData
);
}
// File contracts/utils/FunctionUtils.sol
pragma solidity ^0.8.7;
/// @title FunctionUtils
/// @author Angle Core Team
/// @notice Contains all the utility functions that are needed in different places of the protocol
/// @dev Functions in this contract should typically be pure functions
/// @dev This contract is voluntarily a contract and not a library to save some gas cost every time it is used
contract FunctionUtils {
/// @notice Base that is used to compute ratios and floating numbers
uint256 public constant BASE_TOKENS = 10**18;
/// @notice Base that is used to define parameters that need to have a floating value (for instance parameters
/// that are defined as ratios)
uint256 public constant BASE_PARAMS = 10**9;
/// @notice Computes the value of a linear by part function at a given point
/// @param x Point of the function we want to compute
/// @param xArray List of breaking points (in ascending order) that define the linear by part function
/// @param yArray List of values at breaking points (not necessarily in ascending order)
/// @dev The evolution of the linear by part function between two breaking points is linear
/// @dev Before the first breaking point and after the last one, the function is constant with a value
/// equal to the first or last value of the yArray
/// @dev This function is relevant if `x` is between O and `BASE_PARAMS`. If `x` is greater than that, then
/// everything will be as if `x` is equal to the greater element of the `xArray`
function _piecewiseLinear(
uint64 x,
uint64[] memory xArray,
uint64[] memory yArray
) internal pure returns (uint64) {
if (x >= xArray[xArray.length - 1]) {
return yArray[xArray.length - 1];
} else if (x <= xArray[0]) {
return yArray[0];
} else {
uint256 lower;
uint256 upper = xArray.length - 1;
uint256 mid;
while (upper - lower > 1) {
mid = lower + (upper - lower) / 2;
if (xArray[mid] <= x) {
lower = mid;
} else {
upper = mid;
}
}
if (yArray[upper] > yArray[lower]) {
// There is no risk of overflow here as in the product of the difference of `y`
// with the difference of `x`, the product is inferior to `BASE_PARAMS**2` which does not
// overflow for `uint64`
return
yArray[lower] +
((yArray[upper] - yArray[lower]) * (x - xArray[lower])) /
(xArray[upper] - xArray[lower]);
} else {
return
yArray[lower] -
((yArray[lower] - yArray[upper]) * (x - xArray[lower])) /
(xArray[upper] - xArray[lower]);
}
}
}
/// @notice Checks if the input arrays given by governance to update the fee structure is valid
/// @param xArray List of breaking points (in ascending order) that define the linear by part function
/// @param yArray List of values at breaking points (not necessarily in ascending order)
/// @dev This function is a way to avoid some governance attacks or errors
/// @dev The modifier checks if the arrays have a non null length, if their length is the same, if the values
/// in the `xArray` are in ascending order and if the values in the `xArray` and in the `yArray` are not superior
/// to `BASE_PARAMS`
modifier onlyCompatibleInputArrays(uint64[] memory xArray, uint64[] memory yArray) {
require(xArray.length == yArray.length && xArray.length > 0, "5");
for (uint256 i = 0; i <= yArray.length - 1; i++) {
require(yArray[i] <= uint64(BASE_PARAMS) && xArray[i] <= uint64(BASE_PARAMS), "6");
if (i > 0) {
require(xArray[i] > xArray[i - 1], "7");
}
}
_;
}
/// @notice Checks if the new value given for the parameter is consistent (it should be inferior to 1
/// if it corresponds to a ratio)
/// @param fees Value of the new parameter to check
modifier onlyCompatibleFees(uint64 fees) {
require(fees <= BASE_PARAMS, "4");
_;
}
/// @notice Checks if the new address given is not null
/// @param newAddress Address to check
/// @dev Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#missing-zero-address-validation
modifier zeroCheck(address newAddress) {
require(newAddress != address(0), "0");
_;
}
}
// File contracts/perpetualManager/PerpetualManagerEvents.sol
pragma solidity ^0.8.7;
// Used in the `forceCashOutPerpetuals` function to store owners of perpetuals which have been force cashed
// out, along with the amount associated to it
struct Pairs {
address owner;
uint256 netCashOutAmount;
}
/// @title PerpetualManagerEvents
/// @author Angle Core Team
/// @notice `PerpetualManager` is the contract handling all the Hedging Agents perpetuals
/// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol
/// @dev This file contains all the events of the `PerpetualManager` contract
contract PerpetualManagerEvents {
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);
event PerpetualUpdated(uint256 _perpetualID, uint256 _margin);
event PerpetualOpened(uint256 _perpetualID, uint256 _entryRate, uint256 _margin, uint256 _committedAmount);
event PerpetualClosed(uint256 _perpetualID, uint256 _closeAmount);
event PerpetualsForceClosed(uint256[] perpetualIDs, Pairs[] ownerAndCashOut, address keeper, uint256 reward);
event KeeperTransferred(address keeperAddress, uint256 liquidationFees);
// ============================== Parameters ===================================
event BaseURIUpdated(string _baseURI);
event LockTimeUpdated(uint64 _lockTime);
event KeeperFeesCapUpdated(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap);
event TargetAndLimitHAHedgeUpdated(uint64 _targetHAHedge, uint64 _limitHAHedge);
event BoundsPerpetualUpdated(uint64 _maxLeverage, uint64 _maintenanceMargin);
event HAFeesUpdated(uint64[] _xHAFees, uint64[] _yHAFees, uint8 deposit);
event KeeperFeesLiquidationRatioUpdated(uint64 _keeperFeesLiquidationRatio);
event KeeperFeesClosingUpdated(uint64[] xKeeperFeesClosing, uint64[] yKeeperFeesClosing);
// =============================== Reward ======================================
event RewardAdded(uint256 _reward);
event RewardPaid(address indexed _user, uint256 _reward);
event RewardsDistributionUpdated(address indexed _rewardsDistributor);
event RewardsDistributionDurationUpdated(uint256 _rewardsDuration, address indexed _rewardsDistributor);
event Recovered(address indexed tokenAddress, address indexed to, uint256 amount);
}
// File contracts/perpetualManager/PerpetualManagerStorage.sol
pragma solidity ^0.8.7;
struct Perpetual {
// Oracle value at the moment of perpetual opening
uint256 entryRate;
// Timestamp at which the perpetual was opened
uint256 entryTimestamp;
// Amount initially brought in the perpetual (net from fees) + amount added - amount removed from it
// This is the only element that can be modified in the perpetual after its creation
uint256 margin;
// Amount of collateral covered by the perpetual. This cannot be modified once the perpetual is opened.
// The amount covered is used interchangeably with the amount hedged
uint256 committedAmount;
}
/// @title PerpetualManagerStorage
/// @author Angle Core Team
/// @notice `PerpetualManager` is the contract handling all the Hedging Agents positions and perpetuals
/// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol
/// @dev This file contains all the parameters and references used in the `PerpetualManager` contract
// solhint-disable-next-line max-states-count
contract PerpetualManagerStorage is PerpetualManagerEvents, FunctionUtils {
// Base used in the collateral implementation (ERC20 decimal)
uint256 internal _collatBase;
// ============================== Perpetual Variables ==========================
/// @notice Total amount of stablecoins that are insured (i.e. that could be redeemed against
/// collateral thanks to HAs)
/// When a HA opens a perpetual, it covers/hedges a fixed amount of stablecoins for the protocol, equal to
/// the committed amount times the entry rate
/// `totalHedgeAmount` is the sum of all these hedged amounts
uint256 public totalHedgeAmount;
// Counter to generate a unique `perpetualID` for each perpetual
CountersUpgradeable.Counter internal _perpetualIDcount;
// ========================== Mutable References ============================
/// @notice `Oracle` to give the rate feed, that is the price of the collateral
/// with respect to the price of the stablecoin
/// This reference can be modified by the corresponding `StableMaster` contract
IOracle public oracle;
// `FeeManager` address allowed to update the way fees are computed for this contract
// This reference can be modified by the `PoolManager` contract
IFeeManager internal _feeManager;
// ========================== Immutable References ==========================
/// @notice Interface for the `rewardToken` distributed as a reward
/// As of Angle V1, only a single `rewardToken` can be distributed to HAs who own a perpetual
/// This implementation assumes that reward tokens have a base of 18 decimals
IERC20 public rewardToken;
/// @notice Address of the `PoolManager` instance
IPoolManager public poolManager;
// Address of the `StableMaster` instance
IStableMaster internal _stableMaster;
// Interface for the underlying token accepted by this contract
// This reference cannot be changed, it is taken from the `PoolManager`
IERC20 internal _token;
// ======================= Fees and other Parameters ===========================
/// Deposit fees for HAs depend on the hedge ratio that is the ratio between what is hedged
/// (or covered, this is a synonym) by HAs compared with the total amount to hedge
/// @notice Thresholds for the ratio between to amount hedged and the amount to hedge
/// The bigger the ratio the bigger the fees will be because this means that the max amount
/// to insure is soon to be reached
uint64[] public xHAFeesDeposit;
/// @notice Deposit fees at threshold values
/// This array should have the same length as the array above
/// The evolution of the fees between two threshold values is linear
uint64[] public yHAFeesDeposit;
/// Withdraw fees for HAs also depend on the hedge ratio
/// @notice Thresholds for the hedge ratio
uint64[] public xHAFeesWithdraw;
/// @notice Withdraw fees at threshold values
uint64[] public yHAFeesWithdraw;
/// @notice Maintenance Margin (in `BASE_PARAMS`) for each perpetual
/// The margin ratio is defined for a perpetual as: `(initMargin + PnL) / committedAmount` where
/// `PnL = committedAmount * (1 - initRate/currentRate)`
/// If the `marginRatio` is below `maintenanceMargin`: then the perpetual can be liquidated
uint64 public maintenanceMargin;
/// @notice Maximum leverage multiplier authorized for HAs (`in BASE_PARAMS`)
/// Leverage for a perpetual here corresponds to the ratio between the amount committed
/// and the margin of the perpetual
uint64 public maxLeverage;
/// @notice Target proportion of stablecoins issued using this collateral to insure with HAs.
/// This variable is exactly the same as the one in the `StableMaster` contract for this collateral.
/// Above this hedge ratio, HAs cannot open new perpetuals
/// When keepers are forcing the closing of some perpetuals, they are incentivized to bringing
/// the hedge ratio to this proportion
uint64 public targetHAHedge;
/// @notice Limit proportion of stablecoins issued using this collateral that HAs can insure
/// Above this ratio `forceCashOut` is activated and anyone can see its perpetual cashed out
uint64 public limitHAHedge;
/// @notice Extra parameter from the `FeeManager` contract that is multiplied to the fees from above and that
/// can be used to change deposit fees. It works as a bonus - malus fee, if `haBonusMalusDeposit > BASE_PARAMS`,
/// then the fee will be larger than `haFeesDeposit`, if `haBonusMalusDeposit < BASE_PARAMS`, fees will be smaller.
/// This parameter, updated by keepers in the `FeeManager` contract, could most likely depend on the collateral ratio
uint64 public haBonusMalusDeposit;
/// @notice Extra parameter from the `FeeManager` contract that is multiplied to the fees from above and that
/// can be used to change withdraw fees. It works as a bonus - malus fee, if `haBonusMalusWithdraw > BASE_PARAMS`,
/// then the fee will be larger than `haFeesWithdraw`, if `haBonusMalusWithdraw < BASE_PARAMS`, fees will be smaller
uint64 public haBonusMalusWithdraw;
/// @notice Amount of time before HAs are allowed to withdraw funds from their perpetuals
/// either using `removeFromPerpetual` or `closePerpetual`. New perpetuals cannot be forced closed in
/// situations where the `forceClosePerpetuals` function is activated before this `lockTime` elapsed
uint64 public lockTime;
// ================================= Keeper fees ======================================
// All these parameters can be modified by their corresponding governance function
/// @notice Portion of the leftover cash out amount of liquidated perpetuals that go to
/// liquidating keepers
uint64 public keeperFeesLiquidationRatio;
/// @notice Cap on the fees that go to keepers liquidating a perpetual
/// If a keeper liquidates n perpetuals in a single transaction, then this keeper is entitled to get as much as
/// `n * keeperFeesLiquidationCap` as a reward
uint256 public keeperFeesLiquidationCap;
/// @notice Cap on the fees that go to keepers closing perpetuals when too much collateral is hedged by HAs
/// (hedge ratio above `limitHAHedge`)
/// If a keeper forces the closing of n perpetuals in a single transaction, then this keeper is entitled to get
/// as much as `keeperFeesClosingCap`. This cap amount is independent of the number of perpetuals closed
uint256 public keeperFeesClosingCap;
/// @notice Thresholds on the values of the rate between the current hedged amount (`totalHedgeAmount`) and the
/// target hedged amount by HAs (`targetHedgeAmount`) divided by 2. A value of `0.5` corresponds to a hedge ratio
/// of `1`. Doing this allows to maintain an array with values of `x` inferior to `BASE_PARAMS`.
uint64[] public xKeeperFeesClosing;
/// @notice Values at thresholds of the proportions of the fees that should go to keepers closing perpetuals
uint64[] public yKeeperFeesClosing;
// =========================== Staking Parameters ==============================
/// @notice Below are parameters that can also be found in other staking contracts
/// to be able to compute rewards from staking (having perpetuals here) correctly
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public rewardsDuration;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
address public rewardsDistribution;
// ============================== ERC721 Base URI ==============================
/// @notice URI used for the metadata of the perpetuals
string public baseURI;
// =============================== Mappings ====================================
/// @notice Mapping from `perpetualID` to perpetual data
mapping(uint256 => Perpetual) public perpetualData;
/// @notice Mapping used to compute the rewards earned by a perpetual in a timeframe
mapping(uint256 => uint256) public perpetualRewardPerTokenPaid;
/// @notice Mapping used to get how much rewards in governance tokens are gained by a perpetual
// identified by its ID
mapping(uint256 => uint256) public rewards;
// Mapping from `perpetualID` to owner address
mapping(uint256 => address) internal _owners;
// Mapping from owner address to perpetual owned count
mapping(address => uint256) internal _balances;
// Mapping from `perpetualID` to approved address
mapping(uint256 => address) internal _perpetualApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
}
// File contracts/perpetualManager/PerpetualManagerInternal.sol
pragma solidity ^0.8.7;
/// @title PerpetualManagerInternal
/// @author Angle Core Team
/// @notice `PerpetualManager` is the contract handling all the Hedging Agents perpetuals
/// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol
/// @dev This file contains all the internal functions of the `PerpetualManager` contract
contract PerpetualManagerInternal is PerpetualManagerStorage {
using Address for address;
using SafeERC20 for IERC20;
// ======================== State Modifying Functions ==========================
/// @notice Cashes out a perpetual, which means that it simply deletes the references to the perpetual
/// in the contract
/// @param perpetualID ID of the perpetual
/// @param perpetual Data of the perpetual
function _closePerpetual(uint256 perpetualID, Perpetual memory perpetual) internal {
// Handling the staking logic
// Reward should always be updated before the `totalHedgeAmount`
// Rewards are distributed to the perpetual which is liquidated
uint256 hedge = perpetual.committedAmount * perpetual.entryRate;
_getReward(perpetualID, hedge);
delete perpetualRewardPerTokenPaid[perpetualID];
// Updating `totalHedgeAmount` to represent the fact that less money is insured
totalHedgeAmount -= hedge / _collatBase;
_burn(perpetualID);
}
/// @notice Allows the protocol to transfer collateral to an address while handling the case where there are
/// not enough reserves
/// @param owner Address of the receiver
/// @param amount The amount of collateral sent
/// @dev If there is not enough collateral in balance (this can happen when money has been lent to strategies),
/// then the owner is reimbursed by receiving what is missing in sanTokens at the correct value
function _secureTransfer(address owner, uint256 amount) internal {
uint256 curBalance = poolManager.getBalance();
if (curBalance >= amount && amount > 0) {
// Case where there is enough in reserves to reimburse the person
_token.safeTransferFrom(address(poolManager), owner, amount);
} else if (amount > 0) {
// When there is not enough to reimburse the entire amount, the protocol reimburses
// what it can using its reserves and the rest is paid in sanTokens at the current
// exchange rate
uint256 amountLeft = amount - curBalance;
_token.safeTransferFrom(address(poolManager), owner, curBalance);
_stableMaster.convertToSLP(amountLeft, owner);
}
}
/// @notice Checks whether the perpetual should be liquidated or not, and if so liquidates the perpetual
/// @param perpetualID ID of the perpetual to check and potentially liquidate
/// @param perpetual Data of the perpetual to check
/// @param rateDown Oracle value to compute the cash out amount of the perpetual
/// @return Cash out amount of the perpetual
/// @return Whether the perpetual was liquidated or not
/// @dev Generally, to check for the liquidation of a perpetual, we use the lowest oracle value possible:
/// it's the one that is most at the advantage of the protocol, hence the `rateDown` parameter
function _checkLiquidation(
uint256 perpetualID,
Perpetual memory perpetual,
uint256 rateDown
) internal returns (uint256, uint256) {
uint256 liquidated;
(uint256 cashOutAmount, uint256 reachMaintenanceMargin) = _getCashOutAmount(perpetual, rateDown);
if (cashOutAmount == 0 || reachMaintenanceMargin == 1) {
_closePerpetual(perpetualID, perpetual);
// No need for an event to find out that a perpetual is liquidated
liquidated = 1;
}
return (cashOutAmount, liquidated);
}
// ========================= Internal View Functions ===========================
/// @notice Gets the current cash out amount of a perpetual
/// @param perpetual Data of the concerned perpetual
/// @param rate Value of the oracle
/// @return cashOutAmount Amount that the HA could get by closing this perpetual
/// @return reachMaintenanceMargin Whether the position of the perpetual is now too small
/// compared with its initial position
/// @dev Refer to the whitepaper or the doc for the formulas of the cash out amount
/// @dev The notion of `maintenanceMargin` is standard in centralized platforms offering perpetual futures
function _getCashOutAmount(Perpetual memory perpetual, uint256 rate)
internal
view
returns (uint256 cashOutAmount, uint256 reachMaintenanceMargin)
{
// All these computations are made just because we are working with uint and not int
// so we cannot do x-y if x<y
uint256 newCommit = (perpetual.committedAmount * perpetual.entryRate) / rate;
// Checking if a liquidation is needed: for this to happen the `cashOutAmount` should be inferior
// to the maintenance margin of the perpetual
reachMaintenanceMargin;
if (newCommit >= perpetual.committedAmount + perpetual.margin) cashOutAmount = 0;
else {
// The definition of the margin ratio is `(margin + PnL) / committedAmount`
// where `PnL = commit * (1-entryRate/currentRate)`
// So here: `newCashOutAmount = margin + PnL`
cashOutAmount = perpetual.committedAmount + perpetual.margin - newCommit;
if (cashOutAmount * BASE_PARAMS <= perpetual.committedAmount * maintenanceMargin)
reachMaintenanceMargin = 1;
}
}
/// @notice Calls the oracle to read both Chainlink and Uniswap rates
/// @return The lowest oracle value (between Chainlink and Uniswap) is the first outputted value
/// @return The highest oracle value is the second output
/// @dev If the oracle only involves a single oracle fees (like just Chainlink for USD-EUR),
/// the same value is returned twice
function _getOraclePrice() internal view returns (uint256, uint256) {
return oracle.readAll();
}
/// @notice Computes the incentive for the keeper as a function of the cash out amount of a liquidated perpetual
/// which value falls below its maintenance margin
/// @param cashOutAmount Value remaining in the perpetual
/// @dev By computing keeper fees as a fraction of the cash out amount of a perpetual rather than as a fraction
/// of the `committedAmount`, keepers are incentivized to react fast when a perpetual is below the maintenance margin
/// @dev Perpetual exchange protocols typically compute liquidation fees using an equivalent of the `committedAmount`,
/// this is not the case here
function _computeKeeperLiquidationFees(uint256 cashOutAmount) internal view returns (uint256 keeperFees) {
keeperFees = (cashOutAmount * keeperFeesLiquidationRatio) / BASE_PARAMS;
keeperFees = keeperFees < keeperFeesLiquidationCap ? keeperFees : keeperFeesLiquidationCap;
}
/// @notice Gets the value of the hedge ratio that is the ratio between the amount currently hedged by HAs
/// and the target amount that should be hedged by them
/// @param currentHedgeAmount Amount currently covered by HAs
/// @return ratio Ratio between the amount of collateral (in stablecoin value) currently hedged
/// and the target amount to hedge
function _computeHedgeRatio(uint256 currentHedgeAmount) internal view returns (uint64 ratio) {
// Fetching info from the `StableMaster`: the amount to hedge is based on the `stocksUsers`
// of the given collateral
uint256 targetHedgeAmount = (_stableMaster.getStocksUsers() * targetHAHedge) / BASE_PARAMS;
if (currentHedgeAmount < targetHedgeAmount)
ratio = uint64((currentHedgeAmount * BASE_PARAMS) / targetHedgeAmount);
else ratio = uint64(BASE_PARAMS);
}
// =========================== Fee Computation =================================
/// @notice Gets the net margin corrected from the fees at perpetual opening
/// @param margin Amount brought in the perpetual at creation
/// @param totalHedgeAmountUpdate Amount of stablecoins that this perpetual is going to insure
/// @param committedAmount Committed amount in the perpetual, we need it to compute the fees
/// paid by the HA
/// @return netMargin Amount that will be written in the perpetual as the `margin`
/// @dev The amount of stablecoins insured by a perpetual is `committedAmount * oracleRate / _collatBase`
function _getNetMargin(
uint256 margin,
uint256 totalHedgeAmountUpdate,
uint256 committedAmount
) internal view returns (uint256 netMargin) {
// Checking if the HA has the right to open a perpetual with such amount
// If HAs hedge more than the target amount, then new HAs will not be able to create perpetuals
// The amount hedged by HAs after opening the perpetual is going to be:
uint64 ratio = _computeHedgeRatio(totalHedgeAmount + totalHedgeAmountUpdate);
require(ratio < uint64(BASE_PARAMS), "25");
// Computing the net margin of HAs to store in the perpetual: it consists simply in deducing fees
// Those depend on how much is already hedged by HAs compared with what's to hedge
uint256 haFeesDeposit = (haBonusMalusDeposit * _piecewiseLinear(ratio, xHAFeesDeposit, yHAFeesDeposit)) /
BASE_PARAMS;
// Fees are rounded to the advantage of the protocol
haFeesDeposit = committedAmount - (committedAmount * (BASE_PARAMS - haFeesDeposit)) / BASE_PARAMS;
// Fees are computed based on the committed amount of the perpetual
// The following reverts if fees are too big compared to the margin
netMargin = margin - haFeesDeposit;
}
/// @notice Gets the net amount to give to a HA (corrected from the fees) in case of a perpetual closing
/// @param committedAmount Committed amount in the perpetual
/// @param cashOutAmount The current cash out amount of the perpetual
/// @param ratio What's hedged divided by what's to hedge
/// @return netCashOutAmount Amount that will be distributed to the HA
/// @return feesPaid Amount of fees paid by the HA at perpetual closing
/// @dev This function is called by the `closePerpetual` and by the `forceClosePerpetuals`
/// function
/// @dev The amount of fees paid by the HA is used to compute the incentive given to HAs closing perpetuals
/// when too much is covered
function _getNetCashOutAmount(
uint256 cashOutAmount,
uint256 committedAmount,
uint64 ratio
) internal view returns (uint256 netCashOutAmount, uint256 feesPaid) {
feesPaid = (haBonusMalusWithdraw * _piecewiseLinear(ratio, xHAFeesWithdraw, yHAFeesWithdraw)) / BASE_PARAMS;
// Rounding the fees at the protocol's advantage
feesPaid = committedAmount - (committedAmount * (BASE_PARAMS - feesPaid)) / BASE_PARAMS;
if (feesPaid >= cashOutAmount) {
netCashOutAmount = 0;
feesPaid = cashOutAmount;
} else {
netCashOutAmount = cashOutAmount - feesPaid;
}
}
// ========================= Reward Distribution ===============================
/// @notice View function to query the last timestamp at which a reward was distributed
/// @return Current timestamp if a reward is being distributed or the last timestamp
function _lastTimeRewardApplicable() internal view returns (uint256) {
uint256 returnValue = block.timestamp < periodFinish ? block.timestamp : periodFinish;
return returnValue;
}
/// @notice Used to actualize the `rewardPerTokenStored`
/// @dev It adds to the reward per token: the time elapsed since the `rewardPerTokenStored`
/// was last updated multiplied by the `rewardRate` divided by the number of tokens
/// @dev Specific attention should be placed on the base here: `rewardRate` is in the base of the reward token
/// and `totalHedgeAmount` is in `BASE_TOKENS` here: as this function concerns an amount of reward
/// tokens, the output of this function should be in the base of the reward token too
function _rewardPerToken() internal view returns (uint256) {
if (totalHedgeAmount == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored +
((_lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * BASE_TOKENS) /
totalHedgeAmount;
}
/// @notice Allows a perpetual owner to withdraw rewards
/// @param perpetualID ID of the perpetual which accumulated tokens
/// @param hedge Perpetual commit amount times the entry rate
/// @dev Internal version of the `getReward` function
/// @dev In case where an approved address calls to close a perpetual, rewards are still going to get distributed
/// to the owner of the perpetual, and not necessarily to the address getting the proceeds of the perpetual
function _getReward(uint256 perpetualID, uint256 hedge) internal {
_updateReward(perpetualID, hedge);
uint256 reward = rewards[perpetualID];
if (reward > 0) {
rewards[perpetualID] = 0;
address owner = _owners[perpetualID];
// Attention here, there may be reentrancy attacks because of the following call
// to an external contract done before other things are modified. Yet since the `rewardToken`
// is mostly going to be a trusted contract controlled by governance (namely the ANGLE token), then
// there is no point in putting an expensive `nonReentrant` modifier in the functions in `PerpetualManagerFront`
// that allow indirect interactions with `_updateReward`. If new `rewardTokens` are set, we could think about
// upgrading the `PerpetualManagerFront` contract
rewardToken.safeTransfer(owner, reward);
emit RewardPaid(owner, reward);
}
}
/// @notice Allows to check the amount of gov tokens earned by a perpetual
/// @param perpetualID ID of the perpetual which accumulated tokens
/// @param hedge Perpetual commit amount times the entry rate
/// @return Amount of gov tokens earned by the perpetual
/// @dev A specific attention should be paid to have the base here: we consider that each HA stakes an amount
/// equal to `committedAmount * entryRate / _collatBase`, here as the `hedge` corresponds to `committedAmount * entryRate`,
/// we just need to divide by `_collatBase`
/// @dev HAs earn reward tokens which are in base `BASE_TOKENS`
function _earned(uint256 perpetualID, uint256 hedge) internal view returns (uint256) {
return
(hedge * (_rewardPerToken() - perpetualRewardPerTokenPaid[perpetualID])) /
BASE_TOKENS /
_collatBase +
rewards[perpetualID];
}
/// @notice Updates the amount of gov tokens earned by a perpetual
/// @param perpetualID of the perpetual which earns tokens
/// @param hedge Perpetual commit amount times the entry rate
/// @dev When this function is called in the code, it has already been checked that the `perpetualID`
/// exists
function _updateReward(uint256 perpetualID, uint256 hedge) internal {
rewardPerTokenStored = _rewardPerToken();
lastUpdateTime = _lastTimeRewardApplicable();
// No need to check if the `perpetualID` exists here, it has already been checked
// in the code before when this internal function is called
rewards[perpetualID] = _earned(perpetualID, hedge);
perpetualRewardPerTokenPaid[perpetualID] = rewardPerTokenStored;
}
// =============================== ERC721 Logic ================================
/// @notice Gets the owner of a perpetual
/// @param perpetualID ID of the concerned perpetual
/// @return owner Owner of the perpetual
function _ownerOf(uint256 perpetualID) internal view returns (address owner) {
owner = _owners[perpetualID];
require(owner != address(0), "2");
}
/// @notice Gets the addresses approved for a perpetual
/// @param perpetualID ID of the concerned perpetual
/// @return Address approved for this perpetual
function _getApproved(uint256 perpetualID) internal view returns (address) {
return _perpetualApprovals[perpetualID];
}
/// @notice Safely transfers `perpetualID` token from `from` to `to`, checking first that contract recipients
/// are aware of the ERC721 protocol to prevent tokens from being forever locked
/// @param perpetualID ID of the concerned perpetual
/// @param _data Additional data, it has no specified format and it is sent in call to `to`
/// @dev 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
/// @dev Requirements:
/// - `from` cannot be the zero address.
/// - `to` cannot be the zero address.
/// - `perpetualID` 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.
function _safeTransfer(
address from,
address to,
uint256 perpetualID,
bytes memory _data
) internal {
_transfer(from, to, perpetualID);
require(_checkOnERC721Received(from, to, perpetualID, _data), "24");
}
/// @notice Returns whether `perpetualID` exists
/// @dev Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}
/// @dev Tokens start existing when they are minted (`_mint`),
/// and stop existing when they are burned (`_burn`)
function _exists(uint256 perpetualID) internal view returns (bool) {
return _owners[perpetualID] != address(0);
}
/// @notice Returns whether `spender` is allowed to manage `perpetualID`
/// @dev `perpetualID` must exist
function _isApprovedOrOwner(address spender, uint256 perpetualID) internal view returns (bool) {
// The following checks if the perpetual exists
address owner = _ownerOf(perpetualID);
return (spender == owner || _getApproved(perpetualID) == spender || _operatorApprovals[owner][spender]);
}
/// @notice Mints `perpetualID` and transfers it to `to`
/// @dev This method is equivalent to the `_safeMint` method used in OpenZeppelin ERC721 contract
/// @dev `perpetualID` must not exist and `to` cannot be the zero address
/// @dev Before calling this function it is checked that the `perpetualID` does not exist as it
/// comes from a counter that has been incremented
/// @dev Emits a {Transfer} event
function _mint(address to, uint256 perpetualID) internal {
_balances[to] += 1;
_owners[perpetualID] = to;
emit Transfer(address(0), to, perpetualID);
require(_checkOnERC721Received(address(0), to, perpetualID, ""), "24");
}
/// @notice Destroys `perpetualID`
/// @dev `perpetualID` must exist
/// @dev Emits a {Transfer} event
function _burn(uint256 perpetualID) internal {
address owner = _ownerOf(perpetualID);
// Clear approvals
_approve(address(0), perpetualID);
_balances[owner] -= 1;
delete _owners[perpetualID];
delete perpetualData[perpetualID];
emit Transfer(owner, address(0), perpetualID);
}
/// @notice Transfers `perpetualID` from `from` to `to` as opposed to {transferFrom},
/// this imposes no restrictions on msg.sender
/// @dev `to` cannot be the zero address and `perpetualID` must be owned by `from`
/// @dev Emits a {Transfer} event
function _transfer(
address from,
address to,
uint256 perpetualID
) internal {
require(_ownerOf(perpetualID) == from, "1");
require(to != address(0), "26");
// Clear approvals from the previous owner
_approve(address(0), perpetualID);
_balances[from] -= 1;
_balances[to] += 1;
_owners[perpetualID] = to;
emit Transfer(from, to, perpetualID);
}
/// @notice Approves `to` to operate on `perpetualID`
function _approve(address to, uint256 perpetualID) internal {
_perpetualApprovals[perpetualID] = to;
emit Approval(_ownerOf(perpetualID), to, perpetualID);
}
/// @notice 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 perpetualID 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 perpetualID,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(msg.sender, from, perpetualID, _data) returns (
bytes4 retval
) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("24");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
}
// File contracts/perpetualManager/PerpetualManager.sol
pragma solidity ^0.8.7;
/// @title PerpetualManager
/// @author Angle Core Team
/// @notice `PerpetualManager` is the contract handling all the Hedging Agents positions and perpetuals
/// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol
/// @dev This file contains the functions of the `PerpetualManager` that can be interacted with
/// by `StableMaster`, by the `PoolManager`, by the `FeeManager` and by governance
contract PerpetualManager is
PerpetualManagerInternal,
IPerpetualManagerFunctions,
IStakingRewardsFunctions,
AccessControlUpgradeable,
PausableUpgradeable
{
using SafeERC20 for IERC20;
/// @notice Role for guardians, governors and `StableMaster`
/// Made for the `StableMaster` to be able to update some parameters
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/// @notice Role for `PoolManager` only
bytes32 public constant POOLMANAGER_ROLE = keccak256("POOLMANAGER_ROLE");
// ============================== Modifiers ====================================
/// @notice Checks if the person interacting with the perpetual with `perpetualID` is approved
/// @param caller Address of the person seeking to interact with the perpetual
/// @param perpetualID ID of the concerned perpetual
/// @dev Generally in `PerpetualManager`, perpetual owners should store the ID of the perpetuals
/// they are able to interact with
modifier onlyApprovedOrOwner(address caller, uint256 perpetualID) {
require(_isApprovedOrOwner(caller, perpetualID), "21");
_;
}
/// @notice Checks if the message sender is the rewards distribution address
modifier onlyRewardsDistribution() {
require(msg.sender == rewardsDistribution, "1");
_;
}
// =============================== Deployer ====================================
/// @notice Notifies the address of the `_feeManager` and of the `oracle`
/// to this contract and grants the correct roles
/// @param governorList List of governor addresses of the protocol
/// @param guardian Address of the guardian of the protocol
/// @param feeManager_ Reference to the `FeeManager` contract which will be able to update fees
/// @param oracle_ Reference to the `oracle` contract which will be able to update fees
/// @dev Called by the `PoolManager` contract when it is activated by the `StableMaster`
/// @dev The `governorList` and `guardian` here are those of the `Core` contract
function deployCollateral(
address[] memory governorList,
address guardian,
IFeeManager feeManager_,
IOracle oracle_
) external override onlyRole(POOLMANAGER_ROLE) {
for (uint256 i = 0; i < governorList.length; i++) {
_grantRole(GUARDIAN_ROLE, governorList[i]);
}
// In the end guardian should be revoked by governance
_grantRole(GUARDIAN_ROLE, guardian);
_grantRole(GUARDIAN_ROLE, address(_stableMaster));
_feeManager = feeManager_;
oracle = oracle_;
}
// ========================== Rewards Distribution =============================
/// @notice Notifies the contract that rewards are going to be shared among HAs of this pool
/// @param reward Amount of governance tokens to be distributed to HAs
/// @dev Only the reward distributor contract is allowed to call this function which starts a staking cycle
/// @dev This function is the equivalent of the `notifyRewardAmount` function found in all staking contracts
function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution {
rewardPerTokenStored = _rewardPerToken();
if (block.timestamp >= periodFinish) {
// If the period is not done, then the reward rate changes
rewardRate = reward / rewardsDuration;
} else {
uint256 remaining = periodFinish - block.timestamp;
uint256 leftover = remaining * rewardRate;
// If the period is not over, we compute the reward left and increase reward duration
rewardRate = (reward + leftover) / rewardsDuration;
}
// Ensuring the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of `rewardRate` in the earned and `rewardsPerToken` functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardToken.balanceOf(address(this));
require(rewardRate <= balance / rewardsDuration, "22");
lastUpdateTime = block.timestamp;
// Change the duration
periodFinish = block.timestamp + rewardsDuration;
emit RewardAdded(reward);
}
/// @notice Supports recovering LP Rewards from other systems such as BAL to be distributed to holders
/// or tokens that were mistakenly
/// @param tokenAddress Address of the token to transfer
/// @param to Address to give tokens to
/// @param tokenAmount Amount of tokens to transfer
function recoverERC20(
address tokenAddress,
address to,
uint256 tokenAmount
) external override onlyRewardsDistribution {
require(tokenAddress != address(rewardToken), "20");
IERC20(tokenAddress).safeTransfer(to, tokenAmount);
emit Recovered(tokenAddress, to, tokenAmount);
}
/// @notice Changes the `rewardsDistribution` associated to this contract
/// @param _rewardsDistribution Address of the new rewards distributor contract
/// @dev This function is part of the staking rewards interface and it is used to propagate
/// a change of rewards distributor notified by the current `rewardsDistribution` address
/// @dev It has already been checked in the `RewardsDistributor` contract calling
/// this function that the `newRewardsDistributor` had a compatible reward token
/// @dev With this function, everything is as if `rewardsDistribution` was admin of its own role
function setNewRewardsDistribution(address _rewardsDistribution) external override onlyRewardsDistribution {
rewardsDistribution = _rewardsDistribution;
emit RewardsDistributionUpdated(_rewardsDistribution);
}
// ================================= Keepers ===================================
/// @notice Updates all the fees not depending on individual HA conditions via keeper utils functions
/// @param feeDeposit New deposit global fees
/// @param feeWithdraw New withdraw global fees
/// @dev Governance may decide to incorporate a collateral ratio dependence in the fees for HAs,
/// in this case it will be done through the `FeeManager` contract
/// @dev This dependence can either be a bonus or a malus
function setFeeKeeper(uint64 feeDeposit, uint64 feeWithdraw) external override {
require(msg.sender == address(_feeManager), "1");
haBonusMalusDeposit = feeDeposit;
haBonusMalusWithdraw = feeWithdraw;
}
// ======== Governance - Guardian Functions - Staking and Pauses ===============
/// @notice Pauses the `getReward` method as well as the functions allowing to open, modify or close perpetuals
/// @dev After calling this function, it is going to be impossible for HAs to interact with their perpetuals
/// or claim their rewards on it
function pause() external override onlyRole(GUARDIAN_ROLE) {
_pause();
}
/// @notice Unpauses HAs functions
function unpause() external override onlyRole(GUARDIAN_ROLE) {
_unpause();
}
/// @notice Sets the conditions and specifies the duration of the reward distribution
/// @param _rewardsDuration Duration for the rewards for this contract
/// @param _rewardsDistribution Address which will give the reward tokens
/// @dev It allows governance to directly change the rewards distribution contract and the conditions
/// at which this distribution is done
/// @dev The compatibility of the reward token is not checked here: it is checked
/// in the rewards distribution contract when activating this as a staking contract,
/// so if a reward distributor is set here but does not have a compatible reward token, then this reward
/// distributor will not be able to set this contract as a staking contract
function setRewardDistribution(uint256 _rewardsDuration, address _rewardsDistribution)
external
onlyRole(GUARDIAN_ROLE)
zeroCheck(_rewardsDistribution)
{
rewardsDuration = _rewardsDuration;
rewardsDistribution = _rewardsDistribution;
emit RewardsDistributionDurationUpdated(rewardsDuration, rewardsDistribution);
}
// ============ Governance - Guardian Functions - Parameters ===================
/// @notice Sets `baseURI` that is the URI to access ERC721 metadata
/// @param _baseURI New `baseURI` parameter
function setBaseURI(string memory _baseURI) external onlyRole(GUARDIAN_ROLE) {
baseURI = _baseURI;
emit BaseURIUpdated(_baseURI);
}
/// @notice Sets `lockTime` that is the minimum amount of time HAs have to stay within the protocol
/// @param _lockTime New `lockTime` parameter
/// @dev This parameter is used to prevent HAs from exiting before a certain amount of time and taking advantage
/// of insiders' information they may have due to oracle latency
function setLockTime(uint64 _lockTime) external override onlyRole(GUARDIAN_ROLE) {
lockTime = _lockTime;
emit LockTimeUpdated(_lockTime);
}
/// @notice Changes the maximum leverage authorized (commit/margin) and the maintenance margin under which
/// perpetuals can be liquidated
/// @param _maxLeverage New value of the maximum leverage allowed
/// @param _maintenanceMargin The new maintenance margin
/// @dev For a perpetual, the leverage is defined as the ratio between the committed amount and the margin
/// @dev For a perpetual, the maintenance margin is defined as the ratio between the margin ratio / the committed amount
function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin)
external
override
onlyRole(GUARDIAN_ROLE)
onlyCompatibleFees(_maintenanceMargin)
{
// Checking the compatibility of the parameters
require(BASE_PARAMS**2 > _maxLeverage * _maintenanceMargin, "8");
maxLeverage = _maxLeverage;
maintenanceMargin = _maintenanceMargin;
emit BoundsPerpetualUpdated(_maxLeverage, _maintenanceMargin);
}
/// @notice Sets `xHAFees` that is the thresholds of values of the ratio between what's covered (hedged)
/// divided by what's to hedge with HAs at which fees will change as well as
/// `yHAFees` that is the value of the deposit or withdraw fees at threshold
/// @param _xHAFees Array of the x-axis value for the fees (deposit or withdraw)
/// @param _yHAFees Array of the y-axis value for the fees (deposit or withdraw)
/// @param deposit Whether deposit or withdraw fees should be updated
/// @dev Evolution of the fees is linear between two values of thresholds
/// @dev These x values should be ranked in ascending order
/// @dev For deposit fees, the higher the x that is the ratio between what's to hedge and what's hedged
/// the higher y should be (the more expensive it should be for HAs to come in)
/// @dev For withdraw fees, evolution should follow an opposite logic
function setHAFees(
uint64[] memory _xHAFees,
uint64[] memory _yHAFees,
uint8 deposit
) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleInputArrays(_xHAFees, _yHAFees) {
if (deposit == 1) {
xHAFeesDeposit = _xHAFees;
yHAFeesDeposit = _yHAFees;
} else {
xHAFeesWithdraw = _xHAFees;
yHAFeesWithdraw = _yHAFees;
}
emit HAFeesUpdated(_xHAFees, _yHAFees, deposit);
}
/// @notice Sets the target and limit proportions of collateral from users that can be insured by HAs
/// @param _targetHAHedge Proportion of collateral from users that HAs should hedge
/// @param _limitHAHedge Proportion of collateral from users above which HAs can see their perpetuals
/// cashed out
/// @dev `targetHAHedge` equal to `BASE_PARAMS` means that all the collateral from users should be insured by HAs
/// @dev `targetHAHedge` equal to 0 means HA should not cover (hedge) anything
function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge)
external
override
onlyRole(GUARDIAN_ROLE)
onlyCompatibleFees(_targetHAHedge)
onlyCompatibleFees(_limitHAHedge)
{
require(_targetHAHedge <= _limitHAHedge, "8");
limitHAHedge = _limitHAHedge;
targetHAHedge = _targetHAHedge;
// Updating the value in the `stableMaster` contract
_stableMaster.setTargetHAHedge(_targetHAHedge);
emit TargetAndLimitHAHedgeUpdated(_targetHAHedge, _limitHAHedge);
}
/// @notice Sets the portion of the leftover cash out amount of liquidated perpetuals that go to keepers
/// @param _keeperFeesLiquidationRatio Proportion to keepers
/// @dev This proportion should be inferior to `BASE_PARAMS`
function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio)
external
override
onlyRole(GUARDIAN_ROLE)
onlyCompatibleFees(_keeperFeesLiquidationRatio)
{
keeperFeesLiquidationRatio = _keeperFeesLiquidationRatio;
emit KeeperFeesLiquidationRatioUpdated(keeperFeesLiquidationRatio);
}
/// @notice Sets the maximum amounts going to the keepers when closing perpetuals
/// because too much was hedged by HAs or when liquidating a perpetual
/// @param _keeperFeesLiquidationCap Maximum reward going to the keeper liquidating a perpetual
/// @param _keeperFeesClosingCap Maximum reward going to the keeper forcing the closing of an ensemble
/// of perpetuals
function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap)
external
override
onlyRole(GUARDIAN_ROLE)
{
keeperFeesLiquidationCap = _keeperFeesLiquidationCap;
keeperFeesClosingCap = _keeperFeesClosingCap;
emit KeeperFeesCapUpdated(keeperFeesLiquidationCap, keeperFeesClosingCap);
}
/// @notice Sets the x-array (ie thresholds) for `FeeManager` when closing perpetuals and the y-array that is the
/// value of the proportions of the fees going to keepers closing perpetuals
/// @param _xKeeperFeesClosing Thresholds for closing fees
/// @param _yKeeperFeesClosing Value of the fees at the different threshold values specified in `xKeeperFeesClosing`
/// @dev The x thresholds correspond to values of the hedge ratio divided by two
/// @dev `xKeeperFeesClosing` and `yKeeperFeesClosing` should have the same length
function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing)
external
override
onlyRole(GUARDIAN_ROLE)
onlyCompatibleInputArrays(_xKeeperFeesClosing, _yKeeperFeesClosing)
{
xKeeperFeesClosing = _xKeeperFeesClosing;
yKeeperFeesClosing = _yKeeperFeesClosing;
emit KeeperFeesClosingUpdated(xKeeperFeesClosing, yKeeperFeesClosing);
}
// ================ Governance - `PoolManager` Functions =======================
/// @notice Changes the reference to the `FeeManager` contract
/// @param feeManager_ New `FeeManager` contract
/// @dev This allows the `PoolManager` contract to propagate changes to the `PerpetualManager`
/// @dev This is the only place where the `_feeManager` can be changed, it is as if there was
/// a `FEEMANAGER_ROLE` for which `PoolManager` was the admin
function setFeeManager(IFeeManager feeManager_) external override onlyRole(POOLMANAGER_ROLE) {
_feeManager = feeManager_;
}
// ======================= `StableMaster` Function =============================
/// @notice Changes the oracle contract used to compute collateral price with respect to the stablecoin's price
/// @param oracle_ Oracle contract
/// @dev The collateral `PoolManager` does not store a reference to an oracle, the value of the oracle
/// is hence directly set by the `StableMaster`
function setOracle(IOracle oracle_) external override {
require(msg.sender == address(_stableMaster), "1");
oracle = oracle_;
}
}
// File contracts/perpetualManager/PerpetualManagerFront.sol
pragma solidity ^0.8.7;
/// @title PerpetualManagerFront
/// @author Angle Core Team
/// @notice `PerpetualManager` is the contract handling all the Hedging Agents perpetuals
/// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol
/// @dev This file contains the functions of the `PerpetualManager` that can be directly interacted
/// with by external agents. These functions are the ones that need to be called to open, modify or close
/// perpetuals
/// @dev `PerpetualManager` naturally handles staking, the code allowing HAs to stake has been inspired from
/// https://github.com/SetProtocol/index-coop-contracts/blob/master/contracts/staking/StakingRewardsV2.sol
/// @dev Perpetuals at Angle protocol are treated as NFTs, this contract handles the logic for that
contract PerpetualManagerFront is PerpetualManager, IPerpetualManagerFront {
using SafeERC20 for IERC20;
using CountersUpgradeable for CountersUpgradeable.Counter;
// =============================== Deployer ====================================
/// @notice Initializes the `PerpetualManager` contract
/// @param poolManager_ Reference to the `PoolManager` contract handling the collateral associated to the `PerpetualManager`
/// @param rewardToken_ Reference to the `rewardtoken` that can be distributed to HAs as they have open positions
/// @dev The reward token is most likely going to be the ANGLE token
/// @dev Since this contract is upgradeable, this function is an `initialize` and not a `constructor`
/// @dev Zero checks are only performed on addresses for which no external calls are made, in this case just
/// the `rewardToken_` is checked
/// @dev After initializing this contract, all the fee parameters should be initialized by governance using
/// the setters in this contract
function initialize(IPoolManager poolManager_, IERC20 rewardToken_)
external
initializer
zeroCheck(address(rewardToken_))
{
// Initializing contracts
__Pausable_init();
__AccessControl_init();
// Creating references
poolManager = poolManager_;
_token = IERC20(poolManager_.token());
_stableMaster = IStableMaster(poolManager_.stableMaster());
rewardToken = rewardToken_;
_collatBase = 10**(IERC20Metadata(address(_token)).decimals());
// The references to the `feeManager` and to the `oracle` contracts are to be set when the contract is deployed
// Setting up Access Control for this contract
// There is no need to store the reference to the `PoolManager` address here
// Once the `POOLMANAGER_ROLE` has been granted, no new addresses can be granted or revoked
// from this role: a `PerpetualManager` contract can only have one `PoolManager` associated
_setupRole(POOLMANAGER_ROLE, address(poolManager));
// `PoolManager` is admin of all the roles. Most of the time, changes are propagated from it
_setRoleAdmin(GUARDIAN_ROLE, POOLMANAGER_ROLE);
_setRoleAdmin(POOLMANAGER_ROLE, POOLMANAGER_ROLE);
// Pausing the contract because it is not functional till the collateral has really been deployed by the
// `StableMaster`
_pause();
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
// ================================= HAs =======================================
/// @notice Lets a HA join the protocol and create a perpetual
/// @param owner Address of the future owner of the perpetual
/// @param margin Amount of collateral brought by the HA
/// @param committedAmount Amount of collateral covered by the HA
/// @param maxOracleRate Maximum oracle value that the HA wants to see stored in the perpetual
/// @param minNetMargin Minimum net margin that the HA is willing to see stored in the perpetual
/// @return perpetualID The ID of the perpetual opened by this HA
/// @dev The future owner of the perpetual cannot be the zero address
/// @dev It is possible to open a perpetual on behalf of someone else
/// @dev The `maxOracleRate` parameter serves as a protection against oracle manipulations for HAs opening perpetuals
/// @dev `minNetMargin` is a protection against too big variations in the fees for HAs
function openPerpetual(
address owner,
uint256 margin,
uint256 committedAmount,
uint256 maxOracleRate,
uint256 minNetMargin
) external override whenNotPaused zeroCheck(owner) returns (uint256 perpetualID) {
// Transaction will revert anyway if `margin` is zero
require(committedAmount > 0, "27");
// There could be a reentrancy attack as a call to an external contract is done before state variables
// updates. Yet in this case, the call involves a transfer from the `msg.sender` to the contract which
// eliminates the risk
_token.safeTransferFrom(msg.sender, address(poolManager), margin);
// Computing the oracle value
// Only the highest oracle value (between Chainlink and Uniswap) we get is stored in the perpetual
(, uint256 rateUp) = _getOraclePrice();
// Checking if the oracle rate is not too big: a too big oracle rate could mean for a HA that the price
// has become too high to make it interesting to open a perpetual
require(rateUp <= maxOracleRate, "28");
// Computing the total amount of stablecoins that this perpetual is going to hedge for the protocol
uint256 totalHedgeAmountUpdate = (committedAmount * rateUp) / _collatBase;
// Computing the net amount brought by the HAs to store in the perpetual
uint256 netMargin = _getNetMargin(margin, totalHedgeAmountUpdate, committedAmount);
require(netMargin >= minNetMargin, "29");
// Checking if the perpetual is not too leveraged, even after computing the fees
require((committedAmount * BASE_PARAMS) <= maxLeverage * netMargin, "30");
// ERC721 logic
_perpetualIDcount.increment();
perpetualID = _perpetualIDcount.current();
// In the logic of the staking contract, the `_updateReward` should be called
// before the perpetual is opened
_updateReward(perpetualID, 0);
// Updating the total amount of stablecoins hedged by HAs and creating the perpetual
totalHedgeAmount += totalHedgeAmountUpdate;
perpetualData[perpetualID] = Perpetual(rateUp, block.timestamp, netMargin, committedAmount);
// Following ERC721 logic, the function `_mint(...)` calls `_checkOnERC721Received` and could then be used as
// a reentrancy vector. Minting should then only be done at the very end after updating all variables.
_mint(owner, perpetualID);
emit PerpetualOpened(perpetualID, rateUp, netMargin, committedAmount);
}
/// @notice Lets a HA close a perpetual owned or controlled for the stablecoin/collateral pair associated
/// to this `PerpetualManager` contract
/// @param perpetualID ID of the perpetual to close
/// @param to Address which will receive the proceeds from this perpetual
/// @param minCashOutAmount Minimum net cash out amount that the HA is willing to get for closing the
/// perpetual
/// @dev The HA gets the current amount of her position depending on the entry oracle value
/// and current oracle value minus some transaction fees computed on the committed amount
/// @dev `msg.sender` should be the owner of `perpetualID` or be approved for this perpetual
/// @dev If the `PoolManager` does not have enough collateral, the perpetual owner will be converted to a SLP and
/// receive sanTokens
/// @dev The `minCashOutAmount` serves as a protection for HAs closing their perpetuals: it protects them both
/// from fees that would have become too high and from a too big decrease in oracle value
function closePerpetual(
uint256 perpetualID,
address to,
uint256 minCashOutAmount
) external override whenNotPaused onlyApprovedOrOwner(msg.sender, perpetualID) {
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
(uint256 rateDown, ) = _getOraclePrice();
// The lowest oracle price between Chainlink and Uniswap is used to compute the perpetual's position at
// the time of closing: it is the one that is most at the advantage of the protocol
(uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 0) {
// You need to wait `lockTime` before being able to withdraw funds from the protocol as a HA
require(perpetual.entryTimestamp + lockTime <= block.timestamp, "31");
// Cashing out the perpetual internally
_closePerpetual(perpetualID, perpetual);
// Computing exit fees: they depend on how much is already hedgeded by HAs compared with what's to hedge
(uint256 netCashOutAmount, ) = _getNetCashOutAmount(
cashOutAmount,
perpetual.committedAmount,
// The perpetual has already been cashed out when calling this function, so there is no
// `committedAmount` to add to the `totalHedgeAmount` to get the `currentHedgeAmount`
_computeHedgeRatio(totalHedgeAmount)
);
require(netCashOutAmount >= minCashOutAmount, "32");
emit PerpetualClosed(perpetualID, netCashOutAmount);
_secureTransfer(to, netCashOutAmount);
}
}
/// @notice Lets a HA increase the `margin` in a perpetual she controls for this
/// stablecoin/collateral pair
/// @param perpetualID ID of the perpetual to which amount should be added to `margin`
/// @param amount Amount to add to the perpetual's `margin`
/// @dev This decreases the leverage multiple of this perpetual
/// @dev If this perpetual is to be liquidated, the HA is not going to be able to add liquidity to it
/// @dev Since this function can be used to add liquidity to a perpetual, there is no need to restrict
/// it to the owner of the perpetual
/// @dev Calling this function on a non-existing perpetual makes it revert
function addToPerpetual(uint256 perpetualID, uint256 amount) external override whenNotPaused {
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
(uint256 rateDown, ) = _getOraclePrice();
(, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 0) {
// Overflow check
_token.safeTransferFrom(msg.sender, address(poolManager), amount);
perpetualData[perpetualID].margin += amount;
emit PerpetualUpdated(perpetualID, perpetual.margin + amount);
}
}
/// @notice Lets a HA decrease the `margin` in a perpetual she controls for this
/// stablecoin/collateral pair
/// @param perpetualID ID of the perpetual from which collateral should be removed
/// @param amount Amount to remove from the perpetual's `margin`
/// @param to Address which will receive the collateral removed from this perpetual
/// @dev This increases the leverage multiple of this perpetual
/// @dev `msg.sender` should be the owner of `perpetualID` or be approved for this perpetual
function removeFromPerpetual(
uint256 perpetualID,
uint256 amount,
address to
) external override whenNotPaused onlyApprovedOrOwner(msg.sender, perpetualID) {
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
(uint256 rateDown, ) = _getOraclePrice();
(uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 0) {
// Checking if money can be withdrawn from the perpetual
require(
// The perpetual should not have been opened too soon
(perpetual.entryTimestamp + lockTime <= block.timestamp) &&
// The amount to withdraw should not be more important than the perpetual's `cashOutAmount` and `margin`
(amount < cashOutAmount) &&
(amount < perpetual.margin) &&
// Withdrawing collateral should not make the leverage of the perpetual too important
// Checking both on `cashOutAmount` and `perpetual.margin` (as we can have either
// `cashOutAmount >= perpetual.margin` or `cashOutAmount<perpetual.margin`)
// No checks are done on `maintenanceMargin`, as conditions on `maxLeverage` are more restrictive
perpetual.committedAmount * BASE_PARAMS <= (cashOutAmount - amount) * maxLeverage &&
perpetual.committedAmount * BASE_PARAMS <= (perpetual.margin - amount) * maxLeverage,
"33"
);
perpetualData[perpetualID].margin -= amount;
emit PerpetualUpdated(perpetualID, perpetual.margin - amount);
_secureTransfer(to, amount);
}
}
/// @notice Allows an outside caller to liquidate perpetuals if their margin ratio is
/// under the maintenance margin
/// @param perpetualIDs ID of the targeted perpetuals
/// @dev Liquidation of a perpetual will succeed if the `cashOutAmount` of the perpetual is under the maintenance margin,
/// and nothing will happen if the perpetual is still healthy
/// @dev The outside caller (namely a keeper) gets a portion of the leftover cash out amount of the perpetual
/// @dev As keepers may directly profit from this function, there may be front-running problems with miners bots,
/// we may have to put an access control logic for this function to only allow white-listed addresses to act
/// as keepers for the protocol
function liquidatePerpetuals(uint256[] memory perpetualIDs) external override whenNotPaused {
// Getting the oracle price
(uint256 rateDown, ) = _getOraclePrice();
uint256 liquidationFees;
for (uint256 i = 0; i < perpetualIDs.length; i++) {
uint256 perpetualID = perpetualIDs[i];
if (_exists(perpetualID)) {
// Loading perpetual data
Perpetual memory perpetual = perpetualData[perpetualID];
(uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 1) {
// Computing the incentive for the keeper as a function of the `cashOutAmount` of the perpetual
// This incentivizes keepers to react fast when the price starts to go below the liquidation
// margin
liquidationFees += _computeKeeperLiquidationFees(cashOutAmount);
}
}
}
emit KeeperTransferred(msg.sender, liquidationFees);
_secureTransfer(msg.sender, liquidationFees);
}
/// @notice Allows an outside caller to close perpetuals if too much of the collateral from
/// users is hedged by HAs
/// @param perpetualIDs IDs of the targeted perpetuals
/// @dev This function allows to make sure that the protocol will not have too much HAs for a long period of time
/// @dev A HA that owns a targeted perpetual will get the current value of her perpetual
/// @dev The call to the function above will revert if HAs cannot be cashed out
/// @dev As keepers may directly profit from this function, there may be front-running problems with miners bots,
/// we may have to put an access control logic for this function to only allow white-listed addresses to act
/// as keepers for the protocol
function forceClosePerpetuals(uint256[] memory perpetualIDs) external override whenNotPaused {
// Getting the oracle prices
// `rateUp` is used to compute the cost of manipulation of the covered amounts
(uint256 rateDown, uint256 rateUp) = _getOraclePrice();
// Fetching `stocksUsers` to check if perpetuals cover too much collateral
uint256 stocksUsers = _stableMaster.getStocksUsers();
uint256 targetHedgeAmount = (stocksUsers * targetHAHedge) / BASE_PARAMS;
// `totalHedgeAmount` should be greater than the limit hedge amount
require(totalHedgeAmount > (stocksUsers * limitHAHedge) / BASE_PARAMS, "34");
uint256 liquidationFees;
uint256 cashOutFees;
// Array of pairs `(owner, netCashOutAmount)`
Pairs[] memory outputPairs = new Pairs[](perpetualIDs.length);
for (uint256 i = 0; i < perpetualIDs.length; i++) {
uint256 perpetualID = perpetualIDs[i];
address owner = _owners[perpetualID];
if (owner != address(0)) {
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
// First checking if the perpetual should not be liquidated
(uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 1) {
// This results in the perpetual being liquidated and the keeper being paid the same amount of fees as
// what would have been paid if the perpetual had been liquidated using the `liquidatePerpetualFunction`
// Computing the incentive for the keeper as a function of the `cashOutAmount` of the perpetual
// This incentivizes keepers to react fast
liquidationFees += _computeKeeperLiquidationFees(cashOutAmount);
} else if (perpetual.entryTimestamp + lockTime <= block.timestamp) {
// It is impossible to force the closing a perpetual that was just created: in the other case, this
// function could be used to do some insider trading and to bypass the `lockTime` limit
// If too much collateral is hedged by HAs, then the perpetual can be cashed out
_closePerpetual(perpetualID, perpetual);
uint64 ratioPostCashOut;
// In this situation, `totalHedgeAmount` is the `currentHedgeAmount`
if (targetHedgeAmount > totalHedgeAmount) {
ratioPostCashOut = uint64((totalHedgeAmount * BASE_PARAMS) / targetHedgeAmount);
} else {
ratioPostCashOut = uint64(BASE_PARAMS);
}
// Computing how much the HA will get and the amount of fees paid at closing
(uint256 netCashOutAmount, uint256 fees) = _getNetCashOutAmount(
cashOutAmount,
perpetual.committedAmount,
ratioPostCashOut
);
cashOutFees += fees;
// Storing the owners of perpetuals that were forced cash out in a memory array to avoid
// reentrancy attacks
outputPairs[i] = Pairs(owner, netCashOutAmount);
}
// Checking if at this point enough perpetuals have been cashed out
if (totalHedgeAmount <= targetHedgeAmount) break;
}
}
uint64 ratio = (targetHedgeAmount == 0)
? 0
: uint64((totalHedgeAmount * BASE_PARAMS) / (2 * targetHedgeAmount));
// Computing the rewards given to the keeper calling this function
// and transferring the rewards to the keeper
// Using a cache value of `cashOutFees` to save some gas
// The value below is the amount of fees that should go to the keeper forcing the closing of perpetuals
// In the linear by part function, if `xKeeperFeesClosing` is greater than 0.5 (meaning we are not at target yet)
// then keepers should get almost no fees
cashOutFees = (cashOutFees * _piecewiseLinear(ratio, xKeeperFeesClosing, yKeeperFeesClosing)) / BASE_PARAMS;
// The amount of fees that can go to keepers is capped by a parameter set by governance
cashOutFees = cashOutFees < keeperFeesClosingCap ? cashOutFees : keeperFeesClosingCap;
// A malicious attacker could take advantage of this function to take a flash loan, burn agTokens
// to diminish the stocks users and then force close some perpetuals. We also need to check that assuming
// really small burn transaction fees (of 0.05%), an attacker could make a profit with such flash loan
// if current hedge is below the target hedge by making such flash loan.
// The formula for the cost of such flash loan is:
// `fees * (limitHAHedge - targetHAHedge) * stocksUsers / oracle`
// In order to avoid doing multiplications after divisions, and to get everything in the correct base, we do:
uint256 estimatedCost = (5 * (limitHAHedge - targetHAHedge) * stocksUsers * _collatBase) /
(rateUp * 10000 * BASE_PARAMS);
cashOutFees = cashOutFees < estimatedCost ? cashOutFees : estimatedCost;
emit PerpetualsForceClosed(perpetualIDs, outputPairs, msg.sender, cashOutFees + liquidationFees);
// Processing transfers after all calculations have been performed
for (uint256 j = 0; j < perpetualIDs.length; j++) {
if (outputPairs[j].netCashOutAmount > 0) {
_secureTransfer(outputPairs[j].owner, outputPairs[j].netCashOutAmount);
}
}
_secureTransfer(msg.sender, cashOutFees + liquidationFees);
}
// =========================== External View Function ==========================
/// @notice Returns the `cashOutAmount` of the perpetual owned by someone at a given oracle value
/// @param perpetualID ID of the perpetual
/// @param rate Oracle value
/// @return The `cashOutAmount` of the perpetual
/// @return Whether the position of the perpetual is now too small compared with its initial position and should hence
/// be liquidated
/// @dev This function is used by the Collateral Settlement contract
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view override returns (uint256, uint256) {
Perpetual memory perpetual = perpetualData[perpetualID];
return _getCashOutAmount(perpetual, rate);
}
// =========================== Reward Distribution =============================
/// @notice Allows to check the amount of reward tokens earned by a perpetual
/// @param perpetualID ID of the perpetual to check
function earned(uint256 perpetualID) external view returns (uint256) {
return _earned(perpetualID, perpetualData[perpetualID].committedAmount * perpetualData[perpetualID].entryRate);
}
/// @notice Allows a perpetual owner to withdraw rewards
/// @param perpetualID ID of the perpetual which accumulated tokens
/// @dev Only an approved caller can claim the rewards for the perpetual with perpetualID
function getReward(uint256 perpetualID) external whenNotPaused onlyApprovedOrOwner(msg.sender, perpetualID) {
_getReward(perpetualID, perpetualData[perpetualID].committedAmount * perpetualData[perpetualID].entryRate);
}
// =============================== ERC721 logic ================================
/// @notice Gets the name of the NFT collection implemented by this contract
function name() external pure override returns (string memory) {
return "AnglePerp";
}
/// @notice Gets the symbol of the NFT collection implemented by this contract
function symbol() external pure override returns (string memory) {
return "AnglePerp";
}
/// @notice Gets the URI containing metadata
/// @param perpetualID ID of the perpetual
function tokenURI(uint256 perpetualID) external view override returns (string memory) {
require(_exists(perpetualID), "2");
// There is no perpetual with `perpetualID` equal to 0, so the following variable is
// always greater than zero
uint256 temp = perpetualID;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (perpetualID != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(perpetualID % 10)));
perpetualID /= 10;
}
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, string(buffer))) : "";
}
/// @notice Gets the balance of an owner
/// @param owner Address of the owner
/// @dev Balance here represents the number of perpetuals owned by a HA
function balanceOf(address owner) external view override returns (uint256) {
require(owner != address(0), "0");
return _balances[owner];
}
/// @notice Gets the owner of the perpetual with ID perpetualID
/// @param perpetualID ID of the perpetual
function ownerOf(uint256 perpetualID) external view override returns (address) {
return _ownerOf(perpetualID);
}
/// @notice Approves to an address specified by `to` a perpetual specified by `perpetualID`
/// @param to Address to approve the perpetual to
/// @param perpetualID ID of the perpetual
/// @dev The approved address will have the right to transfer the perpetual, to cash it out
/// on behalf of the owner, to add or remove collateral in it and to choose the destination
/// address that will be able to receive the proceeds of the perpetual
function approve(address to, uint256 perpetualID) external override {
address owner = _ownerOf(perpetualID);
require(to != owner, "35");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "21");
_approve(to, perpetualID);
}
/// @notice Gets the approved address by a perpetual owner
/// @param perpetualID ID of the concerned perpetual
function getApproved(uint256 perpetualID) external view override returns (address) {
require(_exists(perpetualID), "2");
return _getApproved(perpetualID);
}
/// @notice Sets approval on all perpetuals owned by the owner to an operator
/// @param operator Address to approve (or block) on all perpetuals
/// @param approved Whether the sender wants to approve or block the operator
function setApprovalForAll(address operator, bool approved) external override {
require(operator != msg.sender, "36");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/// @notice Gets if the operator address is approved on all perpetuals by the owner
/// @param owner Owner of perpetuals
/// @param operator Address to check if approved
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/// @notice Gets if the sender address is approved for the perpetualId
/// @param perpetualID ID of the perpetual
function isApprovedOrOwner(address spender, uint256 perpetualID) external view override returns (bool) {
return _isApprovedOrOwner(spender, perpetualID);
}
/// @notice Transfers the `perpetualID` from an address to another
/// @param from Source address
/// @param to Destination a address
/// @param perpetualID ID of the perpetual to transfer
function transferFrom(
address from,
address to,
uint256 perpetualID
) external override onlyApprovedOrOwner(msg.sender, perpetualID) {
_transfer(from, to, perpetualID);
}
/// @notice Safely transfers the `perpetualID` from an address to another without data in it
/// @param from Source address
/// @param to Destination a address
/// @param perpetualID ID of the perpetual to transfer
function safeTransferFrom(
address from,
address to,
uint256 perpetualID
) external override {
safeTransferFrom(from, to, perpetualID, "");
}
/// @notice Safely transfers the `perpetualID` from an address to another with data in the transfer
/// @param from Source address
/// @param to Destination a address
/// @param perpetualID ID of the perpetual to transfer
function safeTransferFrom(
address from,
address to,
uint256 perpetualID,
bytes memory _data
) public override onlyApprovedOrOwner(msg.sender, perpetualID) {
_safeTransfer(from, to, perpetualID, _data);
}
// =============================== ERC165 logic ================================
/// @notice Queries 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.
/// Required by the ERC721 standard, so used to check that the IERC721 is implemented.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceId) external pure override(IERC165) returns (bool) {
return
interfaceId == type(IPerpetualManagerFront).interfaceId ||
interfaceId == type(IPerpetualManagerFunctions).interfaceId ||
interfaceId == type(IStakingRewards).interfaceId ||
interfaceId == type(IStakingRewardsFunctions).interfaceId ||
interfaceId == type(IAccessControl).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
} | Gets the URI containing metadata perpetualID ID of the perpetual There is no perpetual with `perpetualID` equal to 0, so the following variable is always greater than zero | function tokenURI(uint256 perpetualID) external view override returns (string memory) {
require(_exists(perpetualID), "2");
uint256 temp = perpetualID;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (perpetualID != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(perpetualID % 10)));
perpetualID /= 10;
}
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, string(buffer))) : "";
}
| 7,761,019 |
./full_match/42/0x2f7575eE23D8931Ab90a6D773b110Ddb95417a03/sources/contracts/interfaces/IProtocol.sol | Protocol contract interface. See {Protocol}. crypto-pumpkin@github/ | interface IProtocol {
function owner() external view returns (address);
function active() external view returns (bool);
function name() external view returns (bytes32);
function claimNonce() external view returns (uint256);
function claimRedeemDelay() external view returns (uint256);
function noclaimRedeemDelay() external view returns (uint256);
function activeCovers(uint256 _index) external view returns (address);
function claimDetails(uint256 _claimNonce) external view returns (uint16 _payoutNumerator, uint16 _payoutDenominator, uint48 _incidentTimestamp, uint48 _timestamp);
function collateralStatusMap(address _collateral) external view returns (uint8 _status);
function expirationTimestampMap(uint48 _expirationTimestamp) external view returns (bytes32 _name, uint8 _status);
function coverMap(address _collateral, uint48 _expirationTimestamp) external view returns (address);
function collaterals(uint256 _index) external view returns (address);
function collateralsLength() external view returns (uint256);
function expirationTimestamps(uint256 _index) external view returns (uint48);
function expirationTimestampsLength() external view returns (uint256);
function activeCoversLength() external view returns (uint256);
function claimsLength() external view returns (uint256);
function addCover(address _collateral, uint48 _timestamp, uint256 _amount)
external returns (bool);
} | 16,236,075 |
./partial_match/3/0x93aE15BC2454C138e79F3F9EB26F9743c0c25C77/sources/pool.sol | update of options, triggered by anyone periodically/ update call options prevent divide by 0; try best to update the price; settle all options current block time difference price alignment we try to get the most recent price after expiry date use the history price to settle option use current price; remove deleted options set with the last one and pop out the last | function update() external {
uint etherPrice = _getEtherPrice();
require(etherPrice > 0, "invalid etherPrice");
if (!_hasPrice() && block.timestamp >= _earliestExpiryDate) {
_recordPrice(etherPrice);
}
for (uint i = 0;i< _options.length;i++) {
uint diff = block.timestamp - _options[i].expiryDate();
(uint hisDiff, uint hisPrice, bool valid) = _getApproxPrice(_options[i].expiryDate());
if (valid && hisDiff < diff) {
_settleOption(_options[i], hisPrice);
_settleOption(_options[i], etherPrice);
}
}
if (_options[i].deleted()) {
uint last = _options.length - 1;
_options[i] = _options[last];
_options.pop();
}
}
| 5,151,205 |
pragma solidity ^0.4.22;
import "./openzeppelin/contracts/lifecycle/Pausable.sol";
import "./EtherDollar.sol";
import "./EtherBank.sol";
contract Liquidator is Pausable {
using SafeMath for uint256;
EtherDollar public token;
EtherBank public bank;
address public owner;
address public etherBankAddr;
uint256 public lastLiquidationId;
enum LiquidationState {
ACTIVE,
FINISHED,
FAILED
}
struct Liquidation {
uint256 loanId;
uint256 collateralAmount;
uint256 loanAmount;
uint256 startBlock;
uint256 endBlock;
uint256 bestBid;
address bestBidder;
LiquidationState state;
}
mapping(uint256 => Liquidation) private liquidations;
mapping(address => uint256) private deposits;
event LogStartLiquidation(uint256 liquidationId, uint256 collateralAmount, uint256 loanAmount, uint256 startBlock, uint256 endBlock);
event LogStopLiquidation(uint256 liquidationId, uint256 bestBid, address bestBidder);
event LogWithdraw(address withdrawalAccount, uint256 amount);
string private constant INVALID_ADDRESS = "INVALID_ADDRESS";
string private constant ONLY_ETHER_BANK = "ONLY_ETHER_BANK";
string private constant INVALID_AMOUNT = "INVALID_AMOUNT";
string private constant NOT_ACTIVE_LOAN = "NOT_ACTIVE_LOAN";
string private constant OPEN_LIQUIDATION = "OPEN_LIQUIDATION";
string private constant NO_BID = "NO_BID";
string private constant INADEQUATE_BIDDING = "INADEQUATE_BIDDING";
string private constant INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS";
constructor(address _tokenAddr, address _etherBankAddr)
public {
owner = msg.sender;
// etherBankAddr = 0x0;
lastLiquidationId = 0;
etherBankAddr = _etherBankAddr;
bank = EtherBank(etherBankAddr);
token = EtherDollar(_tokenAddr);
}
/**
* @dev Set EtherBank smart contract address.
* @param _etherBankAddr The EtherBank smart contract address.
*/
function setEtherBank(address _etherBankAddr)
external
onlyOwner
whenNotPaused
{
require(_etherBankAddr != address(0), INVALID_ADDRESS);
etherBankAddr = _etherBankAddr;
bank = EtherBank(etherBankAddr);
}
/**
* @dev Set EtherDollar smart contract address.
* @param _tokenAddr The EtherDollar smart contract address.
*/
function setEtherDollar(address _tokenAddr)
external
onlyOwner
whenNotPaused
{
require(_tokenAddr != address(0), INVALID_ADDRESS);
token = EtherDollar(_tokenAddr);
}
/**
* @dev Get amount of the deposit.
*/
function getDepositAmount()
public
view
whenNotPaused
returns(uint256)
{
return deposits[msg.sender];
}
/**
* @dev Withdraw EtherDollar.
* @param amount The deposite amount.
*/
function withdraw(uint256 amount)
public
whenNotPaused
throwIfEqualToZero(amount)
{
require(amount <= deposits[msg.sender], INVALID_AMOUNT);
deposits[msg.sender] -= amount;
token.transfer(msg.sender, amount);
emit LogWithdraw(msg.sender, amount);
}
/**
* @dev Start an liquidation.
* @param _numberOfBlocks The number of blocks which liquidation should take.
* @param _loanId The id of the loan which is under liquidation.
* @param _collateralAmount The amount of the loan's collateral.
* @param _loanAmount The amount of the loan's etherDollar.
*/
function startLiquidation(
uint256 _numberOfBlocks,
uint256 _loanId,
uint256 _collateralAmount,
uint256 _loanAmount
)
public
whenNotPaused
onlyEtherBankSC
throwIfEqualToZero(_collateralAmount)
throwIfEqualToZero(_loanAmount)
throwIfEqualToZero(_numberOfBlocks)
{
uint256 startBlock = block.number;
uint256 endBlock = startBlock.add(_numberOfBlocks);
uint256 liquidationId = ++lastLiquidationId;
liquidations[liquidationId].loanId = _loanId;
liquidations[liquidationId].collateralAmount = _collateralAmount;
liquidations[liquidationId].loanAmount = _loanAmount;
liquidations[liquidationId].startBlock = startBlock;
liquidations[liquidationId].endBlock = endBlock;
liquidations[liquidationId].state = LiquidationState.ACTIVE;
emit LogStartLiquidation(liquidationId, _collateralAmount, _loanAmount, startBlock, endBlock);
}
/**
* @dev stop an liquidation.
* @param liquidationId The id of the liquidation.
*/
function stopLiquidation(uint256 liquidationId)
public
checkLiquidationState(liquidationId, LiquidationState.ACTIVE)
whenNotPaused
{
require(liquidations[liquidationId].endBlock <= block.number, OPEN_LIQUIDATION);
require(liquidations[liquidationId].bestBid != 0, NO_BID);
liquidations[liquidationId].state = LiquidationState.FINISHED;
token.burn(liquidations[liquidationId].loanAmount);
bank.liquidated(
liquidations[liquidationId].loanId,
liquidations[liquidationId].bestBid,
liquidations[liquidationId].bestBidder
);
emit LogStopLiquidation(liquidationId, liquidations[liquidationId].bestBid, liquidations[liquidationId].bestBidder);
}
/**
* @dev palce a bid on the liquidation.
* @param liquidationId The id of the liquidation.
*/
function placeBid(uint256 liquidationId, uint256 bidAmount)
public
whenNotPaused
checkLiquidationState(liquidationId, LiquidationState.ACTIVE)
{
require(liquidations[liquidationId].loanAmount <= token.allowance(msg.sender, this), INSUFFICIENT_FUNDS);
require(bidAmount < liquidations[liquidationId].bestBid, INADEQUATE_BIDDING);
token.transferFrom(msg.sender, this, liquidations[liquidationId].loanAmount);
deposits[msg.sender] += liquidations[liquidationId].loanAmount;
deposits[liquidations[liquidationId].bestBidder] += liquidations[liquidationId].loanAmount;
deposits[msg.sender] -= liquidations[liquidationId].loanAmount;
liquidations[liquidationId].bestBidder = msg.sender;
liquidations[liquidationId].bestBid = bidAmount;
}
/**
* @dev Get the best bid of the liquidation.
* @param liquidationId The id of the liquidation.
*/
function getBestBid(uint256 liquidationId)
public
view
whenNotPaused
checkLiquidationState(liquidationId, LiquidationState.ACTIVE)
returns(uint256)
{
return liquidations[liquidationId].bestBid;
}
/**
* @dev Throws if state is not equal to needState.
* @param liquidationId The id of the liquidation.
* @param needState The state which needed.
*/
modifier checkLiquidationState(uint256 liquidationId, LiquidationState needState) {
require(liquidations[liquidationId].state == needState, NOT_ACTIVE_LOAN);
_;
}
/**
* @dev Throws if the number is equal to zero.
* @param number The number to validate.
*/
modifier throwIfEqualToZero(uint number) {
require(number != 0, INVALID_AMOUNT);
_;
}
/**
* @dev Throws if called by any account other than our EtherBank smart conrtact.
*/
modifier onlyEtherBankSC() {
require(msg.sender == etherBankAddr, ONLY_ETHER_BANK);
_;
}
}
| Set EtherBank smart contract address. _etherBankAddr The EtherBank smart contract address./ | function setEtherBank(address _etherBankAddr)
external
onlyOwner
whenNotPaused
{
require(_etherBankAddr != address(0), INVALID_ADDRESS);
etherBankAddr = _etherBankAddr;
bank = EtherBank(etherBankAddr);
}
| 12,958,026 |
pragma solidity ^0.6.0;
contract initializable5 { //inject NONSTANDARD NAMING
bool private initialized;
bool private initializing;
modifier INITIALIZER65() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
}
function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING
}
function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
__OWNABLE_INIT_UNCHAINED84();
}
function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER78();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED52(address(0), msgSender);
}
function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER81() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED52(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED52(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
library safemath14 { //inject NONSTANDARD NAMING
function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB60(a, b, "SafeMath: subtraction overflow");
}
function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV54(a, b, "SafeMath: division by zero");
}
function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD56(a, b, "SafeMath: modulo by zero");
}
function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface ierc2086 { //inject NONSTANDARD NAMING
function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library console87 { //inject NONSTANDARD NAMING
address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address36;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG40() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log()"));
}
function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOG40(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
interface iuniswapv2factory11 { //inject NONSTANDARD NAMING
event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO47() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO7(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING
}
contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING
using safemath14 for uint256;
function INITIALIZE58( //inject NONSTANDARD NAMING
address _NANOCOREAddress,
address _WETHAddress,
address _uniswapFactory
) public INITIALIZER65 {
ownableupgradesafe25.__OWNABLE_INIT13();
nanocoreTokenAddress = _NANOCOREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress);
feePercentX100 = 15;
paused = false; // We start paused until sync post LGE happens.
}
address tokenUniswapPair;
iuniswapv2factory11 public uniswapFactory;
address internal WETHAddress;
address nanocoreTokenAddress;
address nanocoreVaultAddress;
uint8 public feePercentX100; // max 255 = 25.5% artificial clamp
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
// Pausing transfers of the token
function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING
paused = _pause;
}
function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING
feePercentX100 = _feeMultiplier;
}
function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING
nanocoreVaultAddress = _nanocoreVaultAddress;
}
function SYNC99() public { //inject NONSTANDARD NAMING
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING
address sender,
address recipient, // unusued maybe use din future
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount)
{
require(paused == false, "FEE APPROVER: Transfers Paused");
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
// console.log("sender is " , sender);
// console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair);
// console.log("Old LP supply", lastTotalSupplyOfLPTokens);
// console.log("Current LP supply", _LPSupplyOfPairTotal);
if(sender == tokenUniswapPair)
require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden");
// console.log('Sender is pair' , sender == tokenUniswapPair);
// console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal);
if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop
console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it)
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
console87.LOG40("Normal fee transfer");
transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000);
transferToAmount = amount.SUB60(transferToFeeDistributorAmount);
}
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
} | inject NONSTANDARD NAMING | function LOG40(string memory p0, uint p1, address p2, address p3) internal view { | 1,019,039 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
import "./interfaces/IFlightSuretyData.sol";
contract FlightSuretyApp {
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codees
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 payable private contractOwner; // Account used to deploy contract
struct ResponseInfo {
address requester;
bool isOpen;
mapping(uint8 => address[]) responses;
}
mapping(bytes32 => ResponseInfo) oracleResponses;
IFlightSuretyData _flightSuretyData;
uint fundingPrice = 10 ether;
uint256 suretyPayoutMultiplier = uint(3)/uint(2);
event AirlineFunded(bool isFunded);
event FlightRegistered(string, uint256, bytes32);
event InsurancePurchased(string);
event PassengerPaid(string, uint256);
/********************************************************************************************/
/* 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()
{
// 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
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires that a funded airline be the function caller
*/
modifier requireFundedAirline()
{
require(_flightSuretyData.isAirlineFunded(msg.sender) == true, "Caller is not a funded airline");
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor(address payable dataContract, address airline)
{
contractOwner = payable(msg.sender);
_flightSuretyData = IFlightSuretyData(dataContract);
_flightSuretyData.registerAirline(airline, msg.sender);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational()
public
view
returns(bool)
{
return _flightSuretyData.isOperational(); // Modify to call data contract's status
}
function isAirline(address airline)
public
view
returns(bool)
{
return _flightSuretyData.isAirline(airline);
}
function isAirlineFunded(address airline)
public
view
returns(bool)
{
return _flightSuretyData.isAirlineFunded(airline);
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline( address airline )
public
requireFundedAirline
returns(bool success, uint256 votes)
{
return _flightSuretyData.registerAirline(airline, msg.sender);
}
/**
* @dev Completes airline registration by funding it.
*
*/
function fundAirline()
public
payable
{
require(_flightSuretyData.isAirline(msg.sender) == true, 'Airline is not registered, kindly register airline.');
require(msg.value >= fundingPrice, 'Please increase the funding price to the appropriate amount');
require(_flightSuretyData.isAirlineFunded(msg.sender) == false, 'Airline already funded');
bool isFunded = _flightSuretyData.fundsAirline(msg.sender, msg.value);
_flightSuretyData.incrementFundedAirlineCount();
emit AirlineFunded(isFunded);
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlights(string calldata flight, uint256 timestamp)
public
{
require(_flightSuretyData.isAirline(msg.sender) == true, 'Only airlines are allowed to register flight.');
require(_flightSuretyData.isAirlineFunded(msg.sender) == true, 'Kindly fund your airline to enjoy added priviledges.');
bytes32 flightKey = _flightSuretyData.registerFlight(
flight, msg.sender, STATUS_CODE_UNKNOWN, timestamp
);
emit FlightRegistered(flight, timestamp, flightKey);
}
/**
* @dev Buy insurance a flight.
*
*/
function buyInsurance(bytes32 flightKey)
public
payable
{
require(_flightSuretyData.isAirline(msg.sender) == false, 'airlines are not allowed to buy flight insurance.');
require(_flightSuretyData.isFlight(flightKey) == true, 'Flight is not registered');
require(msg.value <= 1 ether, 'Insurance cost a maximum of 1 ether');
uint256 payout = msg.value * suretyPayoutMultiplier;
_flightSuretyData.buy(msg.value, msg.sender, flightKey, payout);
emit InsurancePurchased('Insurance purchased successfully');
}
function getFlightKey(address airline, string calldata flight, uint256 timestamp)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus
(
address airline,
string calldata flight,
uint256 timestamp,
uint8 statusCode,
bytes32 key
)
internal
{
oracleResponses[key].isOpen = false;
if(statusCode == STATUS_CODE_LATE_AIRLINE) {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
_flightSuretyData.creditInsurees(oracleResponses[key].requester, flightKey);
return;
}
}
// 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].requester = msg.sender;
oracleResponses[key].isOpen = true;
emit OracleRequest(index, airline, flight, timestamp);
}
// Sends passengers money to his wallet
function payPassenger()
external
{
uint256 passengerPay = _flightSuretyData.pay(msg.sender);
if(passengerPay == 0) revert('You do not have funds for withdrawal');
emit PassengerPaid("You have received the sum of", passengerPay);
}
// 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;
// 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, key);
}
}
// 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;
}
// endregion
}
| Add an airline to the registration queue/ | function registerAirline( address airline )
public
requireFundedAirline
returns(bool success, uint256 votes)
{
return _flightSuretyData.registerAirline(airline, msg.sender);
}
| 14,105,132 |
// SPDX-License-Identifier: BlueOak-1.0.0
pragma solidity 0.8.9;
// solhint-disable-next-line max-line-length
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "contracts/interfaces/IMain.sol";
import "contracts/interfaces/IRewardable.sol";
import "contracts/interfaces/IRToken.sol";
import "contracts/libraries/Fixed.sol";
import "contracts/p1/mixins/Component.sol";
import "contracts/p1/mixins/RewardableLib.sol";
/**
* @title RTokenP1
* @notice An ERC20 with an elastic supply and governable exchange rate to basket units.
*/
/// @custom:oz-upgrades-unsafe-allow external-library-linking
contract RTokenP1 is ComponentP1, IRewardable, ERC20PermitUpgradeable, IRToken {
using SafeERC20Upgradeable for IERC20Upgradeable;
/// Immutable: expected to be an IPFS link but could be anything
string public manifestoURI;
// MIN_ISS_RATE: {rTok/block} 10k whole RTok
uint192 public constant MIN_ISS_RATE = 10_000 * FIX_ONE;
// Enforce a fixed issuanceRate throughout the entire block by caching it.
uint192 public lastIssRate; // D18{rTok/block}
uint256 public lastIssRateBlock; // {block number}
// When all pending issuances will have vested.
// This is fractional so that we can represent partial progress through a block.
uint192 public allVestAt; // D18{fractional block number}
// IssueItem: One edge of an issuance
struct IssueItem {
uint192 when; // D18{block number} fractional
uint256 amtRToken; // {qRTok} Total amount of RTokens that have vested by `when`
uint192 amtBaskets; // D18{BU} Total amount of baskets that should back those RTokens
uint256[] deposits; // {qTok}, Total amounts of basket collateral deposited for vesting
}
struct IssueQueue {
uint256 basketNonce; // The nonce of the basket this queue models deposits against
address[] tokens; // Addresses of the erc20 tokens modelled by deposits in this queue
uint256 left; // [left, right) is the span of currently-valid items
uint256 right; //
IssueItem[] items; // The actual items (The issuance "fenceposts")
}
/*
* If we want to clean up state, it's safe to delete items[x] iff x < left.
* For an initialized IssueQueue queue:
* queue.items.right >= left
* queue.items.right == left iff there are no more pending issuances here
*
* The short way to describe this is that IssueQueue stores _cumulative_ issuances, not raw
* issuances, and so any particular issuance is actually the _difference_ between two adjaacent
* TotalIssue items in an IssueQueue.
*
* The way to keep an IssueQueue striaght in your head is to think of each TotalIssue item as a
* "fencpost" in the queue of actual issuances. The true issuances are the spans between the
* TotalIssue items. For example, if:
* queue.items[queue.left].amtRToken == 1000 , and
* queue.items[queue.right].amtRToken == 6000,
* then the issuance "between" them is 5000 RTokens. If we waited long enough and then called
* vest() on that account, we'd vest 5000 RTokens *to* that account.
*/
mapping(address => IssueQueue) public issueQueues;
uint192 public basketsNeeded; // D18{BU}
uint192 public issuanceRate; // D18{%} of RToken supply to issue per block
function init(
IMain main_,
string calldata name_,
string calldata symbol_,
string calldata manifestoURI_,
uint192 issuanceRate_
) external initializer {
__Component_init(main_);
__ERC20_init(name_, symbol_);
__ERC20Permit_init(name_);
manifestoURI = manifestoURI_;
issuanceRate = issuanceRate_;
emit IssuanceRateSet(FIX_ZERO, issuanceRate_);
}
/// Begin a time-delayed issuance of RToken for basket collateral
/// @param amtRToken {qTok} The quantity of RToken to issue
/// @custom:interaction almost but not quite CEI
function issue(uint256 amtRToken) external interaction {
require(amtRToken > 0, "Cannot issue zero");
// == Refresh ==
main.assetRegistry().refresh();
address issuer = _msgSender(); // OK to save: it can't be changed in reentrant runs
IBasketHandler bh = main.basketHandler(); // OK to save: can only be changed by gov
(uint256 basketNonce, ) = bh.lastSet();
IssueQueue storage queue = issueQueues[issuer];
// Refund issuances against old baskets
if (queue.basketNonce != basketNonce) {
// == Interaction ==
// This violates simple CEI, so we have to renew any potential transient state!
refundSpan(issuer, queue.left, queue.right);
// Refresh collateral after interaction
main.assetRegistry().refresh();
// Refresh local values after potential reentrant changes to contract state.
(basketNonce, ) = bh.lastSet();
queue = issueQueues[issuer];
}
// == Checks-effects block ==
CollateralStatus status = bh.status();
require(status != CollateralStatus.DISABLED, "basket disabled");
main.furnace().melt();
// ==== Compute and accept collateral ====
// D18{BU} = D18{BU} * {qRTok} / {qRTok}
uint192 amtBaskets = uint192(
totalSupply() > 0 ? mulDiv256(basketsNeeded, amtRToken, totalSupply()) : amtRToken
);
(address[] memory erc20s, uint256[] memory deposits) = bh.quote(amtBaskets, CEIL);
// Add amtRToken's worth of issuance delay to allVestAt
uint192 vestingEnd = whenFinished(amtRToken); // D18{block number}
// Bypass queue entirely if the issuance can fit in this block and nothing blocking
if (
vestingEnd <= FIX_ONE_256 * block.number &&
queue.left == queue.right &&
status == CollateralStatus.SOUND
) {
// Complete issuance
_mint(issuer, amtRToken);
uint192 newBasketsNeeded = basketsNeeded + amtBaskets;
emit BasketsNeededChanged(basketsNeeded, newBasketsNeeded);
basketsNeeded = newBasketsNeeded;
// Note: We don't need to update the prev queue entry because queue.left = queue.right
emit Issuance(issuer, amtRToken, amtBaskets);
address backingMgr = address(main.backingManager());
// == Interactions then return: transfer tokens ==
for (uint256 i = 0; i < erc20s.length; ++i) {
IERC20Upgradeable(erc20s[i]).safeTransferFrom(issuer, backingMgr, deposits[i]);
}
return;
}
// Push issuance onto queue
IssueItem storage curr = queue.items.push();
curr.when = vestingEnd;
curr.amtRToken = amtRToken;
curr.amtBaskets = amtBaskets;
curr.deposits = deposits;
// Accumulate
if (queue.right > 0) {
IssueItem storage prev = queue.items[queue.right - 1];
curr.amtRToken = prev.amtRToken + amtRToken;
curr.amtBaskets = prev.amtBaskets + amtBaskets;
for (uint256 i = 0; i < deposits.length; ++i) {
curr.deposits[i] = prev.deposits[i] + deposits[i];
}
}
// Configure queue
queue.basketNonce = basketNonce;
queue.tokens = erc20s;
queue.right++;
emit IssuanceStarted(
issuer,
queue.right - 1,
amtRToken,
amtBaskets,
erc20s,
deposits,
vestingEnd
);
// == Interactions: accept collateral ==
for (uint256 i = 0; i < erc20s.length; ++i) {
IERC20Upgradeable(erc20s[i]).safeTransferFrom(issuer, address(this), deposits[i]);
}
}
/// Add amtRToken's worth of issuance delay to allVestAt, and return the resulting finish time.
/// @return finished D18{bloick number} The new value of allVestAt
function whenFinished(uint256 amtRToken) private returns (uint192 finished) {
// Calculate the issuance rate (if this is the first issuance in the block)
if (lastIssRateBlock < block.number) {
lastIssRateBlock = block.number;
lastIssRate = uint192((issuanceRate * totalSupply()) / FIX_ONE);
if (lastIssRate < MIN_ISS_RATE) lastIssRate = MIN_ISS_RATE;
}
// Add amtRToken's worth of issuance delay to allVestAt
uint192 before = allVestAt; // D18{block number}
uint192 worst = uint192(FIX_ONE * (block.number - 1)); // D18{block number}
if (worst > before) before = worst;
finished = before + uint192((FIX_ONE_256 * amtRToken) / lastIssRate);
allVestAt = finished;
}
/// Vest all available issuance for the account
/// Callable by anyone!
/// @param account The address of the account to vest issuances for
/// @custom:completion
/// @custom:interaction CEI
function vest(address account, uint256 endId) external interaction {
// == Keepers ==
main.assetRegistry().refresh();
// == Checks ==
require(main.basketHandler().status() == CollateralStatus.SOUND, "collateral default");
// Refund old issuances if there are any
IssueQueue storage queue = issueQueues[account];
(uint256 basketNonce, ) = main.basketHandler().lastSet();
// == Interactions ==
// ensure that the queue models issuances against the current basket, not previous baskets
if (queue.basketNonce != basketNonce) {
refundSpan(account, queue.left, queue.right);
} else {
vestUpTo(account, endId);
}
}
/// @return A non-inclusive ending index
function endIdForVest(address account) external view returns (uint256) {
IssueQueue storage queue = issueQueues[account];
uint256 blockNumber = FIX_ONE_256 * block.number; // D18{block number}
// Handle common edge cases in O(1)
if (queue.left == queue.right) return queue.left;
if (blockNumber < queue.items[queue.left].when) return queue.left;
if (queue.items[queue.right - 1].when <= blockNumber) return queue.right;
// find left and right (using binary search where always left <= right) such that:
// left == right - 1
// queue[left].when <= block.timestamp
// right == queue.right or block.timestamp < queue[right].when
uint256 left = queue.left;
uint256 right = queue.right;
while (left < right - 1) {
uint256 test = (left + right) / 2;
if (queue.items[test].when < blockNumber) left = test;
else right = test;
}
return right;
}
/// Cancel some vesting issuance(s)
/// If earliest == true, cancel id if id < endId
/// If earliest == false, cancel id if endId <= id
/// @param endId The issuance index to cancel through
/// @param earliest If true, cancel earliest issuances; else, cancel latest issuances
/// @custom:interaction CEI
function cancel(uint256 endId, bool earliest) external interaction {
address account = _msgSender();
IssueQueue storage queue = issueQueues[account];
require(queue.left <= endId && endId <= queue.right, "'endId' is out of range");
// == Interactions ==
if (earliest) {
refundSpan(account, queue.left, endId);
} else {
refundSpan(account, endId, queue.right);
}
}
/// Redeem RToken for basket collateral
/// @param amount {qTok} The quantity {qRToken} of RToken to redeem
/// @custom:action
/// @custom:interaction CEI
function redeem(uint256 amount) external interaction {
require(amount > 0, "Cannot redeem zero");
// == Refresh ==
main.assetRegistry().refresh();
// == Checks and Effects ==
address redeemer = _msgSender();
require(balanceOf(redeemer) >= amount, "not enough RToken");
// Allow redemption during IFFY
require(main.basketHandler().status() != CollateralStatus.DISABLED, "collateral default");
main.furnace().melt();
uint192 basketsNeeded_ = basketsNeeded; // gas optimization
// D18{BU} = D18{BU} * {qRTok} / {qRTok}
uint192 baskets = uint192(mulDiv256(basketsNeeded_, amount, totalSupply()));
emit Redemption(redeemer, amount, baskets);
(address[] memory erc20s, uint256[] memory amounts) = main.basketHandler().quote(
uint192(baskets),
FLOOR
);
// D18{1} = D18 * {qRTok} / {qRTok}
uint192 prorate = uint192((FIX_ONE_256 * amount) / totalSupply());
// Accept and burn RToken
_burn(redeemer, amount);
basketsNeeded = basketsNeeded_ - baskets;
emit BasketsNeededChanged(basketsNeeded_, basketsNeeded);
// ==== Send back collateral tokens ====
IBackingManager backingMgr = main.backingManager();
uint256 erc20length = erc20s.length;
// Bound each withdrawal by the prorata share, in case we're currently under-capitalized
for (uint256 i = 0; i < erc20length; ++i) {
// {qTok} = D18{1} * {qTok} / D18
uint256 prorata = (prorate *
IERC20Upgradeable(erc20s[i]).balanceOf(address(backingMgr))) / FIX_ONE;
if (prorata < amounts[i]) amounts[i] = prorata;
}
// == Interactions ==
for (uint256 i = 0; i < erc20length; ++i) {
// Send withdrawal
IERC20Upgradeable(erc20s[i]).safeTransferFrom(
address(backingMgr),
redeemer,
amounts[i]
);
}
}
/// Mint a quantity of RToken to the `recipient`, decreasing the basket rate
/// @param recipient The recipient of the newly minted RToken
/// @param amtRToken {qRTok} The amtRToken to be minted
/// @custom:protected
function mint(address recipient, uint256 amtRToken) external notPaused {
require(_msgSender() == address(main.backingManager()), "not backing manager");
_mint(recipient, amtRToken);
}
/// Melt a quantity of RToken from the caller's account, increasing the basket rate
/// @param amtRToken {qRTok} The amtRToken to be melted
function melt(uint256 amtRToken) external notPaused {
_burn(_msgSender(), amtRToken);
emit Melted(amtRToken);
}
/// An affordance of last resort for Main in order to ensure re-capitalization
/// @custom:protected
function setBasketsNeeded(uint192 basketsNeeded_) external notPaused {
require(_msgSender() == address(main.backingManager()), "not backing manager");
emit BasketsNeededChanged(basketsNeeded, basketsNeeded_);
basketsNeeded = basketsNeeded_;
}
/// Claim all rewards and sweep to BackingManager
/// @custom:interaction
function claimAndSweepRewards() external interaction {
RewardableLibP1.claimAndSweepRewards();
}
/// @custom:governance
function setIssuanceRate(uint192 val) external governance {
emit IssuanceRateSet(issuanceRate, val);
issuanceRate = val;
}
/// @return {UoA/rTok} The protocol's best guess of the RToken price on markets
function price() external view returns (uint192) {
if (totalSupply() == 0) return main.basketHandler().price();
// D18{UoA/rTok} = D18{UoA/BU} * D18{BU} / D18{rTok}
return
uint192(mulDiv256(main.basketHandler().price(), basketsNeeded, totalSupply(), ROUND));
}
/// @dev This function is only here because solidity can't autogenerate our getter
function issueItem(address account, uint256 index) external view returns (IssueItem memory) {
return issueQueues[account].items[index];
}
// ==== private ====
/// Refund all deposits in the span [left, right)
/// after: queue.left == queue.right
/// @custom:interaction
function refundSpan(
address account,
uint256 left,
uint256 right
) private {
if (left >= right) return; // refund an empty span
IssueQueue storage queue = issueQueues[account];
// compute total deposits to refund
uint256 tokensLen = queue.tokens.length;
uint256[] memory amt = new uint256[](tokensLen);
IssueItem storage rightItem = queue.items[right - 1];
// we could dedup this logic but it would take more SLOADS, so I think this is best
if (queue.left == 0) {
for (uint256 i = 0; i < tokensLen; ++i) {
amt[i] = rightItem.deposits[i];
}
} else {
IssueItem storage leftItem = queue.items[queue.left - 1];
for (uint256 i = 0; i < tokensLen; ++i) {
amt[i] = rightItem.deposits[i] - leftItem.deposits[i];
}
}
// Check the relationships of these intervals, and set queue.{left, right} to final values.
if (queue.left == left && right <= queue.right) {
// refund from beginning of queue
queue.left = right;
} else if (queue.left < left && right == queue.right) {
// refund from end of queue
queue.right = left;
} else {
// error: can't remove [left,right) from the queue, and leave just one interval
revert("Bad refundSpan");
}
emit IssuancesCanceled(account, left, right);
// == Interactions ==
for (uint256 i = 0; i < queue.tokens.length; ++i) {
IERC20Upgradeable(queue.tokens[i]).safeTransfer(account, amt[i]);
}
}
/// Vest all RToken issuance in queue = queues[account], from queue.left to < endId
/// Fixes up queue.left and queue.right
/// @custom:interaction
function vestUpTo(address account, uint256 endId) private {
IssueQueue storage queue = issueQueues[account];
if (queue.left == endId) return;
require(queue.left <= endId && endId <= queue.right, "'endId' is out of range");
// Vest the span up to `endId`.
uint256 amtRToken;
uint192 amtBaskets;
IssueItem storage rightItem = queue.items[endId - 1];
require(rightItem.when <= 1e18 * block.number, "issuance not ready");
uint256 queueLength = queue.tokens.length;
uint256[] memory amtDeposits = new uint256[](queueLength);
// we could dedup this logic but it would take more SLOADS, so this seems best
if (queue.left == 0) {
for (uint256 i = 0; i < queueLength; ++i) {
amtDeposits[i] = rightItem.deposits[i];
}
amtRToken = rightItem.amtRToken;
amtBaskets = rightItem.amtBaskets;
} else {
IssueItem storage leftItem = queue.items[queue.left - 1];
for (uint256 i = 0; i < queueLength; ++i) {
amtDeposits[i] = rightItem.deposits[i] - leftItem.deposits[i];
}
amtRToken = rightItem.amtRToken - leftItem.amtRToken;
amtBaskets = rightItem.amtBaskets - leftItem.amtBaskets;
}
_mint(account, amtRToken);
emit BasketsNeededChanged(basketsNeeded, basketsNeeded + amtBaskets);
basketsNeeded = basketsNeeded + amtBaskets;
emit Issuance(account, amtRToken, amtBaskets);
emit IssuancesCompleted(account, queue.left, endId);
queue.left = endId;
// == Interactions ==
for (uint256 i = 0; i < queueLength; ++i) {
IERC20Upgradeable(queue.tokens[i]).safeTransfer(
address(main.backingManager()),
amtDeposits[i]
);
}
}
}
| Claim all rewards and sweep to BackingManager @custom:interaction | function claimAndSweepRewards() external interaction {
RewardableLibP1.claimAndSweepRewards();
}
| 1,015,582 |
/**
*Submitted for verification at Etherscan.io on 2022-03-11
*/
// File: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.6.2;
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);
}
// File: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
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;
}
// File: musashi-js/contracts/Farm/price-convertor/TransferHelper.sol
pragma solidity 0.6.12;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// File: musashi-js/contracts/Farm/price-convertor/SafeMath.sol
pragma solidity 0.6.12;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a, 'SafeMath:INVALID_ADD');
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a, 'SafeMath:OVERFLOW_SUB');
c = a - b;
}
function mul(uint a, uint b, uint decimal) internal pure returns (uint) {
uint dc = 10**decimal;
uint c0 = a * b;
require(a == 0 || c0 / a == b, "SafeMath: multiple overflow");
uint c1 = c0 + (dc / 2);
require(c1 >= c0, "SafeMath: multiple overflow");
uint c2 = c1 / dc;
return c2;
}
function div(uint256 a, uint256 b, uint decimal) internal pure returns (uint256) {
require(b != 0, "SafeMath: division by zero");
uint dc = 10**decimal;
uint c0 = a * dc;
require(a == 0 || c0 / a == dc, "SafeMath: division internal");
uint c1 = c0 + (b / 2);
require(c1 >= c0, "SafeMath: division internal");
uint c2 = c1 / b;
return c2;
}
}
// File: musashi-js/contracts/Farm/price-convertor/PriceConvertor.sol
pragma solidity 0.6.12;
contract PriceConvertor {
using SafeMath for uint;
uint constant ETHER_DECIMAL = 18;
address public owner;
address public token_usdt;
address public uniswap_factory;
address public uniswap_router;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
constructor() public {
owner = msg.sender;
token_usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
uniswap_factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
uniswap_router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
}
// (default asset) convert token to usd. assume token have pair with BNB
function getTokenToUsd(address token, uint token0Amount) public view returns (uint) {
address[] memory path = new address[](2);
path[0] = token;
path[1] = IUniswapV2Router02(uniswap_router).WETH();
uint bnb = _getPrice(token0Amount, path);
address[] memory path2 = new address[](2);
path2[0] = IUniswapV2Router02(uniswap_router).WETH();
path2[1] = token_usdt;
return _getPrice(bnb, path2);
}
// get WETH from the router
function getWeth() public view returns (address) {
return IUniswapV2Router02(uniswap_router).WETH();
}
// convert any pairing
function getPrice(uint token0Amount, address[] memory pair) public view returns (uint) {
return _getPrice(token0Amount, pair);
}
// update factory address
function updateUniswapFactory(address _address) public onlyOwner {
uniswap_factory = _address;
}
// update router address
function updateUniswapRouter(address _address) public onlyOwner {
uniswap_router = _address;
}
// update token_usdt address
function updateUsdt(address _address) public onlyOwner {
token_usdt = _address;
}
// transfer ownership
function transferOwner(address _address) public onlyOwner {
owner = _address;
}
// emergency transfer ether to owner. only owner executable
function emergencyTransferEther(uint amount) public onlyOwner {
TransferHelper.safeTransferETH(owner, amount);
}
// emergency transfer any token to owner. only owner executable
function emergencyTransferToken(address token, uint amount) public onlyOwner {
TransferHelper.safeTransfer(token, owner, amount);
}
// get pair price rate as close as the raw price
function _getPrice(uint token0Amount, address[] memory pair) internal view returns (uint) {
// retrieve reserve of pairing
(uint reserve0, uint reserve1,) = IUniswapPair(IUniswapFactory(uniswap_factory).getPair(pair[0], pair[1])).getReserves();
address token0 = IUniswapPair(IUniswapFactory(uniswap_factory).getPair(pair[0], pair[1])).token0();
address token1 = IUniswapPair(IUniswapFactory(uniswap_factory).getPair(pair[0], pair[1])).token1();
// convert to WEI unit for calculation
reserve0 = reserve0 * 10**(ETHER_DECIMAL.sub(IERC20(token0).decimals()));
reserve1 = reserve1 * 10**(ETHER_DECIMAL.sub(IERC20(token1).decimals()));
token0Amount = token0Amount * 10**(ETHER_DECIMAL.sub(IERC20(pair[0]).decimals()));
// calculate price rate
uint price = token0Amount.mul((token0 == pair[0] ? reserve1 : reserve0), ETHER_DECIMAL);
price = price.div((token0 == pair[0] ? reserve0 : reserve1), ETHER_DECIMAL);
// convert WEI unit to the output currency decimal
price = price / 10**(ETHER_DECIMAL.sub(IERC20(pair[1]).decimals()));
return price;
}
}
interface IERC20 {
function decimals() external view returns (uint);
}
interface IUniswapFactory {
function getPair(address tokenA, address tokenB) external view returns (address);
}
interface IUniswapPair {
function getReserves() external view returns (uint112, uint112, uint32);
function token0() external view returns (address);
function token1() external view returns (address);
} | convert any pairing | function getPrice(uint token0Amount, address[] memory pair) public view returns (uint) {
return _getPrice(token0Amount, pair);
}
| 10,533,651 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./MemeNumbersRenderer.sol";
library Errors {
string constant AlreadyMinted = "already minted";
string constant UnderPriced = "current price is higher than msg.value";
string constant NotForSale = "number is not for sale in this batch";
string constant MustOwnNum = "must own number to operate on it";
string constant NoSelfBurn = "burn numbers must be different";
string constant InvalidOp = "invalid op";
string constant DoesNotExist = "does not exist";
string constant RendererUpgradeDisabled = "renderer upgrade disabled";
}
contract MemeNumbers is ERC721, Ownable {
uint256 public constant AUCTION_START_PRICE = 5 ether;
uint256 public constant AUCTION_DURATION = 1 hours;
uint256 public constant BATCH_SIZE = 8;
uint256 constant DECAY_RESOLUTION = 1000000000; // 1 gwei
uint256 public auctionStarted;
uint256[BATCH_SIZE] private forSale;
mapping(uint256 => bool) viaBurn; // Numbers that were created via burn
/// disableRenderUpgrade is whether we can still upgrade the tokenURI renderer.
/// Once it is set it cannot be unset.
bool disableRenderUpgrade = false;
ITokenRenderer public renderer;
/// @notice Emitted when the auction batch is refreshed.
event Refresh(); // TODO: Do we want to include any fields?
constructor(address _renderer) ERC721("MemeNumbers", "MEMENUM") {
renderer = ITokenRenderer(_renderer);
_refresh();
}
// Internal helpers:
function _getEntropy() view internal returns(uint256) {
// This is not ideal but it's not practical to do a real source of entropy
// like ChainLink with 2 LINK per refresh shuffle.
// Borrowed from: https://github.com/1001-digital/erc721-extensions/blob/f5c983bac8989bc5ebf9b34c03f28e438da9a7b3/contracts/RandomlyAssigned.sol#L27
return uint256(keccak256(
abi.encodePacked(
msg.sender,
block.coinbase,
block.difficulty,
block.gaslimit,
block.timestamp,
blockhash(block.number))));
}
/**
* @dev Generate a fresh sequence available for sale based on the current block state.
*/
function _refresh() internal {
auctionStarted = block.timestamp;
uint256 entropy = _getEntropy();
// Slice up our 256 bits of entropy into delicious bite-sized numbers.
// Eligibility is confirmed during isForSale, getForSale, and mint.
// Eligible batches can be smaller than the forSale batch.
forSale[0] = (entropy >> 0) & (2 ** 8 - 1);
forSale[1] = (entropy >> 5) & (2 ** 10 - 1);
forSale[2] = (entropy >> 8) & (2 ** 14 - 1);
forSale[3] = (entropy >> 8) & (2 ** 18 - 1);
forSale[4] = (entropy >> 13) & (2 ** 24 - 1);
forSale[5] = (entropy >> 21) & (2 ** 32 - 1);
forSale[6] = (entropy >> 34) & (2 ** 64 - 1);
forSale[7] = (entropy >> 55) & (2 ** 86 - 1);
emit Refresh();
}
// Public views:
/// @notice The current price of the dutch auction. Winning bids above this price will return the difference.
function currentPrice() view public returns(uint256) {
// Linear price reduction from AUCTION_START_PRICE to 0
uint256 endTime = (auctionStarted + AUCTION_DURATION);
if (block.timestamp >= endTime) {
return 0;
}
uint256 elapsed = endTime - block.timestamp;
return AUCTION_START_PRICE * ((elapsed * DECAY_RESOLUTION) / AUCTION_DURATION) / DECAY_RESOLUTION;
}
/// @notice Return whether a number is for sale and eligible
function isForSale(uint256 num) view public returns (bool) {
for (uint256 i=0; i<forSale.length; i++) {
if (forSale[i] == num) return !_exists(num);
}
return false;
}
/// @notice Eligible numbers for sale.
/// @return nums Array of numbers available for sale.
function getForSale() view external returns (uint256[] memory nums) {
uint256[] memory batch = new uint256[](BATCH_SIZE);
uint256 count = 0;
for (uint256 i=0; i<forSale.length; i++) {
if (_exists(forSale[i])) continue;
batch[count] = forSale[i];
count += 1;
}
// Copy to properly-sized array
nums = new uint256[](count);
for (uint256 i=0; i<count; i++) {
nums[i] = batch[i];
}
return nums;
}
/// @notice Returns whether num was minted by burning, or if it is an original from auction.
function isMintedByBurn(uint256 num) view external returns (bool) {
return viaBurn[num];
}
/**
* @notice Apply a mathematical operation on two numbers, returning the
* resulting number. Treat this as a partial read-only preview of `burn`.
* This preview does *not* account for the mint state of numbers.
* @param num1 Number to burn, must own
* @param op Operation to burn num1 and num2 with, one of: add, sub, mul, div
* @param num2 Number to burn, must own
*/
function operate(uint256 num1, string calldata op, uint256 num2) public pure returns (uint256) {
bytes1 mode = bytes(op)[0];
if (mode == "a") { // Add
return num1 + num2;
}
if (mode == "s") { // Subtact
return num1 - num2;
}
if (mode == "m") { // Multiply
return num1 * num2;
}
if (mode == "d") { // Divide
return num1 / num2;
}
revert(Errors.InvalidOp);
}
// Main interface:
/**
* @notice Mint one of the numbers that are currently for sale at the current dutch auction price.
* @param to Address to mint the number into.
* @param num Number to mint, must be in the current for-sale sequence.
*
* Emits a {Refresh} event.
*/
function mint(address to, uint256 num) external payable {
uint256 price = currentPrice();
require(price <= msg.value, Errors.UnderPriced);
require(isForSale(num), Errors.NotForSale);
_mint(to, num);
_refresh();
if (msg.value > price) {
// Refund difference of currentPrice vs msg.value to allow overbidding
payable(msg.sender).transfer(msg.value - price);
}
}
/**
* @notice Mint all of the eligible numbers for sale, uses more gas than mint but you get more numbers.
* @param to Address to mint the numbers into.
*
* Emits a {Refresh} event.
*/
function mintAll(address to) external payable {
uint256 price = currentPrice();
require(price <= msg.value, Errors.UnderPriced);
for (uint256 i=0; i<forSale.length; i++) {
if (_exists(forSale[i])) continue;
_mint(to, forSale[i]);
}
_refresh();
if (msg.value > price) {
// Refund difference of currentPrice vs msg.value to allow overbidding
payable(msg.sender).transfer(msg.value - price);
}
}
/**
* @notice Refresh the auction without minting once the auction price is 0. More gas efficient than doing a free mint.
*
* Emits a {Refresh} event.
*/
function refresh() external {
require(currentPrice() == 0, Errors.UnderPriced);
_refresh();
}
/**
* @notice Burn two numbers together using a mathematical operation, producing
* a new number if it is not already taken. No minting fee required.
* @param to Address to mint the resulting number into.
* @param num1 Number to burn, must own
* @param op Operation to burn num1 and num2 with, one of: add, sub, mul, div
* @param num2 Number to burn, must own
*/
function burn(address to, uint256 num1, string calldata op, uint256 num2) external {
require(num1 != num2, Errors.NoSelfBurn);
require(ownerOf(num1) == _msgSender(), Errors.MustOwnNum);
require(ownerOf(num2) == _msgSender(), Errors.MustOwnNum);
uint256 num = operate(num1, op, num2);
require(!_exists(num), Errors.AlreadyMinted);
_mint(to, num);
viaBurn[num] = true;
_burn(num1);
_burn(num2);
delete viaBurn[num1];
delete viaBurn[num2];
}
// Renderer:
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) {
require(_exists(tokenId), Errors.DoesNotExist);
return renderer.tokenURI(IMemeNumbers(address(this)), tokenId);
}
// onlyOwner admin functions:
/// @notice Withdraw contract balance.
function adminWithdraw(address payable to) external onlyOwner {
to.transfer(address(this).balance);
}
/// @notice Change the tokenURI renderer.
/// @param _renderer Address of ITokenRenderer.
function adminSetRenderer(address _renderer) external onlyOwner {
require(disableRenderUpgrade == false, Errors.RendererUpgradeDisabled);
renderer = ITokenRenderer(_renderer);
}
/// @notice Disable upgrading the renderer. Once it is disabled, it cannot be enabled again.
function adminDisableRenderUpgrade() external onlyOwner {
disableRenderUpgrade = true;
}
}
| Disable upgrading the renderer. Once it is disabled, it cannot be enabled again. | function adminDisableRenderUpgrade() external onlyOwner {
disableRenderUpgrade = true;
}
| 6,405,312 |
pragma solidity ^0.4.26;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// Ownership contract
// _newOwner is address of new owner
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = 0x07b423cf5481417013E4Ae435A1A060F94D88945;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// transfer Ownership to other address
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0));
emit OwnershipTransferred(owner,_newOwner);
owner = _newOwner;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
contract Yfkp3rToken is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public RATE;
uint public DENOMINATOR;
bool public isStopped = false;
uint public minimumbuy;
uint public maximumbuy;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event ChangeRate(uint256 amount);
modifier onlyWhenRunning {
require(!isStopped);
_;
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Yfkp3r";
name = "Yfkp3r Token";
decimals = 18;
_totalSupply = 4500 * 10**uint(decimals);
balances[owner] = _totalSupply;
RATE = 5000; // 1 ETH = 5 Yfkp3r
minimumbuy = 10**17;
maximumbuy = 2*10**18;
DENOMINATOR = 1000;
emit Transfer(address(0), owner, _totalSupply);
}
// ----------------------------------------------------------------------------
// requires enough gas for execution
// ----------------------------------------------------------------------------
function() public payable {
buyTokens();
}
// ----------------------------------------------------------------------------
// Function to handle eth and token transfers
// tokens are transferred to user
// ETH are transferred to current owner
// ----------------------------------------------------------------------------
function buyTokens() onlyWhenRunning public payable {
require(msg.value > 0);
uint tokens = msg.value.mul(RATE).div(DENOMINATOR);
require(balances[owner] >= tokens);
balances[msg.sender] = balances[msg.sender].add(tokens);
balances[owner] = balances[owner].sub(tokens);
emit Transfer(owner, msg.sender, tokens);
owner.transfer(msg.value);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
require(to != address(0));
require(tokens > 0);
require(balances[msg.sender] >= tokens);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
require(spender != address(0));
require(tokens > 0);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(from != address(0));
require(to != address(0));
require(tokens > 0);
require(balances[from] >= tokens);
require(allowed[from][msg.sender] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Increase the amount of tokens that an owner allowed to a spender.
//
// approve should be called when allowed[_spender] == 0. To increment
// allowed value is better to use this function to avoid 2 calls (and wait until
// the first transaction is mined)
// _spender The address which will spend the funds.
// _addedValue The amount of tokens to increase the allowance by.
// ------------------------------------------------------------------------
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// ------------------------------------------------------------------------
// Decrease the amount of tokens that an owner allowed to a spender.
//
// approve should be called when allowed[_spender] == 0. To decrement
// allowed value is better to use this function to avoid 2 calls (and wait until
// the first transaction is mined)
// _spender The address which will spend the funds.
// _subtractedValue The amount of tokens to decrease the allowance by.
// ------------------------------------------------------------------------
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
require(_spender != address(0));
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// ------------------------------------------------------------------------
// Change the ETH to IO rate
// ------------------------------------------------------------------------
function changeRate(uint256 _rate) public onlyOwner {
require(_rate > 0);
RATE =_rate;
emit ChangeRate(_rate);
}
// ------------------------------------------------------------------------
// _to The address that will receive the minted tokens.
// _amount The amount of tokens to mint.
// A boolean that indicates if the operation was successful.
// ------------------------------------------------------------------------
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
require(_to != address(0));
require(_amount > 0);
uint newamount = _amount * 10**uint(decimals);
_totalSupply = _totalSupply.add(newamount);
balances[_to] = balances[_to].add(newamount);
emit Transfer(address(0), _to, newamount);
return true;
}
// ------------------------------------------------------------------------
// function to stop the ICO
// ------------------------------------------------------------------------
function stopPRESALE() onlyOwner public {
isStopped = true;
}
// ------------------------------------------------------------------------
// function to resume ICO
// ------------------------------------------------------------------------
function resumePRESALE() onlyOwner public {
isStopped = false;
}
} | ------------------------------------------------------------------------ function to resume ICO ------------------------------------------------------------------------ | function resumePRESALE() onlyOwner public {
isStopped = false;
}
| 10,110,753 |
./full_match/56/0x06d5021b75693Eebd8a998d546Ad7875198720CE/sources/project_/contracts/CHT.sol | Destroys `amount` tokens from the user. See {ERC20-_burn}./ | function burn(uint256 amount) public override onlyMintableGroup {
_burn(_msgSender(), amount);
}
| 3,257,946 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../common/Decimal.sol";
import "../common/SafeMath.sol";
import "../common/IERC20.sol";
import "../common/SafeERC20.sol";
import "../ownership/Ownable.sol";
import "../utils/Version.sol";
import "./ManagerConstants.sol";
import "./RewardDistribution.sol";
// BridgeManager implements the Fantom CrossChain Bridge management
// contract.
contract BridgeManager is Initializable, Ownable, Context, ManagerConstants, RewardDistribution, Version {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// ------------------------------
// structs
// ------------------------------
// Validator represents a Bridge validator record
struct Validator {
// status pf the Validator
uint256 status;
uint256 receivedStake;
// milestones in the Validator's life
uint256 createdTime;
uint256 deactivatedTime;
// authorized address of the Validator
address auth;
}
// UnstakingRequest represents a structure describing
// a request for (partial) stake removal.
struct UnstakingRequest {
uint256 time;
uint256 amount;
}
// ------------------------------
// state variables storage space
// ------------------------------
// getValidator represents the list of validators by their IDs
mapping(uint256 => Validator) public getValidator;
// validatorMetadata stores encoded validator information in case
// validators wanted to present their details to the community
mapping(uint256 => bytes) public validatorMetadata;
// getValidatorID represents the relation between a Validator address
// and the ID of the Validator.
mapping(address => uint256) public getValidatorID;
// getDelegation represents the amount of stake granted by a staker address
// to the given validator.
// Map: Staker => ValidatorID => Amount
mapping(address => mapping(uint256 => uint256)) public getDelegation;
// getUnstakingRequest represents the structure of un-staking requests
// being placed from the given staker address to the given validator.
// Each request must have a unique requestID identifier under which
// the unstaking is registered.
// Map: Staker => ValidatorID => RequestID => UnstakingRequest struct
mapping(address => mapping(uint256 => mapping(uint256 => UnstakingRequest))) public getUnstakingRequest;
// lastValidatorID represents the ID of the latest validator;
// it also represents the total number of Validators since a new validator
// is assigned the next available ID and zero ID is skipped.
uint256 public lastValidatorID;
// totalSlashedStake represents the total amount of staked tokens
// slashed by the protocol due to validators malicious behaviour.
uint256 public totalSlashedStake;
// totalStake represents the total amount of staked tokens across
// all active Validators.
uint256 totalStake;
// stakingToken represents the address of an ERC20 token used for staking
// on the Bridge.
IERC20 public stakingToken;
// validatorMetadata represents the metadata of a Validator by the ID;
// please check documentation for the expected metadata structure (JSON object)
mapping(uint256 => bytes) public validatorMetadata;
// ----------------------------
// events
// ----------------------------
event UpdatedValidatorWeight(uint256 indexed validatorID, uint256 weight);
// ------------------------------
// init & reset state logic
// ------------------------------
// initialize sets the initial state of the bridge manager creating the genesis set
// of bridge validators and assigning the contract owner and tokens
function initialize(address stToken, address rwToken, address[] memory gnsValidators) external initializer {
// initialize the owner
Ownable.initialize(msg.sender);
// setup the stake token
stakingToken = IERC20(stToken);
// setup rewards distribution
_initRewards(rwToken, initialRewardRate());
// create the first genesis set of validators
// we don't handle staking here, the stake
// for this genesis batch will be added later through stake() call
for (uint256 i = 0; i < gnsValidators.length; i++) {
_createValidator(gnsValidators[i]);
}
}
// ------------------------------
// interface
// ------------------------------
// createValidator allows a new candidate to sign up as a validator
function createValidator(uint256 stake) external {
// make the validator record
_createValidator(msg.sender);
// register the validator stake
_stake(_sender(), lastValidatorID, stake);
}
// stake increases the stake of the given validator identified
// by the validator ID from the sender by the given amount of staking tokens.
function stake(uint256 validatorID, uint256 amount) external {
// validator must exist to receive stake
require(_validatorExists(validatorID), "BridgeManager: unknown validator");
// stash accumulated rewards up to this point before the stake amount is updated
rewardUpdate(_sender(), validatorID);
// process the stake
_stake(_sender(), validatorID, amount);
}
// setValidatorMetadata stores the new metadata for the validator
// we don't validate the metadata here, please check the documentation
// to get the recommended and expected structure of the metadata
function setValidatorMetadata(bytes calldata metadata) external {
// validator must exist
uint256 validatorID = getValidatorID[_sender()];
require(0 < validatorID, "BridgeManager: unknown validator address");
// store the new metadata content
validatorMetadata[validatorID] = metadata;
}
// unstake decreases the stake of the given validator identified
// by the validator ID from the sender by the given amount of staking tokens.
// User chooses the request ID, which must be unique and not used before.
function unstake(uint256 validatorID, uint256 amount, uint256 requestID) external {
// validator must exist to receive stake
require(_validatorExists(validatorID), "BridgeManager: unknown validator");
// stash accumulated rewards so the staker doesn't loose any
rewardUpdate(_sender(), validatorID);
// process the unstake starter
_unstake(requestID, _sender(), validatorID, amount);
}
// canWithdraw checks if the given un-stake request for the given delegate and validator ID
// is already unlocked and ready to be withdrawn.
function canWithdraw(address delegate, uint256 validatorID, uint256 requestID) external view returns (bool) {
// if the validator dropped its validation account, delegations will unlock sooner
uint256 requestTime = getUnstakingRequest[delegate][validatorID][requestID].time;
if (0 < getValidator[validatorID].deactivatedTime && requestTime > getValidator[validatorID].deactivatedTime) {
requestTime = getValidator[validatorID].deactivatedTime;
}
return /* the request must exist */ 0 < requestTime &&
/* enough time passed from the unstaking */ _now() <= requestTime + unstakePeriodTime();
}
// withdraw transfers previously un-staked tokens back to the staker/delegator, if possible
// this is the place where we check for a slashing, if a validator did not behave correctly
function withdraw(uint256 validatorID, uint256 requestID) external {
// make sure the request can be withdrawn
address delegate = _sender();
require(canWithdraw(delegate, validatorID, requestID), "BridgeManager: can not withdraw");
// do the withdraw
_withdraw(delegate, validatorID, requestID);
}
// ------------------------------
// business logic
// ------------------------------
// _createValidator builds up the validator structure
function _createValidator(address auth) internal {
// make sure the validator does not exist yet
require(0 == getValidatorID[auth], "BridgeManager: validator already exists");
// what will be the new validator id
uint256 validatorID = ++lastValidatorID;
getValidatorID[auth] = validatorID;
// update the validator core record
getValidator[validatorID].status = STATUS_NEW;
getValidator[validatorID].createdTime = _now();
getValidator[validatorID].auth = auth;
}
// _stake processes a new stake of a validator
function _stake(address delegator, uint256 toValidatorID, uint256 amount) internal {
// make sure the staking request is valid
require(0 == getValidator[toValidatorID].status & MASK_INACTIVE, "BridgeManager: validator not active");
require(0 < amount, "BridgeManager: zero stake rejected");
require(amount <= stakingToken.allowance(delegator, address(this)), "BridgeManager: allowance too low");
// transfer the stake tokens first
stakingToken.safeTransferFrom(delegator, address(this), amount);
// remember the stake and add the staked amount to the validator's total stake value
// we add the amount using SafeMath to prevent overflow
totalStake = totalStake.add(amount);
getDelegation[delegator][toValidatorID] = getDelegation[delegator][toValidatorID].add(amount);
getValidator[toValidatorID].receivedStake = getValidator[toValidatorID].receivedStake.add(amount);
// make sure the validator stake is at least the min amount required
require(minStakeAmount() <= getValidator[toValidatorID].receivedStake, "BridgeManager: stake too low");
require(_checkDelegatedStakeLimit(toValidatorID), "BridgeManager: delegations limit exceeded");
// notify the update
_notifyValidatorWeightChange(toValidatorID);
}
// _unstake begins the process of lowering staked tokens by the given amount
function _unstake(uint256 id, address delegator, uint256 toValidatorID, uint256 amount) internal {
// validate the request
require(0 < amount, "BridgeManager: zero un-stake rejected");
require(amount <= getDelegation[delegator][toValidatorID], "BridgeManager: not enough staked");
require(0 == getUnstakingRequest[delegator][toValidatorID][id].amount, "BridgeManager: request ID already in use");
// update the staking picture
// we can subtract directly since we already tested the request validity and underflow can not happen
getDelegation[delegator][toValidatorID] -= amount;
getValidator[toValidatorID].receivedStake -= amount;
totalStake -= amount;
// check the remained stake validity and/or validator deactivation condition
require(_checkDelegatedStakeLimit(toValidatorID) || 0 == _selfStake(toValidatorID), "BridgeManager: delegations limit exceeded");
if (0 == _selfStake(toValidatorID)) {
_deactivateValidator(toValidatorID);
}
// add the request record
getUnstakingRequest[delegator][toValidatorID][id].amount = amount;
getUnstakingRequest[delegator][toValidatorID][id].time = _now();
// notify the update
_notifyValidatorWeightChange(toValidatorID);
}
// _withdraw transfers previously un-staked tokens back to the staker/delegator, if possible
// this is the place where we check for a slashing, if a validator did not behave correctly
function _withdraw(address delegate, uint256 validatorID, uint256 requestID) internal {
// get the request amount and drop the request; we don't need it anymore
uint256 amount = getUnstakingRequest[delegate][validatorID][requestID].amount;
delete getUnstakingRequest[delegate][validatorID][requestID];
// do we slash the stake?
if (0 == getValidator[validatorID].status & STATUS_ERROR) {
// transfer tokens to the delegate
stakingToken.safeTransfer(delegate, amount);
} else {
// we don't transfer anything and just add the stake to total slash
totalSlashedStake = totalSlashedStake.add(amount);
}
}
// _validatorExists performs a check for a validator existence
function _validatorExists(uint256 validatorID) view internal returns (bool) {
return getValidator[validatorID].status > 0;
}
// _isSelfStake checks if the given stake is actually an initial stake of the validator.
function _isSelfStake(address delegator, uint256 toValidatorID) internal view returns (bool) {
return getValidatorID[delegator] == toValidatorID;
}
// _selfStake returns the amount of tokens staked by the validator himself
function _selfStake(uint256 validatorID) internal view returns (uint256) {
return getDelegation[getValidator[validatorID].auth][validatorID];
}
// _checkDelegatedStakeLimit verifies if the 3rd party delegation does not exceed
// delegation limit defined as a ratio between self stake of the validator
// and sum of delegation.
function _checkDelegatedStakeLimit(uint256 validatorID) internal view returns (bool) {
return getValidator[validatorID].receivedStake <= _selfStake(validatorID).mul(maxDelegatedRatio()).div(Decimal.unit());
}
// _deactivateValidator sets the validator account as withdrawn, if active
// inactive validator accounts can not be deactivated and trying to do so will revert
function _deactivateValidator(uint256 validatorID) internal {
// validator must exist and be active
require(0 == getValidator[validatorID].status & MASK_INACTIVE, "BridgeManager: invalid validator state");
// set withdrawn status
getValidator[validatorID].status = getValidator[validatorID].status | STATUS_WITHDRAWN;
getValidator[validatorID].deactivatedTime = _now();
}
// _notifyValidatorWeightChange notifies a change of the validation power
// of the given validator. Clients listening for this notification can act
// accordingly.
function _notifyValidatorWeightChange(uint256 validatorID) internal {
// check for validator existence
require(_validatorExists(validatorID), "BridgeManager: unknown validator");
// calculate the new weight of the validator; if the validator
// is not available for whatever reason, the new weight will be zero
uint256 weight = getValidator[validatorID].receivedStake;
if (getValidator[toValidatorID].status & MASK_INACTIVE != 0) {
weight = 0;
}
// emit the event for the validator
emit UpdatedValidatorWeight(validatorID, weight);
}
// ------------------------------
// tooling
// ------------------------------
// getTotalStake returns the total amount of staked tokens for the reward
// distribution calculation.
function getStakeTotal() public view returns (uint256) {
return totalStake;
}
// getStakeBy returns the amount of staked tokens of a specific staker/validator combo
// for the reward distribution calculation.
function getStakeBy(address staker, uint256 validatorID) internal returns (uint256) {
return getDelegation[staker][validatorID];
}
// isStakeJailed returns jail status of the given stake.
function isStakeJailed(address staker, uint256 validatorID) public view returns (bool) {
return (getValidator[validatorID].status & STATUS_ERROR != 0);
}
}
| _createValidator builds up the validator structure make sure the validator does not exist yet what will be the new validator id update the validator core record | function _createValidator(address auth) internal {
require(0 == getValidatorID[auth], "BridgeManager: validator already exists");
uint256 validatorID = ++lastValidatorID;
getValidatorID[auth] = validatorID;
getValidator[validatorID].status = STATUS_NEW;
getValidator[validatorID].createdTime = _now();
getValidator[validatorID].auth = auth;
}
| 13,086,646 |
pragma solidity 0.7.0;
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {size := extcodesize(account)}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value : amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value : weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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;
}
}
interface Events {
/**
* Emitted when the washout mechanism has been called.
* Signifies that all tokens have been burned and all further token transfers are blocked, unless the recipient
* is the contract owner.
*/
event Washout();
/**
* Emitted when a new address is appended to the list of addresses in the contract.
*/
event NewAddressAppended(address newAddress);
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract TokenDynAgro is Context, IERC20, Events {
using SafeMath for uint256;
using Address for address;
address contractOwner;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
address[] private _addressList;
mapping(address => bool) private _isOnAddressList;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
bool private _washedOut;
/**
* @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 (uint256 totalSupply_) {
_name = 'DynAgro Benefit Token';
_symbol = 'DAQ';
_decimals = 2;
_washedOut = false;
// set the contract owner
contractOwner = msg.sender;
_totalSupply = totalSupply_;
_balances[msg.sender] = totalSupply_;
}
// When attached to a function, restricts the calls to that function only to the contract owner
modifier onlyOwner {
require(msg.sender == contractOwner, "Only owner can call this function.");
_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* Calls the internal _mint function to generate the given amount of tokens and add them to the total supply.
* The tokens are added to the contract owner's address.
*/
function mint(uint256 amount) public onlyOwner returns (bool){
_mint(contractOwner, amount);
return true;
}
/**
* Sets the global variable _washedOut to true, meaning that all other functions that manage funds will not be
* executing.
* Also, the total supply is set to zero, so transferring tokens from the contract to users cannot happen.
*/
function washout() public onlyOwner returns (bool) {
require(!_washedOut, "Total burn has already been executed");
_totalSupply = 0;
_washedOut = true;
emit Washout();
return true;
}
/**
* Burns a given amount ot tokens from the contract owner's address.
*/
function burn(uint256 amount) public onlyOwner returns (bool) {
_burn(contractOwner, amount);
return true;
}
/**
* The the total count of the addresses in the list of addresses of the contract.
*/
function getAddressCount() public view onlyOwner returns (uint count) {
return _addressList.length;
}
/**
* Get a given address at an index of the list of addresses.
*/
function getAddressAtRow(uint row) public view onlyOwner returns (address theAddress) {
return _addressList[row];
}
/**
* Get the full list of addresses in the contract.
*/
function getAddresses() public view onlyOwner returns (address[] memory) {
return _addressList;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* Checks if the given address is already on the list of addresses, by checking if the address exists in the mapping
* signifying that the address is on the list of addresses.
*/
function _isAddressPresent(address check) internal view returns (bool addressIsPresent) {
return _isOnAddressList[check];
}
/**
* Appends the given address to the list of addresses in the contract, and also to the mapping signifying whether
* the address is on the list.
*/
function _appendAddressToList(address newAddress) internal virtual {
if (!_isAddressPresent(newAddress)) {
_addressList.push(newAddress);
_isOnAddressList[newAddress] = true;
emit NewAddressAppended(newAddress);
}
}
/**
* @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");
if (recipient != contractOwner) {
require(!_washedOut, "All tokes have been burned");
}
_appendAddressToList(recipient);
_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");
_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");
_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);
}
}
| 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 | 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;
}
| 7,418,896 |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.10;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*///////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*///////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
event Debug(bool one, bool two, uint256 retsize);
/*///////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
/*///////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "APPROVE_FAILED");
}
}
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/*///////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
/*///////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// Divide z by the denominator.
z := div(z, denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// First, divide z - 1 by the denominator and add 1.
// We allow z - 1 to underflow if z is 0, because we multiply the
// end result by 0 if z is zero, ensuring we return 0 if z is zero.
z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
}
}
function rpow(
uint256 x,
uint256 n,
uint256 scalar
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := scalar
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store scalar in z for now.
z := scalar
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, scalar)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, scalar)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, scalar)
}
}
}
}
}
/*///////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
assembly {
// Start off with z at 1.
z := 1
// Used below to help find a nearby power of 2.
let y := x
// Find the lowest power of 2 that is at least sqrt(x).
if iszero(lt(y, 0x100000000000000000000000000000000)) {
y := shr(128, y) // Like dividing by 2 ** 128.
z := shl(64, z) // Like multiplying by 2 ** 64.
}
if iszero(lt(y, 0x10000000000000000)) {
y := shr(64, y) // Like dividing by 2 ** 64.
z := shl(32, z) // Like multiplying by 2 ** 32.
}
if iszero(lt(y, 0x100000000)) {
y := shr(32, y) // Like dividing by 2 ** 32.
z := shl(16, z) // Like multiplying by 2 ** 16.
}
if iszero(lt(y, 0x10000)) {
y := shr(16, y) // Like dividing by 2 ** 16.
z := shl(8, z) // Like multiplying by 2 ** 8.
}
if iszero(lt(y, 0x100)) {
y := shr(8, y) // Like dividing by 2 ** 8.
z := shl(4, z) // Like multiplying by 2 ** 4.
}
if iszero(lt(y, 0x10)) {
y := shr(4, y) // Like dividing by 2 ** 4.
z := shl(2, z) // Like multiplying by 2 ** 2.
}
if iszero(lt(y, 0x8)) {
// Equivalent to 2 ** z.
z := shl(1, z)
}
// Shifting right by 1 is like dividing by 2.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// Compute a rounded down version of z.
let zRoundDown := div(x, z)
// If zRoundDown is smaller, use it.
if lt(zRoundDown, z) {
z := zRoundDown
}
}
}
}
/// @notice Minimal ERC4626 tokenized Vault implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/mixins/ERC4626.sol)
abstract contract ERC4626 is ERC20 {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
ERC20 public immutable asset;
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol, _asset.decimals()) {
asset = _asset;
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
//////////////////////////////////////////////////////////////*/
function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {
// Check for rounding error since we round down in previewDeposit.
require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES");
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {
assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function withdraw(
uint256 assets,
address receiver,
address owner
) public virtual returns (uint256 shares) {
shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
function redeem(
uint256 shares,
address receiver,
address owner
) public virtual returns (uint256 assets) {
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
// Check for rounding error since we round down in previewRedeem.
require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS");
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
function totalAssets() public view virtual returns (uint256);
function convertToShares(uint256 assets) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());
}
function convertToAssets(uint256 shares) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
}
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return convertToShares(assets);
}
function previewMint(uint256 shares) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);
}
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());
}
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return convertToAssets(shares);
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LIMIT LOGIC
//////////////////////////////////////////////////////////////*/
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxWithdraw(address owner) public view virtual returns (uint256) {
return convertToAssets(balanceOf[owner]);
}
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf[owner];
}
/*///////////////////////////////////////////////////////////////
INTERNAL HOOKS LOGIC
//////////////////////////////////////////////////////////////*/
function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
function afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}
interface InterestRateModel {
function getBorrowRate(
uint256,
uint256,
uint256
) external view returns (uint256);
function getSupplyRate(
uint256,
uint256,
uint256,
uint256
) external view returns (uint256);
}
abstract contract CERC20 is ERC20 {
function mint(uint256) external virtual returns (uint256);
function borrow(uint256) external virtual returns (uint256);
function underlying() external view virtual returns (ERC20);
function totalBorrows() external view virtual returns (uint256);
function totalFuseFees() external view virtual returns (uint256);
function repayBorrow(uint256) external virtual returns (uint256);
function totalReserves() external view virtual returns (uint256);
function exchangeRateCurrent() external virtual returns (uint256);
function totalAdminFees() external view virtual returns (uint256);
function fuseFeeMantissa() external view virtual returns (uint256);
function adminFeeMantissa() external view virtual returns (uint256);
function exchangeRateStored() external view virtual returns (uint256);
function accrualBlockNumber() external view virtual returns (uint256);
function redeemUnderlying(uint256) external virtual returns (uint256);
function balanceOfUnderlying(address) external virtual returns (uint256);
function reserveFactorMantissa() external view virtual returns (uint256);
function borrowBalanceCurrent(address) external virtual returns (uint256);
function interestRateModel() external view virtual returns (InterestRateModel);
function initialExchangeRateMantissa() external view virtual returns (uint256);
function repayBorrowBehalf(address, uint256) external virtual returns (uint256);
}
/// @notice Get up to date cToken data without mutating state.
/// @author Transmissions11 (https://github.com/transmissions11/libcompound)
library LibFuse {
using FixedPointMathLib for uint256;
function viewUnderlyingBalanceOf(CERC20 cToken, address user) internal view returns (uint256) {
return cToken.balanceOf(user).mulWadDown(viewExchangeRate(cToken));
}
function viewExchangeRate(CERC20 cToken) internal view returns (uint256) {
uint256 accrualBlockNumberPrior = cToken.accrualBlockNumber();
if (accrualBlockNumberPrior == block.number) return cToken.exchangeRateStored();
uint256 totalCash = cToken.underlying().balanceOf(address(cToken));
uint256 borrowsPrior = cToken.totalBorrows();
uint256 reservesPrior = cToken.totalReserves();
uint256 adminFeesPrior = cToken.totalAdminFees();
uint256 fuseFeesPrior = cToken.totalFuseFees();
uint256 interestAccumulated; // Generated in new scope to avoid stack too deep.
{
uint256 borrowRateMantissa = cToken.interestRateModel().getBorrowRate(
totalCash,
borrowsPrior,
reservesPrior + adminFeesPrior + fuseFeesPrior
);
// Same as borrowRateMaxMantissa in CTokenInterfaces.sol
require(borrowRateMantissa <= 0.0005e16, "RATE_TOO_HIGH");
interestAccumulated = (borrowRateMantissa * (block.number - accrualBlockNumberPrior)).mulWadDown(
borrowsPrior
);
}
uint256 totalReserves = cToken.reserveFactorMantissa().mulWadDown(interestAccumulated) + reservesPrior;
uint256 totalAdminFees = cToken.adminFeeMantissa().mulWadDown(interestAccumulated) + adminFeesPrior;
uint256 totalFuseFees = cToken.fuseFeeMantissa().mulWadDown(interestAccumulated) + fuseFeesPrior;
uint256 totalSupply = cToken.totalSupply();
return
totalSupply == 0
? cToken.initialExchangeRateMantissa()
: (totalCash + (interestAccumulated + borrowsPrior) - (totalReserves + totalAdminFees + totalFuseFees))
.divWadDown(totalSupply);
}
}
abstract contract CToken is CERC20 {
function comptroller() external view virtual returns (address);
function getCash() external view virtual returns (uint256);
}
abstract contract Unitroller {
struct Market {
bool isListed;
uint256 collateralFactorMantissa;
mapping(address => bool) accountMembership;
}
address public admin;
address public borrowCapGuardian;
address public pauseGuardian;
address public oracle;
address public pendingAdmin;
uint256 public closeFactorMantissa;
uint256 public liquidationIncentiveMantissa;
mapping(address => Market) public markets;
mapping(address => address) public cTokensByUnderlying;
mapping(address => uint256) public supplyCaps;
function _setPendingAdmin(address newPendingAdmin)
public
virtual
returns (uint256);
function _setBorrowCapGuardian(address newBorrowCapGuardian) public virtual;
function _setMarketSupplyCaps(
CERC20[] calldata cTokens,
uint256[] calldata newSupplyCaps
) external virtual;
function _setMarketBorrowCaps(
CERC20[] calldata cTokens,
uint256[] calldata newBorrowCaps
) external virtual;
function _setPauseGuardian(address newPauseGuardian)
public
virtual
returns (uint256);
function _setMintPaused(CERC20 cToken, bool state)
public
virtual
returns (bool);
function _setBorrowPaused(CERC20 cToken, bool borrowPaused)
public
virtual
returns (bool);
function _setTransferPaused(bool state) public virtual returns (bool);
function _setSeizePaused(bool state) public virtual returns (bool);
function _setPriceOracle(address newOracle)
external
virtual
returns (uint256);
function _setCloseFactor(uint256 newCloseFactorMantissa)
external
virtual
returns (uint256);
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external
virtual
returns (uint256);
function _setCollateralFactor(
CERC20 cToken,
uint256 newCollateralFactorMantissa
) public virtual returns (uint256);
function _acceptAdmin() external virtual returns (uint256);
function _deployMarket(
bool isCEther,
bytes calldata constructionData,
uint256 collateralFactorMantissa
) external virtual returns (uint256);
function mintGuardianPaused(address cToken)
external
view
virtual
returns (bool);
function borrowGuardianPaused(address cToken)
external
view
virtual
returns (bool);
function comptrollerImplementation()
external
view
virtual
returns (address);
function rewardsDistributors(uint256 index)
external
view
virtual
returns (address);
function _addRewardsDistributor(address distributor)
external
virtual
returns (uint256);
function _setWhitelistEnforcement(bool enforce)
external
virtual
returns (uint256);
function _setWhitelistStatuses(
address[] calldata suppliers,
bool[] calldata statuses
) external virtual returns (uint256);
function _unsupportMarket(CERC20 cToken) external virtual returns (uint256);
function _toggleAutoImplementations(bool enabled)
public
virtual
returns (uint256);
}
contract FuseERC4626 is ERC4626 {
using FixedPointMathLib for uint256;
using SafeTransferLib for ERC20;
using LibFuse for CToken;
/// @notice CToken token reference
CToken public immutable cToken;
/// @notice reference to the Unitroller of the CToken token
Unitroller public immutable unitroller;
/// @notice The address of the underlying ERC20 token used for
/// the Vault for accounting, depositing, and withdrawing.
ERC20 public immutable cTokenUnderlying;
/// @notice CompoundERC4626 constructor
/// @param _cToken Compound cToken to wrap
/// @param name ERC20 name of the vault shares token
/// @param symbol ERC20 symbol of the vault shares token
constructor(
address _cToken,
string memory name,
string memory symbol
) ERC4626(ERC20(CToken(_cToken).underlying()), name, symbol) {
cToken = CToken(_cToken);
unitroller = Unitroller(cToken.comptroller());
cTokenUnderlying = ERC20(CToken(cToken).underlying());
}
function beforeWithdraw(uint256 underlyingAmount, uint256)
internal
override
{
// Withdraw the underlying tokens from the cToken.
require(
cToken.redeemUnderlying(underlyingAmount) == 0,
"REDEEM_FAILED"
);
}
function afterDeposit(uint256 underlyingAmount, uint256) internal override {
// Approve the underlying tokens to the cToken
asset.safeApprove(address(cToken), underlyingAmount);
// mint tokens
require(cToken.mint(underlyingAmount) == 0, "MINT_FAILED");
}
/// @notice Total amount of the underlying asset that
/// is "managed" by Vault.
function totalAssets() public view override returns (uint256) {
// Use libfuse to determine an accurate view exchange rate.
// this use Fuse cToken functions that do not exist in Compound implementations:
// - cToken.totalAdminFees()
// - cToken.totalFuseFees()
// - cToken.adminFeeMantissa()
return cToken.viewUnderlyingBalanceOf(address(this));
}
/// @notice maximum amount of assets that can be deposited.
/// This is capped by the amount of assets the cToken can be
/// supplied with.
/// This is 0 if minting is paused on the cToken.
function maxDeposit(address) public view override returns (uint256) {
address cTokenAddress = address(cToken);
if (unitroller.mintGuardianPaused(cTokenAddress)) return 0;
uint256 supplyCap = unitroller.supplyCaps(cTokenAddress);
if (supplyCap == 0) return type(uint256).max;
uint256 assetsDeposited = cToken.totalSupply().mulWadDown(
cToken.viewExchangeRate()
);
return supplyCap - assetsDeposited;
}
/// @notice maximum amount of shares that can be minted.
/// This is capped by the amount of assets the cToken can be
/// supplied with.
/// This is 0 if minting is paused on the cToken.
function maxMint(address) public view override returns (uint256) {
address cTokenAddress = address(cToken);
if (unitroller.mintGuardianPaused(cTokenAddress)) return 0;
uint256 supplyCap = unitroller.supplyCaps(cTokenAddress);
if (supplyCap == 0) return type(uint256).max;
uint256 assetsDeposited = cToken.totalSupply().mulWadDown(
cToken.viewExchangeRate()
);
return convertToShares(supplyCap - assetsDeposited);
}
/// @notice Maximum amount of assets that can be withdrawn.
/// This is capped by the amount of cash available on the cToken,
/// if all assets are borrowed, a user can't withdraw from the vault.
function maxWithdraw(address owner) public view override returns (uint256) {
uint256 cash = cToken.getCash();
uint256 assetsBalance = convertToAssets(balanceOf[owner]);
return cash < assetsBalance ? cash : assetsBalance;
}
/// @notice Maximum amount of shares that can be redeemed.
/// This is capped by the amount of cash available on the cToken,
/// if all assets are borrowed, a user can't redeem from the vault.
function maxRedeem(address owner) public view override returns (uint256) {
uint256 cash = cToken.getCash();
uint256 cashInShares = convertToShares(cash);
uint256 shareBalance = balanceOf[owner];
return cashInShares < shareBalance ? cashInShares : shareBalance;
}
} | Start off with z at 1. Used below to help find a nearby power of 2. Find the lowest power of 2 that is at least sqrt(x). Equivalent to 2 z. If zRoundDown is smaller, use it. | function sqrt(uint256 x) internal pure returns (uint256 z) {
assembly {
z := 1
let y := x
if iszero(lt(y, 0x100000000000000000000000000000000)) {
}
if iszero(lt(y, 0x10000000000000000)) {
}
if iszero(lt(y, 0x100000000)) {
}
if iszero(lt(y, 0x10000)) {
}
if iszero(lt(y, 0x100)) {
}
if iszero(lt(y, 0x10)) {
}
if iszero(lt(y, 0x8)) {
z := shl(1, z)
}
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
if lt(zRoundDown, z) {
z := zRoundDown
}
}
}
| 128,544 |
pragma solidity ^0.5.16;
/**
* @dev Allow tokens to be transferred to contracts and have the contract trigger logic for how to respond to receiving the tokens within a single transaction.
* https://github.com/ethereum/EIPs/issues/677
*/
interface Callable {
function tokenCallback(address _from, uint256 _tokens, bytes calldata _data) external returns (bool);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
/**
* @dev 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;
}
}
/**
* @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);
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
// silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {codehash := extcodehash(account)}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success,) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// 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) external view 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 {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping(uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping(address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/*
* 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This is an internal detail of the `ERC721` contract and its use is deprecated.
* @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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/*
* bytes4(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 Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 = _ownedTokens[from].length.sub(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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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.sub(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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* 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;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
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}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*
* _Available since v2.5.0._
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Full ERC721 Token
* @dev This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology.
*
* See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) {
// solhint-disable-previous-line no-empty-blocks
}
}
contract BonkNftMinter is ERC721Full, Ownable, Callable {
using SafeMath for uint256;
// Mapping from token ID to the creator's address.
mapping(uint256 => address) private tokenCreators;
// Counter for creating token IDs
uint256 private idCounter;
// BONK ERC20 token
IERC20 public bonkToken;
// Where to send collected fees
address public feeCollector;
// BONK fee amount with decimals, for example, 1*10**18 means one BONK
uint256 public bonkFee;
// Event indicating metadata was updated.
event TokenURIUpdated(uint256 indexed _tokenId, string _uri);
// Event indicating bonk fee was updated.
event BonkFeeUpdated(uint256 _newFee, uint _timestamp);
constructor(
string memory _name,
string memory _symbol,
address _bonkToken,
address _feeCollector,
uint256 _bonkFee
)
public
ERC721Full(_name, _symbol)
{
bonkToken = IERC20(_bonkToken);
feeCollector = _feeCollector;
bonkFee = _bonkFee;
}
/**
* @dev Checks that the token is owned by the sender.
* @param _tokenId uint256 ID of the token.
*/
modifier onlyTokenOwner(uint256 _tokenId) {
address owner = ownerOf(_tokenId);
require(owner == msg.sender, "must be the owner of the token");
_;
}
/**
* @dev Checks that the caller is BONK token.
*/
modifier onlyBonkToken() {
require(msg.sender == address(bonkToken), "must be BONK token");
_;
}
/**
* @dev callback function that is called by BONK token. Adds new NFT token. Trusted.
* @param _from who sent the tokens.
* @param _tokens how many tokens were sent.
* @param _data extra call data.
* @return success.
*/
function tokenCallback(address _from, uint256 _tokens, bytes calldata _data)
external
onlyBonkToken
returns (bool) {
if (bonkFee > 0) {
uint256 tokensWithTransferFee = _tokens * 100 / 99; // there is 1% fee upon some transfers of BONK
require(tokensWithTransferFee >= bonkFee, "not enough tokens");
_forwardBonkTokens();
}
_createToken(string(_data), _from);
return true;
}
/**
* @dev Adds a new unique token to the supply.
* @param _uri string metadata uri associated with the token.
*/
function addNewToken(string calldata _uri) external {
if (bonkFee > 0) {
require(bonkToken.transferFrom(msg.sender, address(this), bonkFee), "fee transferFrom failed");
_forwardBonkTokens();
}
_createToken(_uri, msg.sender);
}
/**
* @dev Deletes the token with the provided ID.
* @param _tokenId uint256 ID of the token.
*/
function deleteToken(uint256 _tokenId) external onlyTokenOwner(_tokenId) {
_burn(msg.sender, _tokenId);
}
/**
* @dev Allows owner of the contract updating the token metadata in case there is a need.
* @param _tokenId uint256 ID of the token.
* @param _uri string metadata URI.
*/
function updateTokenMetadata(uint256 _tokenId, string calldata _uri) external onlyOwner {
_setTokenURI(_tokenId, _uri);
emit TokenURIUpdated(_tokenId, _uri);
}
/**
* @dev change address of BONK token
* @param _bonkToken address of ERC20 contract
*/
function setBonkToken(address _bonkToken) external onlyOwner {
bonkToken = IERC20(_bonkToken);
}
/**
* @dev change address of where collected fees are sent
* @param _feeCollector address where to send the fees
*/
function setFeeCollector(address _feeCollector) external onlyOwner {
feeCollector = _feeCollector;
}
/**
* @dev change BONK fee
* @param _bonkFee new fee in BONK (with decimals)
*/
function setBonkFee(uint _bonkFee) external onlyOwner {
bonkFee = _bonkFee;
emit BonkFeeUpdated(_bonkFee, now);
}
/**
* @dev allows withdrawal of ETH in case it was sent by accident
* @param _beneficiary address where to send the eth.
*/
function withdrawEth(address payable _beneficiary) external onlyOwner {
_beneficiary.transfer(address(this).balance);
}
/**
* @dev allows withdrawal of ERC20 token in case it was sent by accident
* @param _tokenAddress address of ERC20 token.
* @param _beneficiary address where to send the tokens.
* @param _amount amount to send.
*/
function withdrawERC20(address _tokenAddress, address _beneficiary, uint _amount) external onlyOwner {
IERC20(_tokenAddress).transfer(_beneficiary, _amount);
}
/**
* @dev Gets the current fee in BONK.
* @return BONK fee.
*/
function getBonkFee() public view returns (uint256) {
return bonkFee;
}
/**
* @dev Gets the creator of the token.
* @param _tokenId uint256 ID of the token.
* @return address of the creator.
*/
function tokenCreator(uint256 _tokenId) public view returns (address) {
return tokenCreators[_tokenId];
}
/**
* @dev Internal function for setting the token's creator.
* @param _tokenId uint256 id of the token.
* @param _creator address of the creator of the token.
*/
function _setTokenCreator(uint256 _tokenId, address _creator) internal {
tokenCreators[_tokenId] = _creator;
}
/**
* @dev Internal function creating a new token.
* @param _uri string metadata uri associated with the token
* @param _creator address of the creator of the token.
*/
function _createToken(string memory _uri, address _creator) internal returns (uint256) {
uint256 newId = idCounter;
idCounter++;
_mint(_creator, newId);
_setTokenURI(newId, _uri);
_setTokenCreator(newId, _creator);
return newId;
}
/**
* @dev Internal function for forwarding collected fees to the fee collector.
*/
function _forwardBonkTokens() internal {
uint balance = IERC20(bonkToken).balanceOf(address(this));
require(IERC20(bonkToken).transfer(feeCollector, balance), "fee transfer failed");
}
} | Internal function to safely mint a new token. Reverts if the given token ID already exists. If the target address is a contract, it must implement `onERC721Received`, which is called upon a safe transfer, and return the magic value `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, the transfer is reverted. to The address that will own the minted token tokenId uint256 ID of the token to be minted _data bytes data to send along with a safe transfer check/ | function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
| 14,330,529 |
./full_match/43113/0x296c347E6C41eb68E14Bf78a6A61a2da3139003e/sources/utils/Ownable.sol | Nominate new Owner of the contract to a new account (`newOwner`). Can only be called by the current owner./ | function nominateNewOwner(address newOwner) external onlyOwner {
_nominatedOwner = newOwner;
emit OwnershipNominated(_owner,newOwner);
}
| 13,163,394 |
./partial_match/80001/0x0b85324695860E65308fbC0f165e0404e8d3b05A/sources/contracts/VoteChain.sol | Vote for a Proposal | function voteToProposal(
bytes32 proposalId,
bool vote
) external nonReentrant {
uint256 totalProposedAmount = getProposedAmountByProposalId(proposalId);
uint256 balanceInCategory = donationAmountByCategory[
proposalCategories[proposalId]
];
require(
balanceInCategory > totalProposedAmount,
"VoteToProposal:: Insufficiant Funds in the Category"
);
require(isDonor(msg.sender), "VoteToProposal:: Only donors can vote");
if (vote) {
upVoteCountForProposal[proposalId]++;
downVoteCountForProposal[proposalId]++;
}
IVoteChainNFT(voterNFT).mint(msg.sender);
emit Voted(proposalId, msg.sender, block.timestamp);
}
| 8,811,257 |
./full_match/80001/0x498F649C3A36E2799d18541E4a057E76B847D73d/sources/contracts/GenesisAvatar.sol | Manage information about the Family Badge | function updateFamilyBadgeTokenInfo(address _newTokenAddress, uint256 newTokenId) external onlyRole(MANAGER_ROLE) {
familyBadgeTokenAddress = _newTokenAddress;
familyBadgeTokenId = newTokenId;
}
| 9,445,855 |
./full_match/1/0x7921613d694Da3e035FaE9a227cE61d1127a1D18/sources/coin12.sol | private function to swap tax to eth tokenAmount: token amount to swap for eth generate the uniswap pair path of token -> weth | function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
if(allowance(address(this), address(uniswapV2Router)) < tokenAmount){
_approve(address(this), address(uniswapV2Router), type(uint256).max);
}
tokenAmount,
path,
feeWallet,
block.timestamp
);
}
| 3,160,618 |
./partial_match/1/0x32d94d714F0F69Aca4f09bA6Ae49993DD8fA63C5/sources/PeeriumToken.sol | Removes a token from the approved list. _token The address of the token to be disapproved. return A boolean indicating whether the operation was successful or not./ | function disapproveToken(address _token) external onlyAdmin returns (bool) {
require(approvedTokens[address(this)][_token], "Token is not approved");
approvedTokens[address(this)][_token] = false;
emit TokenDisapproved(_token);
return true;
}
| 2,665,115 |
pragma solidity >=0.8.9 <0.9.0;
//SPDX-License-Identifier: MIT
import "../node_modules/@openzeppelin/contracts/interfaces/IERC20Metadata.sol";
import "../node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../node_modules/@openzeppelin/contracts/access/Ownable.sol";
import "./ISwapper.sol";
import "./XToken.sol";
/*
Hello and welcome to the ShibaBurn burning portal.
This is a contract that empowers developers to
create incentive based deflation for all ERC20 tokens!
ShibaBurn allows for an infinite number of burn pools
to be created for any given token. By default, burn pools track the following data:
- total tokens burnt by each user
- total tokens burnt by all users
ShibaBurn also allows for ETH to be "zapped" into burn pool ownershib by means of
buying the specified token on ShibaSwap, and burning it in one transaction. This
is only possible if eth-token liquidity is present on ShibaSwap.com
If configured by the ShibaBurn owner wallet, burn pools can optionally:
- Mint xTokens for users (e.g. burntSHIB in the case of burning SHIB to the default pool)
- Keep track of the index at which any given address exceeds a burnt amount beyond an admin specified threshold
_____ _____ _____ _____ _____
/\ \ /\ \ /\ \ /\ \ /\ \
/::\ \ /::\____\ /::\ \ /::\ \ /::\ \
/::::\ \ /:::/ / \:::\ \ /::::\ \ /::::\ \
/::::::\ \ /:::/ / \:::\ \ /::::::\ \ /::::::\ \
/:::/\:::\ \ /:::/ / \:::\ \ /:::/\:::\ \ /:::/\:::\ \
/:::/__\:::\ \ /:::/____/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \
\:::\ \:::\ \ /::::\ \ /::::\ \ /::::\ \:::\ \ /::::\ \:::\ \
___\:::\ \:::\ \ /::::::\ \ _____ ____ /::::::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \
/\ \:::\ \:::\ \ /:::/\:::\ \ /\ \ /\ \ /:::/\:::\ \ /:::/\:::\ \:::\ ___\ /:::/\:::\ \:::\ \
/::\ \:::\ \:::\____\/:::/ \:::\ /::\____\/::\ \/:::/ \:::\____\/:::/__\:::\ \:::| |/:::/ \:::\ \:::\____\
\:::\ \:::\ \::/ /\::/ \:::\ /:::/ /\:::\ /:::/ \::/ /\:::\ \:::\ /:::|____|\::/ \:::\ /:::/ /
\:::\ \:::\ \/____/ \/____/ \:::\/:::/ / \:::\/:::/ / \/____/ \:::\ \:::\/:::/ / \/____/ \:::\/:::/ /
\:::\ \:::\ \ \::::::/ / \::::::/ / \:::\ \::::::/ / \::::::/ /
\:::\ \:::\____\ \::::/ / \::::/____/ \:::\ \::::/ / \::::/ /
\:::\ /:::/ / /:::/ / \:::\ \ \:::\ /:::/ / /:::/ /
\:::\/:::/ / /:::/ / \:::\ \ \:::\/:::/ / /:::/ /
\::::::/ / /:::/ / \:::\ \ \::::::/ / /:::/ /
\::::/ / /:::/ / \:::\____\ \::::/ / /:::/ /
\::/ / \::/ / \::/ / \::/____/ \::/ /
\/____/ \/____/ \/____/ ~~ \/____/
_____ _____ _____ _____
/\ \ /\ \ /\ \ /\ \
/::\ \ /::\____\ /::\ \ /::\____\
/::::\ \ /:::/ / /::::\ \ /::::| |
/::::::\ \ /:::/ / /::::::\ \ /:::::| |
/:::/\:::\ \ /:::/ / /:::/\:::\ \ /::::::| |
/:::/__\:::\ \ /:::/ / /:::/__\:::\ \ /:::/|::| |
/::::\ \:::\ \ /:::/ / /::::\ \:::\ \ /:::/ |::| |
/::::::\ \:::\ \ /:::/ / _____ /::::::\ \:::\ \ /:::/ |::| | _____
/:::/\:::\ \:::\ ___\ /:::/____/ /\ \ /:::/\:::\ \:::\____\ /:::/ |::| |/\ \
/:::/__\:::\ \:::| ||:::| / /::\____\/:::/ \:::\ \:::| |/:: / |::| /::\____\
\:::\ \:::\ /:::|____||:::|____\ /:::/ /\::/ |::::\ /:::|____|\::/ /|::| /:::/ /
\:::\ \:::\/:::/ / \:::\ \ /:::/ / \/____|:::::\/:::/ / \/____/ |::| /:::/ /
\:::\ \::::::/ / \:::\ \ /:::/ / |:::::::::/ / |::|/:::/ /
\:::\ \::::/ / \:::\ /:::/ / |::|\::::/ / |::::::/ /
\:::\ /:::/ / \:::\__/:::/ / |::| \::/____/ |:::::/ /
\:::\/:::/ / \::::::::/ / |::| ~| |::::/ /
\::::::/ / \::::::/ / |::| | /:::/ /
\::::/ / \::::/ / \::| | /:::/ /
\::/____/ \::/____/ \:| | \::/ /
~~ ~~ \|___| \/____/
*/
contract ShibaBurn is Ownable {
// ShibaSwap router:
ISwapper public router = ISwapper(0x03f7724180AA6b939894B5Ca4314783B0b36b329);
// Ledgendary burn address that holds tokens burnt of the SHIB ecosystem:
address public burnAddress = 0xdEAD000000000000000042069420694206942069;
address public wethAddress;
// Addresses of SHIB ecosystem tokens:
address public shibAddress = 0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE;
address public boneAddress = 0x9813037ee2218799597d83D4a5B6F3b6778218d9;
address public leashAddress = 0x27C70Cd1946795B66be9d954418546998b546634;
address public ryoshiAddress = 0x777E2ae845272a2F540ebf6a3D03734A5a8f618e;
event Burn(address sender, uint256 time, address tokenAddress, uint256 poolIndex, uint256 amount);
bool locked;
modifier noReentrancy() {
require(!locked,"Reentrant call");
locked = true;
_;
locked = false;
}
//////////////
// BURN POOLS:
//////////////
//
// xTokens[tokenAddress][poolIndex]
// => address of pool's xToken
mapping(address => mapping(uint256 => address)) public xTokens;
// totalBurnt[tokenAddress][poolIndex]
// => total amount burnt for specified pool
mapping(address => mapping(uint256 => uint256)) public totalBurnt;
// totalTrackedBurners[tokenAddress][poolIndex]
// => total number of burners that have exceeded the trackBurnerIndexThreshold
mapping(address => mapping(uint256 => uint256)) public totalTrackedBurners;
// trackBurnerIndexThreshold[tokenAddress][poolIndex]
// => the burn threshold required to track user burn indexes of a specific pool
mapping(address => mapping(uint256 => uint256)) public trackBurnerIndexThreshold;
// burnerIndex[tokenAddress][poolIndex][userAddress]
// => the index at which a user exceeded the trackBurnerIndexThreshold for a specific pool
mapping(address => mapping(uint256 => mapping(address => uint256))) public burnerIndex;
// burnerIndex[tokenAddress][poolIndex][burnerIndex]
// => the address of the a specified tracked burner at a specified index
mapping(address => mapping(uint256 => mapping(uint256 => address))) public burnersByIndex;
// amountBurnt[tokenAddress][poolIndex][userAddress]
// => amount burnt by a specific user for a specified pool
mapping(address => mapping(uint256 => mapping(address => uint256))) public amountBurnt;
constructor(address _wethAddress) Ownable() {
wethAddress = _wethAddress;
}
/**
* @notice Intended to be used for web3 interface, such that all data can be pulled at once
* @param tokenAddress The address of the token for which the query will be made
* @param currentUser The address used to query user-based pool info and ethereum balance
* @return burnPool info for the default pool (0) of the specified token
*/
function getInfo(address currentUser, address tokenAddress) external view returns (uint256[] memory) {
return getInfoForPool(0, currentUser, tokenAddress);
}
/**
* @notice Intended to be used for web3 interface, such that all data can be pulled at once
* @param poolIndex The index of which token-specific burn pool to be used
* @param tokenAddress The address of the token for which the query will be made
* @param currentUser The address used to query user-based pool info and ethereum balance
*
* @return burnPool info for the specified pool of the specified token as an array of 11 integers indicating the following:
* (0) Number of decimals of the token associated with the tokenAddress
* (1) Total amount burnt for the specified burn-pool
* (2) Total amount burnt by the specified currentUser for the specified burn-pool
* (3) The amount of specified tokens in possession by the specified currentUser
* (4) The amount of eth in the wallet of the specified currentUser
* (5) The amount of specified tokens allowed to be burnt by this contract
* (6) The threshold of tokens needed to be burnt to track the index of a user for the specified pool (if zero, no indexes will be tracked)
* (7) Burn index of the current user with regards to a specified pool (only tracked if admin configured, and burn meets threshold requirements)
* (8) Total number of burners above the specified threshold for the specific pool
* (9) Decimal integer representation of the address of the 'xToken' of the specified pool
* (10) Total supply of the xToken associated with the specified pool
* (11) Specified pool's xToken balance of currentUser
*/
function getInfoForPool(uint256 poolIndex, address currentUser, address tokenAddress) public view returns (uint256[] memory) {
uint256[] memory info = new uint256[](12);
IERC20Metadata token = IERC20Metadata(tokenAddress);
info[0] = token.decimals();
info[1] = totalBurnt[tokenAddress][poolIndex];
info[2] = amountBurnt[tokenAddress][poolIndex][currentUser];
info[3] = token.balanceOf(currentUser);
info[4] = currentUser.balance;
info[5] = token.allowance(currentUser, address(this));
if (trackBurnerIndexThreshold[tokenAddress][poolIndex] != 0) {
info[6] = trackBurnerIndexThreshold[tokenAddress][poolIndex];
info[7] = burnerIndex[tokenAddress][poolIndex][currentUser];
info[8] = totalTrackedBurners[tokenAddress][poolIndex];
}
if (xTokens[tokenAddress][poolIndex] != address(0)) {
IERC20Metadata xToken = IERC20Metadata(xTokens[tokenAddress][poolIndex]);
info[9] = uint256(uint160(address(xToken)));
info[10] = xToken.totalSupply();
info[11] = xToken.balanceOf(currentUser);
}
return info;
}
/**
* @notice Intended to be used for web3 such that all necessary data can be requested at once
* @param tokenAddress The address of the token to buy on shibaswap.
* @return Name and Symbol metadata of specified ERC20 token.
*/
function getTokenInfo(address tokenAddress) external view returns (string[] memory) {
string[] memory info = new string[](2);
IERC20Metadata token = IERC20Metadata(tokenAddress);
info[0] = token.name();
info[1] = token.symbol();
return info;
}
/**
* @param tokenAddress The address of the token to buy on shibaswap.
* @param minOut specifies the minimum number of tokens to be burnt when buying (to prevent front-runner attacks)
*
* @notice Allows users to buy tokens (with ETH on ShibaSwap) and burn them in 1 tx for the
* "default" burn pool for the specified token. Based on the admin configuration of each pool,
* xTokens may be issued, and/or the burner's index will be tracked.
*/
function buyAndBurn(address tokenAddress, uint256 minOut) external payable {
buyAndBurnForPool(tokenAddress, minOut, 0);
}
/**
* @param tokenAddress The address of the token intended to be burnt.
* @param poolIndex the index of which token-specific burn pool to be used
* @param threshold the minimum amount of tokens required to be burnt for the burner's index to be tracked
*
* @dev This can only be set on pools with no burns
* @notice Allows the admin address to mark a specific pool as tracking "indexes" of burns above a specific threshold.
* This allows for projects to reward users based on how early they burned more than the specified amount.
* Setting this threshold will cause each burn to require more gas.
*/
function trackIndexesForPool(address tokenAddress, uint256 poolIndex, uint256 threshold) public onlyOwner {
require (totalBurnt[tokenAddress][poolIndex] == 0, "tracking indexes can only be turned on for pools with no burns");
trackBurnerIndexThreshold[tokenAddress][poolIndex] = threshold;
}
/**
* @param tokenAddress The address of the token intended to be burnt.
* @param poolIndex the index of which token-specific burn pool to be used
* @param xTokenAddress the address of the xToken that will be minted in exchange for burning
*
* @notice Allows the admin address to set an xToken address for a specific pool.
* @dev It is required for this contract to have permission to mint the xToken
*/
function setXTokenForPool(address tokenAddress, uint256 poolIndex, address xTokenAddress) public onlyOwner {
require (totalBurnt[tokenAddress][poolIndex] == 0, "xToken can only be set on pools with no burns");
xTokens[tokenAddress][poolIndex] = xTokenAddress;
}
/**
* @notice Allows users to buy tokens (with ETH on ShibaSwap) and burn them in 1 tx.
* Based on the admin configuration of each pool, xTokens may be issued,
* and the burner's index will be tracked.
*
* @dev uses hard coded shibaswap router address
*
* @param tokenAddress The address of the token to buy on shibaswap.
* @param minOut specifies the minimum number of tokens to be burnt when buying (to prevent front-runner attacks)
* @param poolIndex the index of which token-specific burn pool to be used
*
*/
function buyAndBurnForPool(address tokenAddress, uint256 minOut, uint256 poolIndex) public payable noReentrancy {
address[] memory ethPath = new address[](2);
ethPath[0] = wethAddress; // WETH
ethPath[1] = tokenAddress;
IERC20Metadata token = IERC20Metadata(tokenAddress);
uint256 balanceWas = token.balanceOf(burnAddress);
router.swapExactETHForTokens{ value: msg.value }(minOut, ethPath, burnAddress, block.timestamp + 1000);
uint256 amount = token.balanceOf(burnAddress) - balanceWas;
_increaseOwnership(tokenAddress, poolIndex, amount);
}
/**
* @dev internal method
* @param tokenAddress The address of the token intended to be burnt.
* @param poolIndex the index of which token-specific burn pool to be used
* @param amount the amount of tokens intended to be burnt
*
* @return boolean value which indicates whether or not the burner's burn index should be tracked for the current transaction.
*/
function shouldTrackIndex(address tokenAddress, uint256 poolIndex, uint256 amount) internal returns (bool) {
uint256 threshold = trackBurnerIndexThreshold[tokenAddress][poolIndex];
uint256 alreadyBurnt = amountBurnt[tokenAddress][poolIndex][msg.sender];
return threshold != 0 &&
alreadyBurnt < threshold &&
alreadyBurnt + amount >= threshold;
}
/**
* @notice increases ownership of specified pool.
* @dev tracks the user's burn Index if configured
* @dev mints xTokens for the user if configured
* @dev internal method
* @param tokenAddress The address of the token intended to be burnt.
* @param poolIndex the index of which token-specific burn pool to be used
* @param amount of tokens intended to be burnt
*
*/
function _increaseOwnership(address tokenAddress, uint256 poolIndex, uint256 amount) internal {
if (shouldTrackIndex(tokenAddress, poolIndex, amount)) {
burnerIndex[tokenAddress][poolIndex][msg.sender] = totalTrackedBurners[tokenAddress][poolIndex];
burnersByIndex[tokenAddress][poolIndex][totalTrackedBurners[tokenAddress][poolIndex]] = msg.sender;
totalTrackedBurners[tokenAddress][poolIndex] += 1;
}
if (xTokens[tokenAddress][poolIndex] != address(0))
XToken(xTokens[tokenAddress][poolIndex]).mint(msg.sender, amount);
amountBurnt[tokenAddress][poolIndex][msg.sender] = amountBurnt[tokenAddress][poolIndex][msg.sender] + amount;
totalBurnt[tokenAddress][poolIndex] += amount;
emit Burn(msg.sender, block.timestamp, tokenAddress, poolIndex, amount);
}
/**
* @notice Burns SHIB to the default SHIB pool
* @param amount the amount of SHIB to be burnt
*/
function burnShib(uint256 amount) external {
burnToken(shibAddress, amount);
}
/**
* @notice Burns RYOSHI to the default RYOSHI pool
* @param amount the amount of RYOSHI to be burnt
*/
function burnRyoshi(uint256 amount) external {
burnToken(ryoshiAddress, amount);
}
/**
* @notice Burns LEASH to the default LEASH pool
* @param amount the amount of LEASH to be burnt
*
*/
function burnLeash(uint256 amount) external {
burnToken(leashAddress, amount);
}
/**
* @notice Burns BONE to the default BONE pool
* @param amount the amount of BONE to be burnt
*
*/
function burnBone(uint256 amount) external {
burnToken(boneAddress, amount);
}
/**
* @notice Burns any token to the default (0) pool for that token
* @param tokenAddress the address of the token intended to be burnt
* @param amount the amount of tokens to be burnt
*
*/
function burnToken(address tokenAddress, uint256 amount) public {
burnTokenForPool(tokenAddress, 0, amount);
}
/**
* @notice Burns any token to the specified pool for that token
* @param tokenAddress the address of the token intended to be burnt
* @param poolIndex the index of which token-specific burn pool to be used
* @param amount the amount of tokens to be burnt
*
*/
function burnTokenForPool(address tokenAddress, uint256 poolIndex, uint256 amount) public noReentrancy {
IERC20Metadata token = IERC20Metadata(tokenAddress);
require (token.balanceOf(msg.sender) >= amount, "insufficient token balance");
token.transferFrom(msg.sender, burnAddress, amount);
_increaseOwnership(tokenAddress, poolIndex, amount);
}
}
| Intended to be used for web3 interface, such that all data can be pulled at once poolIndex The index of which token-specific burn pool to be used tokenAddress The address of the token for which the query will be made currentUser The address used to query user-based pool info and ethereum balance return burnPool info for the specified pool of the specified token as an array of 11 integers indicating the following: (0) Number of decimals of the token associated with the tokenAddress (1) Total amount burnt for the specified burn-pool (2) Total amount burnt by the specified currentUser for the specified burn-pool (3) The amount of specified tokens in possession by the specified currentUser (4) The amount of eth in the wallet of the specified currentUser (5) The amount of specified tokens allowed to be burnt by this contract (6) The threshold of tokens needed to be burnt to track the index of a user for the specified pool (if zero, no indexes will be tracked) (7) Burn index of the current user with regards to a specified pool (only tracked if admin configured, and burn meets threshold requirements) (8) Total number of burners above the specified threshold for the specific pool (9) Decimal integer representation of the address of the 'xToken' of the specified pool (10) Total supply of the xToken associated with the specified pool (11) Specified pool's xToken balance of currentUser/ | function getInfoForPool(uint256 poolIndex, address currentUser, address tokenAddress) public view returns (uint256[] memory) {
uint256[] memory info = new uint256[](12);
IERC20Metadata token = IERC20Metadata(tokenAddress);
info[0] = token.decimals();
info[1] = totalBurnt[tokenAddress][poolIndex];
info[2] = amountBurnt[tokenAddress][poolIndex][currentUser];
info[3] = token.balanceOf(currentUser);
info[4] = currentUser.balance;
info[5] = token.allowance(currentUser, address(this));
if (trackBurnerIndexThreshold[tokenAddress][poolIndex] != 0) {
info[6] = trackBurnerIndexThreshold[tokenAddress][poolIndex];
info[7] = burnerIndex[tokenAddress][poolIndex][currentUser];
info[8] = totalTrackedBurners[tokenAddress][poolIndex];
}
if (xTokens[tokenAddress][poolIndex] != address(0)) {
IERC20Metadata xToken = IERC20Metadata(xTokens[tokenAddress][poolIndex]);
info[9] = uint256(uint160(address(xToken)));
info[10] = xToken.totalSupply();
info[11] = xToken.balanceOf(currentUser);
}
return info;
}
| 12,569,946 |
./full_match/5/0x426E93C7Dbcc7e341B6318Cd4e656C72E26e7248/sources/contracts/CrowdFunding.sol | payable is a solidity keyword for paying with cryptocurrency Allows us to set the mount with the value from the FE Selects the campaign from the mapped list/array of campaigns selects the campaign to which it will donate Add info to the arrays of donators and donations | function donateToCampaign(uint256 _id) public payable {
uint256 amount = msg.value;
Campaign storage campaign = campaigns[_id];
campaign.donators.push(msg.sender);
campaign.donations.push(amount);
if(sent) {
campaign.amountCollected = campaign.amountCollected + amount;
}
}
| 1,927,676 |
./full_match/1/0xfacd2eC4647df2Cb758F684C2aAAB56A93288f9e/sources/contracts/Polygon_SpokePool.sol | Called by FxChild upon receiving L1 message that targets this contract. Performs an additional check that the L1 caller was the expected cross domain admin, and then delegate calls. Polygon bridge only executes this external function on the target Polygon contract when relaying messages from L1, so all functions on this SpokePool are expected to originate via this call. stateId value isn't used because it isn't relevant for this method. It doesn't care what state sync triggered this call. rootMessageSender Original L1 sender of data. data ABI encoded function call to execute on this contract./ Validation logic. This uses delegatecall to take the information in the message and process it as a function call on this contract. | function processMessageFromRoot(
uint256, /*stateId*/
address rootMessageSender,
bytes calldata data
) public validateInternalCalls {
require(msg.sender == fxChild, "Not from fxChild");
require(rootMessageSender == crossDomainAdmin, "Not from mainnet admin");
(bool success, ) = address(this).delegatecall(data);
require(success, "delegatecall failed");
}
| 4,938,445 |
./full_match/1/0x95729aCac181E072bcF5d2770d47E9488FD82506/sources/contracts/usds/StablyUsd.sol | Decreases the max supply by `amount` tokens. Emits an {DecreasedMaxSupply} event with `amount` set to the amount, and `sender` set to the sender. Requirements: - `amount` should not result in a max supply lower than the total supply./ | function decreaseMaxSupply(uint256 amount) public onlyRole(DEFAULT_ADMIN_ROLE) {
require(_maxSupply - amount >= totalSupply(), "Resulting max supply is lower than total supply");
_maxSupply -= amount;
emit DecreasedMaxSupply(amount, _msgSender());
}
| 3,087,892 |
pragma solidity ^0.4.19;
/*
* The ResultRegistry contract.
* Store computation results.
*/
contract ResultRegistry {
// Result data structure
struct ResultInfo {
bytes32 resultData; // IPFS address of computation output
bytes32 password; // IPFS address of one-time-password to decrypt the result
}
// array of results
struct ResultStruct {
ResultInfo[] results;
uint count;
}
mapping(address => ResultStruct) addressToResult;
mapping(address => bool) accessAllowed;
function ResultRegistry() public {
accessAllowed[msg.sender] = true;
}
// allow an address to access contract's methods
function allowAccess(address _address) onlyIfAllowed public {
accessAllowed[_address] = true;
}
// ResultManager contract calls this method to add a new result
function addResult(address _owner, bytes32 _newResultData, bytes32 _newPassword) onlyIfAllowed public returns(bool){
addressToResult[_owner].results.push(ResultInfo(_newResultData, _newPassword));
addressToResult[_owner].count = addressToResult[_owner].count + 1;
return true;
}
modifier onlyIfAllowed () {
require(accessAllowed[msg.sender] == true);
_;
}
// returns the a specific result from the given address
function getResult(address owner, uint index) public view returns(bytes32, bytes32) {
require(msg.sender == owner);
return (addressToResult[owner].results[index].resultData, addressToResult[owner].results[index].password);
}
// returns the number of results of the given address
function getResultCount(address owner) public view returns(uint) {
require(msg.sender == owner);
return addressToResult[owner].count;
}
}
| returns the number of results of the given address | function getResultCount(address owner) public view returns(uint) {
require(msg.sender == owner);
return addressToResult[owner].count;
}
| 12,769,186 |
// SPDX-License-Identifier: MIT
/**
* @authors: [@unknownunknown1]
* @reviewers: []
* @auditors: []
* @bounties: []
* @deployments: []
*/
pragma solidity ^0.8;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IArbitrator.sol";
import "./IDisputeKit.sol";
import {SortitionSumTreeFactory} from "../data-structures/SortitionSumTreeFactory.sol";
/**
* @title KlerosCore
* Core arbitrator contract for Kleros v2.
*/
contract KlerosCore is IArbitrator {
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; // Use library functions for sortition sum trees.
// ************************************* //
// * Enums / Structs * //
// ************************************* //
enum Phase {
staking, // Stake can be updated during this phase.
freezing // Phase during which the dispute kits can undergo the drawing process. Staking is not allowed during this phase.
}
enum Period {
evidence, // Evidence can be submitted. This is also when drawing has to take place.
commit, // Jurors commit a hashed vote. This is skipped for courts without hidden votes.
vote, // Jurors reveal/cast their vote depending on whether the court has hidden votes or not.
appeal, // The dispute can be appealed.
execution // Tokens are redistributed and the ruling is executed.
}
struct Court {
uint96 parent; // The parent court.
bool hiddenVotes; // Whether to use commit and reveal or not.
uint256[] children; // List of child courts.
uint256 minStake; // Minimum tokens needed to stake in the court.
uint256 alpha; // Basis point of tokens that are lost when incoherent.
uint256 feeForJuror; // Arbitration fee paid per juror.
uint256 jurorsForCourtJump; // The appeal after the one that reaches this number of jurors will go to the parent court if any.
uint256[4] timesPerPeriod; // The time allotted to each dispute period in the form `timesPerPeriod[period]`.
uint256 supportedDisputeKits; // The bitfield of dispute kits that the court supports.
}
struct Dispute {
uint96 subcourtID; // The ID of the subcourt the dispute is in.
IArbitrable arbitrated; // The arbitrable contract.
IDisputeKit disputeKit; // ID of the dispute kit that this dispute was assigned to.
Period period; // The current period of the dispute.
bool ruled; // True if the ruling has been executed, false otherwise.
uint256 lastPeriodChange; // The last time the period was changed.
uint256 nbVotes; // The total number of votes the dispute can possibly have in the current round. Former votes[_appeal].length.
Round[] rounds;
}
struct Round {
uint256 tokensAtStakePerJuror; // The amount of tokens at stake for each juror in this round.
uint256 totalFeesForJurors; // The total juror fees paid in this round.
uint256 repartitions; // A counter of reward repartitions made in this round.
uint256 penalties; // The amount of tokens collected from penalties in this round.
address[] drawnJurors; // Addresses of the jurors that were drawn in this round.
}
struct Juror {
uint96[] subcourtIDs; // The IDs of subcourts where the juror's stake path ends. A stake path is a path from the forking court to a court the juror directly staked in using `_setStake`.
mapping(uint96 => uint256) stakedTokens; // The number of tokens the juror has staked in the subcourt in the form `stakedTokens[subcourtID]`.
mapping(uint96 => uint256) lockedTokens; // The number of tokens the juror has locked in the subcourt in the form `lockedTokens[subcourtID]`.
}
struct ActiveDisputeKit {
bool added; // Whether dispute kit has already been added to the array.
uint256 index; // Maps array's index with dispute kit's address.
}
struct DelayedStake {
address account; // The address of the juror.
uint96 subcourtID; // The ID of the subcourt.
uint256 stake; // The new stake.
uint256 penalty; // Penalty value, in case the stake was set during execution.
}
// ************************************* //
// * Storage * //
// ************************************* //
uint256 public constant MAX_STAKE_PATHS = 4; // The maximum number of stake paths a juror can have.
uint256 public constant MIN_JURORS = 3; // The global default minimum number of jurors in a dispute.
uint256 public constant ALPHA_DIVISOR = 1e4; // The number to divide `Court.alpha` by.
uint256 public constant NON_PAYABLE_AMOUNT = (2**256 - 2) / 2; // An amount higher than the supply of ETH.
address public governor; // The governor of the contract.
IERC20 public pinakion; // The Pinakion token contract.
// TODO: interactions with jurorProsecutionModule.
address public jurorProsecutionModule; // The module for juror's prosecution.
Phase public phase; // The current phase.
uint256 public minStakingTime; // The time after which the phase can be switched to Freezing if there are open disputes.
uint256 public maxFreezingTime; // The time after which the phase can be switched back to Staking.
uint256 public lastPhaseChange; // The last time the phase was changed.
uint256 public nbDKReadyForPhaseSwitch; // Number of dispute kits that are prepaired for switching from Freezing to Staking phase.
uint256 public freezeBlock; // Number of the block when Core was frozen.
Court[] public courts; // The subcourts.
//TODO: disputeKits forest.
mapping(uint256 => IDisputeKit) public disputeKits; // All supported dispute kits.
Dispute[] public disputes; // The disputes.
mapping(address => Juror) internal jurors; // The jurors.
SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees; // The sortition sum trees.
mapping(uint256 => DelayedStake) public delayedStakes; // Stores the stakes that were changed during Freezing phase, to update them when the phase is switched to Staking.
IDisputeKit[] public activeDisputeKits; // Addresses of dispute kits that currently have disputes that need drawing.
mapping(IDisputeKit => ActiveDisputeKit) public activeKitInfo; // Contains the information about dispute kit which is necessary for switching phases.
uint256 public delayedStakeWriteIndex; // The index of the last `delayedStake` item that was written to the array. 0 index is skipped.
uint256 public delayedStakeReadIndex = 1; // The index of the next `delayedStake` item that should be processed. Starts at 1 because 0 index is skipped.
// ************************************* //
// * Events * //
// ************************************* //
event NewPhase(Phase _phase);
event StakeSet(address indexed _address, uint256 _subcourtID, uint256 _amount, uint256 _newTotalStake);
event NewPeriod(uint256 indexed _disputeID, Period _period);
event AppealPossible(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);
event AppealDecision(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);
event Draw(address indexed _address, uint256 indexed _disputeID, uint256 _appeal, uint256 _voteID);
event TokenAndETHShift(
address indexed _account,
uint256 indexed _disputeID,
int256 _tokenAmount,
int256 _ETHAmount
);
// ************************************* //
// * Function Modifiers * //
// ************************************* //
modifier onlyByGovernor() {
require(governor == msg.sender, "Access not allowed: Governor only.");
_;
}
/** @dev Constructor.
* @param _governor The governor's address.
* @param _pinakion The address of the token contract.
* @param _jurorProsecutionModule The address of the juror prosecution module.
* @param _disputeKit The address of the default dispute kit.
* @param _phaseTimeouts minStakingTime and maxFreezingTime respectively
* @param _hiddenVotes The `hiddenVotes` property value of the forking court.
* @param _courtParameters Numeric parameters of Forking court (minStake, alpha, feeForJuror and jurorsForCourtJump respectively).
* @param _timesPerPeriod The `timesPerPeriod` property value of the forking court.
* @param _sortitionSumTreeK The number of children per node of the forking court's sortition sum tree.
*/
constructor(
address _governor,
IERC20 _pinakion,
address _jurorProsecutionModule,
IDisputeKit _disputeKit,
uint256[2] memory _phaseTimeouts,
bool _hiddenVotes,
uint256[4] memory _courtParameters,
uint256[4] memory _timesPerPeriod,
uint256 _sortitionSumTreeK
) {
governor = _governor;
pinakion = _pinakion;
jurorProsecutionModule = _jurorProsecutionModule;
disputeKits[0] = _disputeKit;
minStakingTime = _phaseTimeouts[0];
maxFreezingTime = _phaseTimeouts[1];
lastPhaseChange = block.timestamp;
// Create the Forking court.
courts.push(
Court({
parent: 0,
children: new uint256[](0),
hiddenVotes: _hiddenVotes,
minStake: _courtParameters[0],
alpha: _courtParameters[1],
feeForJuror: _courtParameters[2],
jurorsForCourtJump: _courtParameters[3],
timesPerPeriod: _timesPerPeriod,
supportedDisputeKits: 1 // The first bit of the bit field is supported by default.
})
);
sortitionSumTrees.createTree(bytes32(0), _sortitionSumTreeK);
}
// ************************ //
// * Governance * //
// ************************ //
/** @dev Allows the governor to call anything on behalf of the contract.
* @param _destination The destination of the call.
* @param _amount The value sent with the call.
* @param _data The data sent with the call.
*/
function executeGovernorProposal(
address _destination,
uint256 _amount,
bytes memory _data
) external onlyByGovernor {
(bool success, ) = _destination.call{value: _amount}(_data);
require(success, "Unsuccessful call");
}
/** @dev Changes the `governor` storage variable.
* @param _governor The new value for the `governor` storage variable.
*/
function changeGovernor(address payable _governor) external onlyByGovernor {
governor = _governor;
}
/** @dev Changes the `pinakion` storage variable.
* @param _pinakion The new value for the `pinakion` storage variable.
*/
function changePinakion(IERC20 _pinakion) external onlyByGovernor {
pinakion = _pinakion;
}
/** @dev Changes the `jurorProsecutionModule` storage variable.
* @param _jurorProsecutionModule The new value for the `jurorProsecutionModule` storage variable.
*/
function changeJurorProsecutionModule(address _jurorProsecutionModule) external onlyByGovernor {
jurorProsecutionModule = _jurorProsecutionModule;
}
/** @dev Changes the `minStakingTime` storage variable.
* @param _minStakingTime The new value for the `minStakingTime` storage variable.
*/
function changeMinStakingTime(uint256 _minStakingTime) external onlyByGovernor {
minStakingTime = _minStakingTime;
}
/** @dev Changes the `maxFreezingTime` storage variable.
* @param _maxFreezingTime The new value for the `maxFreezingTime` storage variable.
*/
function changeMaxFreezingTime(uint256 _maxFreezingTime) external onlyByGovernor {
maxFreezingTime = _maxFreezingTime;
}
/** @dev Add a new supported dispute kit module to the court.
* @param _disputeKitAddress The address of the dispute kit contract.
* @param _disputeKitID The ID assigned to the added dispute kit.
*/
function addNewDisputeKit(IDisputeKit _disputeKitAddress, uint8 _disputeKitID) external onlyByGovernor {
// TODO: the dispute kit data structure. For now keep it a simple mapping.
// Also note that in current state this function doesn't take into account that the added address is actually new.
disputeKits[_disputeKitID] = _disputeKitAddress;
}
/** @dev Creates a subcourt under a specified parent court.
* @param _parent The `parent` property value of the subcourt.
* @param _hiddenVotes The `hiddenVotes` property value of the subcourt.
* @param _minStake The `minStake` property value of the subcourt.
* @param _alpha The `alpha` property value of the subcourt.
* @param _feeForJuror The `feeForJuror` property value of the subcourt.
* @param _jurorsForCourtJump The `jurorsForCourtJump` property value of the subcourt.
* @param _timesPerPeriod The `timesPerPeriod` property value of the subcourt.
* @param _sortitionSumTreeK The number of children per node of the subcourt's sortition sum tree.
* @param _supportedDisputeKits Bitfield that contains the IDs of the dispute kits that this court will support.
*/
function createSubcourt(
uint96 _parent,
bool _hiddenVotes,
uint256 _minStake,
uint256 _alpha,
uint256 _feeForJuror,
uint256 _jurorsForCourtJump,
uint256[4] memory _timesPerPeriod,
uint256 _sortitionSumTreeK,
uint256 _supportedDisputeKits
) external onlyByGovernor {
require(
courts[_parent].minStake <= _minStake,
"A subcourt cannot be a child of a subcourt with a higher minimum stake."
);
uint256 subcourtID = courts.length;
// Create the subcourt.
courts.push(
Court({
parent: _parent,
children: new uint256[](0),
hiddenVotes: _hiddenVotes,
minStake: _minStake,
alpha: _alpha,
feeForJuror: _feeForJuror,
jurorsForCourtJump: _jurorsForCourtJump,
timesPerPeriod: _timesPerPeriod,
supportedDisputeKits: _supportedDisputeKits
})
);
sortitionSumTrees.createTree(bytes32(subcourtID), _sortitionSumTreeK);
// Update the parent.
courts[_parent].children.push(subcourtID);
}
/** @dev Changes the `minStake` property value of a specified subcourt. Don't set to a value lower than its parent's `minStake` property value.
* @param _subcourtID The ID of the subcourt.
* @param _minStake The new value for the `minStake` property value.
*/
function changeSubcourtMinStake(uint96 _subcourtID, uint256 _minStake) external onlyByGovernor {
require(_subcourtID == 0 || courts[courts[_subcourtID].parent].minStake <= _minStake);
for (uint256 i = 0; i < courts[_subcourtID].children.length; i++) {
require(
courts[courts[_subcourtID].children[i]].minStake >= _minStake,
"A subcourt cannot be the parent of a subcourt with a lower minimum stake."
);
}
courts[_subcourtID].minStake = _minStake;
}
/** @dev Changes the `alpha` property value of a specified subcourt.
* @param _subcourtID The ID of the subcourt.
* @param _alpha The new value for the `alpha` property value.
*/
function changeSubcourtAlpha(uint96 _subcourtID, uint256 _alpha) external onlyByGovernor {
courts[_subcourtID].alpha = _alpha;
}
/** @dev Changes the `feeForJuror` property value of a specified subcourt.
* @param _subcourtID The ID of the subcourt.
* @param _feeForJuror The new value for the `feeForJuror` property value.
*/
function changeSubcourtJurorFee(uint96 _subcourtID, uint256 _feeForJuror) external onlyByGovernor {
courts[_subcourtID].feeForJuror = _feeForJuror;
}
/** @dev Changes the `jurorsForCourtJump` property value of a specified subcourt.
* @param _subcourtID The ID of the subcourt.
* @param _jurorsForCourtJump The new value for the `jurorsForCourtJump` property value.
*/
function changeSubcourtJurorsForJump(uint96 _subcourtID, uint256 _jurorsForCourtJump) external onlyByGovernor {
courts[_subcourtID].jurorsForCourtJump = _jurorsForCourtJump;
}
/** @dev Changes the `timesPerPeriod` property value of a specified subcourt.
* @param _subcourtID The ID of the subcourt.
* @param _timesPerPeriod The new value for the `timesPerPeriod` property value.
*/
function changeSubcourtTimesPerPeriod(uint96 _subcourtID, uint256[4] memory _timesPerPeriod)
external
onlyByGovernor
{
courts[_subcourtID].timesPerPeriod = _timesPerPeriod;
}
/** @dev Adds/removes particular dispute kits to a subcourt's bitfield of supported dispute kits.
* @param _subcourtID The ID of the subcourt.
* @param _disputeKitIDs IDs of dispute kits which support should be added/removed.
* @param _enable Whether add or remove the dispute kits from the subcourt.
*/
function setDisputeKits(
uint96 _subcourtID,
uint8[] memory _disputeKitIDs,
bool _enable
) external onlyByGovernor {
Court storage subcourt = courts[_subcourtID];
for (uint256 i = 0; i < _disputeKitIDs.length; i++) {
uint256 bitToChange = 1 << _disputeKitIDs[i]; // Get the bit that corresponds with dispute kit's ID.
if (_enable)
require((bitToChange & ~subcourt.supportedDisputeKits) == bitToChange, "Dispute kit already supported");
else require((bitToChange & subcourt.supportedDisputeKits) == bitToChange, "Dispute kit is not supported");
// Change the bit corresponding with the dispute kit's ID to an opposite value.
subcourt.supportedDisputeKits ^= bitToChange;
}
}
// ************************************* //
// * State Modifiers * //
// ************************************* //
/** @dev Sets the caller's stake in a subcourt.
* @param _subcourtID The ID of the subcourt.
* @param _stake The new stake.
*/
function setStake(uint96 _subcourtID, uint256 _stake) external {
require(setStakeForAccount(msg.sender, _subcourtID, _stake, 0), "Staking failed");
}
/** @dev Executes the next delayed stakes.
* @param _iterations The number of delayed stakes to execute.
*/
function executeDelayedStakes(uint256 _iterations) external {
require(phase == Phase.staking, "Should be in Staking phase.");
uint256 actualIterations = (delayedStakeReadIndex + _iterations) - 1 > delayedStakeWriteIndex
? (delayedStakeWriteIndex - delayedStakeReadIndex) + 1
: _iterations;
uint256 newDelayedStakeReadIndex = delayedStakeReadIndex + actualIterations;
for (uint256 i = delayedStakeReadIndex; i < newDelayedStakeReadIndex; i++) {
DelayedStake storage delayedStake = delayedStakes[i];
setStakeForAccount(delayedStake.account, delayedStake.subcourtID, delayedStake.stake, delayedStake.penalty);
delete delayedStakes[i];
}
delayedStakeReadIndex = newDelayedStakeReadIndex;
}
/** @dev Creates a dispute. Must be called by the arbitrable contract.
* @param _numberOfChoices Number of choices for the jurors to choose from.
* @param _extraData Additional info about the dispute. We use it to pass the ID of the dispute's subcourt (first 32 bytes),
* the minimum number of jurors required (next 32 bytes) and the ID of the specific dispute kit (last 32 bytes).
* @return disputeID The ID of the created dispute.
*/
function createDispute(uint256 _numberOfChoices, bytes memory _extraData)
external
payable
override
returns (uint256 disputeID)
{
require(msg.value >= arbitrationCost(_extraData), "Not enough ETH to cover arbitration cost.");
(uint96 subcourtID, , uint8 disputeKitID) = extraDataToSubcourtIDMinJurorsDisputeKit(_extraData);
uint256 bitToCheck = 1 << disputeKitID; // Get the bit that corresponds with dispute kit's ID.
require(
(bitToCheck & courts[subcourtID].supportedDisputeKits) == bitToCheck,
"The dispute kit is not supported by this subcourt"
);
disputeID = disputes.length;
Dispute storage dispute = disputes.push();
dispute.subcourtID = subcourtID;
dispute.arbitrated = IArbitrable(msg.sender);
IDisputeKit disputeKit = disputeKits[disputeKitID];
dispute.disputeKit = disputeKit;
dispute.lastPeriodChange = block.timestamp;
dispute.nbVotes = msg.value / courts[dispute.subcourtID].feeForJuror;
Round storage round = dispute.rounds.push();
round.tokensAtStakePerJuror =
(courts[dispute.subcourtID].minStake * courts[dispute.subcourtID].alpha) /
ALPHA_DIVISOR;
round.totalFeesForJurors = msg.value;
disputeKit.createDispute(disputeID, _numberOfChoices, _extraData, dispute.nbVotes);
ActiveDisputeKit storage activeDK = activeKitInfo[disputeKit];
if (!activeDK.added) {
activeDK.index = activeDisputeKits.length;
activeDisputeKits.push(disputeKit);
activeDK.added = true;
}
emit DisputeCreation(disputeID, IArbitrable(msg.sender));
}
/** @dev Switches the phases between Staking and Freezing, also prepares the dispute kits for a switch.
* @param _iterations Number of active dispute kits to go through.
* If set to 0 or a value larger than the number of active dispute kits iterates until the last element.
* @notice `_iterations` parameter is only required for switch from Freezing to Staking and can be left empty otherwise.
*/
function passPhase(uint256 _iterations) external {
if (phase == Phase.staking) {
require(
block.timestamp - lastPhaseChange >= minStakingTime,
"The minimal staking time has not passed yet."
);
require(activeDisputeKits.length > 0, "There are no disputes that need jurors.");
phase = Phase.freezing;
freezeBlock = block.number;
lastPhaseChange = block.timestamp;
emit NewPhase(phase);
} else if (phase == Phase.freezing) {
// Prepare dispute kits for switching.
require(block.timestamp - lastPhaseChange >= maxFreezingTime, "Timeout has not passed yet");
uint256 startIndex = nbDKReadyForPhaseSwitch;
bool chkPrevIndex;
for (
uint256 i = startIndex;
i < activeDisputeKits.length && (_iterations == 0 || i < startIndex + _iterations);
i++
) {
if (chkPrevIndex) {
// Check the element that replaced the deleted one in the previous iteration.
i--;
chkPrevIndex = false;
}
IDisputeKit disputeKit = activeDisputeKits[i];
disputeKit.onCoreFreezingPhase();
// Remove dispute kit from activeDisputeKits if it finished drawing.
if (disputeKit.getDisputesWithoutJurors() == 0) {
ActiveDisputeKit storage activeDK = activeKitInfo[disputeKit];
// Replace the deleted address with the last one and also replace its index.
activeDisputeKits[activeDK.index] = activeDisputeKits[activeDisputeKits.length - 1];
activeKitInfo[activeDisputeKits[activeDK.index]].index = activeDK.index;
activeDisputeKits.pop();
// We don't increment the DK counter here since we delete the element anyway.
delete activeKitInfo[disputeKit];
chkPrevIndex = true;
} else {
nbDKReadyForPhaseSwitch++;
}
}
if (nbDKReadyForPhaseSwitch == activeDisputeKits.length) {
phase = Phase.staking;
lastPhaseChange = block.timestamp;
nbDKReadyForPhaseSwitch = 0;
emit NewPhase(phase);
}
}
}
/** @dev Passes the period of a specified dispute.
* @param _disputeID The ID of the dispute.
*/
function passPeriod(uint256 _disputeID) external {
Dispute storage dispute = disputes[_disputeID];
uint256 currentRound = dispute.rounds.length - 1;
Round storage round = dispute.rounds[currentRound];
if (dispute.period == Period.evidence) {
require(
currentRound > 0 ||
block.timestamp - dispute.lastPeriodChange >=
courts[dispute.subcourtID].timesPerPeriod[uint256(dispute.period)],
"The evidence period time has not passed yet and it is not an appeal."
);
require(round.drawnJurors.length == dispute.nbVotes, "The dispute has not finished drawing yet.");
dispute.period = courts[dispute.subcourtID].hiddenVotes ? Period.commit : Period.vote;
} else if (dispute.period == Period.commit) {
// In case the jurors finished casting commits beforehand the dispute kit should call passPeriod() by itself.
require(
block.timestamp - dispute.lastPeriodChange >=
courts[dispute.subcourtID].timesPerPeriod[uint256(dispute.period)] ||
msg.sender == address(dispute.disputeKit),
"The commit period time has not passed yet."
);
dispute.period = Period.vote;
} else if (dispute.period == Period.vote) {
// In case the jurors finished casting votes beforehand the dispute kit should call passPeriod() by itself.
require(
block.timestamp - dispute.lastPeriodChange >=
courts[dispute.subcourtID].timesPerPeriod[uint256(dispute.period)] ||
msg.sender == address(dispute.disputeKit),
"The vote period time has not passed yet"
);
dispute.period = Period.appeal;
emit AppealPossible(_disputeID, dispute.arbitrated);
} else if (dispute.period == Period.appeal) {
require(
block.timestamp - dispute.lastPeriodChange >=
courts[dispute.subcourtID].timesPerPeriod[uint256(dispute.period)],
"The appeal period time has not passed yet."
);
dispute.period = Period.execution;
} else if (dispute.period == Period.execution) {
revert("The dispute is already in the last period.");
}
dispute.lastPeriodChange = block.timestamp;
emit NewPeriod(_disputeID, dispute.period);
}
/** @dev Draws jurors for the dispute. Can be called in parts.
* @param _disputeID The ID of the dispute.
* @param _iterations The number of iterations to run.
*/
function draw(uint256 _disputeID, uint256 _iterations) external {
require(phase == Phase.freezing, "Wrong phase.");
Dispute storage dispute = disputes[_disputeID];
uint256 currentRound = dispute.rounds.length - 1;
Round storage round = dispute.rounds[currentRound];
require(dispute.period == Period.evidence, "Should be evidence period.");
IDisputeKit disputeKit = dispute.disputeKit;
uint256 startIndex = round.drawnJurors.length;
uint256 endIndex = startIndex + _iterations <= dispute.nbVotes ? startIndex + _iterations : dispute.nbVotes;
for (uint256 i = startIndex; i < endIndex; i++) {
address drawnAddress = disputeKit.draw(_disputeID);
if (drawnAddress != address(0)) {
// In case no one has staked at the court yet.
jurors[drawnAddress].lockedTokens[dispute.subcourtID] += round.tokensAtStakePerJuror;
round.drawnJurors.push(drawnAddress);
emit Draw(drawnAddress, _disputeID, currentRound, i);
}
}
}
/** @dev Appeals the ruling of a specified dispute.
* Note: Access restricted to the Dispute Kit for this `disputeID`.
* @param _disputeID The ID of the dispute.
*/
function appeal(uint256 _disputeID) external payable {
require(msg.value >= appealCost(_disputeID), "Not enough ETH to cover appeal cost.");
Dispute storage dispute = disputes[_disputeID];
require(dispute.period == Period.appeal, "Dispute is not appealable.");
require(msg.sender == address(dispute.disputeKit), "Access not allowed: Dispute Kit only.");
if (dispute.nbVotes >= courts[dispute.subcourtID].jurorsForCourtJump)
// Jump to parent subcourt.
// TODO: Handle court jump in the Forking court. Also make sure the new subcourt is compatible with the dispute kit.
dispute.subcourtID = courts[dispute.subcourtID].parent;
dispute.period = Period.evidence;
dispute.lastPeriodChange = block.timestamp;
// As many votes that can be afforded by the provided funds.
dispute.nbVotes = msg.value / courts[dispute.subcourtID].feeForJuror;
Round storage extraRound = dispute.rounds.push();
extraRound.tokensAtStakePerJuror =
(courts[dispute.subcourtID].minStake * courts[dispute.subcourtID].alpha) /
ALPHA_DIVISOR;
extraRound.totalFeesForJurors = msg.value;
ActiveDisputeKit storage activeDK = activeKitInfo[dispute.disputeKit];
if (!activeDK.added) {
activeDK.index = activeDisputeKits.length;
activeDisputeKits.push(dispute.disputeKit);
activeDK.added = true;
}
emit AppealDecision(_disputeID, dispute.arbitrated);
emit NewPeriod(_disputeID, Period.evidence);
}
/** @dev Distribute tokens and ETH for the specific round of the dispute. Can be called in parts.
* @param _disputeID The ID of the dispute.
* @param _appeal The appeal round.
* @param _iterations The number of iterations to run.
*/
function execute(
uint256 _disputeID,
uint256 _appeal,
uint256 _iterations
) external {
Dispute storage dispute = disputes[_disputeID];
require(dispute.period == Period.execution, "Should be execution period.");
uint256 end = dispute.rounds[_appeal].repartitions + _iterations;
uint256 penaltiesInRoundCache = dispute.rounds[_appeal].penalties; // For saving gas.
uint256 numberOfVotesInRound = dispute.rounds[_appeal].drawnJurors.length;
uint256 coherentCount = dispute.disputeKit.getCoherentCount(_disputeID, _appeal); // Total number of jurors that are eligible to a reward in this round.
address account; // Address of the juror.
uint256 degreeOfCoherence; // [0, 1] value that determines how coherent the juror was in this round, in basis points.
if (coherentCount == 0) {
// We loop over the votes once as there are no rewards because it is not a tie and no one in this round is coherent with the final outcome.
if (end > numberOfVotesInRound) end = numberOfVotesInRound;
} else {
// We loop over the votes twice, first to collect penalties, and second to distribute them as rewards along with arbitration fees.
if (end > numberOfVotesInRound * 2) end = numberOfVotesInRound * 2;
}
for (uint256 i = dispute.rounds[_appeal].repartitions; i < end; i++) {
// Penalty.
if (i < numberOfVotesInRound) {
degreeOfCoherence = dispute.disputeKit.getDegreeOfCoherence(_disputeID, _appeal, i);
if (degreeOfCoherence > ALPHA_DIVISOR) degreeOfCoherence = ALPHA_DIVISOR; // Make sure the degree doesn't exceed 1, though it should be ensured by the dispute kit.
uint256 penalty = (dispute.rounds[_appeal].tokensAtStakePerJuror *
(ALPHA_DIVISOR - degreeOfCoherence)) / ALPHA_DIVISOR; // Fully coherent jurors won't be penalized.
penaltiesInRoundCache += penalty;
account = dispute.rounds[_appeal].drawnJurors[i];
jurors[account].lockedTokens[dispute.subcourtID] -= penalty; // Release this part of locked tokens.
// Can only update the stake if it is able to cover the minStake and penalty, otherwise unstake from the court.
if (jurors[account].stakedTokens[dispute.subcourtID] >= courts[dispute.subcourtID].minStake + penalty) {
setStakeForAccount(
account,
dispute.subcourtID,
jurors[account].stakedTokens[dispute.subcourtID] - penalty,
penalty
);
} else if (jurors[account].stakedTokens[dispute.subcourtID] != 0) {
setStakeForAccount(account, dispute.subcourtID, 0, penalty);
}
// Unstake the juror if he lost due to inactivity.
if (!dispute.disputeKit.isVoteActive(_disputeID, _appeal, i)) {
for (uint256 j = 0; j < jurors[account].subcourtIDs.length; j++)
setStakeForAccount(account, jurors[account].subcourtIDs[j], 0, 0);
}
emit TokenAndETHShift(account, _disputeID, -int256(penalty), 0);
if (i == numberOfVotesInRound - 1) {
if (coherentCount == 0) {
// No one was coherent. Send the rewards to governor.
payable(governor).send(dispute.rounds[_appeal].totalFeesForJurors);
pinakion.transfer(governor, penaltiesInRoundCache);
}
}
// Reward.
} else {
degreeOfCoherence = dispute.disputeKit.getDegreeOfCoherence(
_disputeID,
_appeal,
i % numberOfVotesInRound
);
if (degreeOfCoherence > ALPHA_DIVISOR) degreeOfCoherence = ALPHA_DIVISOR;
account = dispute.rounds[_appeal].drawnJurors[i % numberOfVotesInRound];
// Release the rest of the tokens of the juror for this round.
jurors[account].lockedTokens[dispute.subcourtID] -=
(dispute.rounds[_appeal].tokensAtStakePerJuror * degreeOfCoherence) /
ALPHA_DIVISOR;
if (jurors[account].stakedTokens[dispute.subcourtID] == 0) {
// Give back the locked tokens in case the juror fully unstaked earlier.
pinakion.transfer(
account,
(dispute.rounds[_appeal].tokensAtStakePerJuror * degreeOfCoherence) / ALPHA_DIVISOR
);
}
uint256 tokenReward = ((penaltiesInRoundCache / coherentCount) * degreeOfCoherence) / ALPHA_DIVISOR;
uint256 ETHReward = ((dispute.rounds[_appeal].totalFeesForJurors / coherentCount) * degreeOfCoherence) /
ALPHA_DIVISOR;
pinakion.transfer(account, tokenReward);
payable(account).send(ETHReward);
emit TokenAndETHShift(account, _disputeID, int256(tokenReward), int256(ETHReward));
}
}
if (dispute.rounds[_appeal].penalties != penaltiesInRoundCache)
dispute.rounds[_appeal].penalties = penaltiesInRoundCache;
dispute.rounds[_appeal].repartitions = end;
}
/** @dev Executes a specified dispute's ruling. UNTRUSTED.
* @param _disputeID The ID of the dispute.
*/
function executeRuling(uint256 _disputeID) external {
Dispute storage dispute = disputes[_disputeID];
require(dispute.period == Period.execution, "Should be execution period.");
require(!dispute.ruled, "Ruling already executed.");
uint256 winningChoice = currentRuling(_disputeID);
dispute.ruled = true;
dispute.arbitrated.rule(_disputeID, winningChoice);
}
// ************************************* //
// * Public Views * //
// ************************************* //
/** @dev Gets the cost of arbitration in a specified subcourt.
* @param _extraData Additional info about the dispute. We use it to pass the ID of the subcourt to create the dispute in (first 32 bytes)
* and the minimum number of jurors required (next 32 bytes).
* @return cost The arbitration cost.
*/
function arbitrationCost(bytes memory _extraData) public view override returns (uint256 cost) {
(uint96 subcourtID, uint256 minJurors, ) = extraDataToSubcourtIDMinJurorsDisputeKit(_extraData);
cost = courts[subcourtID].feeForJuror * minJurors;
}
/** @dev Gets the cost of appealing a specified dispute.
* @param _disputeID The ID of the dispute.
* @return cost The appeal cost.
*/
function appealCost(uint256 _disputeID) public view returns (uint256 cost) {
Dispute storage dispute = disputes[_disputeID];
if (dispute.nbVotes >= courts[dispute.subcourtID].jurorsForCourtJump) {
// Jump to parent subcourt.
if (dispute.subcourtID == 0)
// Already in the forking court.
cost = NON_PAYABLE_AMOUNT; // Get the cost of the parent subcourt.
else cost = courts[courts[dispute.subcourtID].parent].feeForJuror * ((dispute.nbVotes * 2) + 1);
}
// Stay in current subcourt.
else cost = courts[dispute.subcourtID].feeForJuror * ((dispute.nbVotes * 2) + 1);
}
/** @dev Gets the start and the end of a specified dispute's current appeal period.
* @param _disputeID The ID of the dispute.
* @return start The start of the appeal period.
* @return end The end of the appeal period.
*/
function appealPeriod(uint256 _disputeID) public view returns (uint256 start, uint256 end) {
Dispute storage dispute = disputes[_disputeID];
if (dispute.period == Period.appeal) {
start = dispute.lastPeriodChange;
end = dispute.lastPeriodChange + courts[dispute.subcourtID].timesPerPeriod[uint256(Period.appeal)];
} else {
start = 0;
end = 0;
}
}
/** @dev Gets the current ruling of a specified dispute.
* @param _disputeID The ID of the dispute.
* @return ruling The current ruling.
*/
function currentRuling(uint256 _disputeID) public view returns (uint256 ruling) {
IDisputeKit disputeKit = disputes[_disputeID].disputeKit;
return disputeKit.currentRuling(_disputeID);
}
function getRoundInfo(uint256 _disputeID, uint256 _round)
external
view
returns (
uint256 tokensAtStakePerJuror,
uint256 totalFeesForJurors,
uint256 repartitions,
uint256 penalties,
address[] memory drawnJurors
)
{
Dispute storage dispute = disputes[_disputeID];
Round storage round = dispute.rounds[_round];
return (
round.tokensAtStakePerJuror,
round.totalFeesForJurors,
round.repartitions,
round.penalties,
round.drawnJurors
);
}
function getNumberOfRounds(uint256 _disputeID) external view returns (uint256) {
Dispute storage dispute = disputes[_disputeID];
return dispute.rounds.length;
}
function getJurorBalance(address _juror, uint96 _subcourtID)
external
view
returns (uint256 staked, uint256 locked)
{
Juror storage juror = jurors[_juror];
staked = juror.stakedTokens[_subcourtID];
locked = juror.lockedTokens[_subcourtID];
}
// ************************************* //
// * Public Views for Dispute Kits * //
// ************************************* //
function getSortitionSumTree(bytes32 _key)
public
view
returns (
uint256 K,
uint256[] memory stack,
uint256[] memory nodes
)
{
SortitionSumTreeFactory.SortitionSumTree storage tree = sortitionSumTrees.sortitionSumTrees[_key];
K = tree.K;
stack = tree.stack;
nodes = tree.nodes;
}
// TODO: some getters can be merged into a single function
function getSortitionSumTreeID(bytes32 _key, uint256 _nodeIndex) external view returns (bytes32 ID) {
ID = sortitionSumTrees.sortitionSumTrees[_key].nodeIndexesToIDs[_nodeIndex];
}
function getSubcourtID(uint256 _disputeID) external view returns (uint256 subcourtID) {
return disputes[_disputeID].subcourtID;
}
function getCurrentPeriod(uint256 _disputeID) external view returns (Period period) {
return disputes[_disputeID].period;
}
function areVotesHidden(uint256 _subcourtID) external view returns (bool hiddenVotes) {
return courts[_subcourtID].hiddenVotes;
}
function isRuled(uint256 _disputeID) external view returns (bool) {
return disputes[_disputeID].ruled;
}
function getNumberOfVotes(uint256 _disputeID) external view returns (uint256) {
return disputes[_disputeID].nbVotes;
}
function getFreezeBlock() external view returns (uint256) {
return freezeBlock;
}
/** @dev Returns true if Dispute Kits are allowed to change their phases.
* The purpose of this function is to make sure that every dispute kit is in the same phase before Core contract switches its phase to Staking.
* @return Whether dispute kits are allowed to switch phases or not.
*/
function allowSwitchPhase() external view returns (bool) {
return phase == Phase.freezing && nbDKReadyForPhaseSwitch == 0;
}
// ************************************* //
// * Internal * //
// ************************************* //
/** @dev Sets the specified juror's stake in a subcourt.
* `O(n + p * log_k(j))` where
* `n` is the number of subcourts the juror has staked in,
* `p` is the depth of the subcourt tree,
* `k` is the minimum number of children per node of one of these subcourts' sortition sum tree,
* and `j` is the maximum number of jurors that ever staked in one of these subcourts simultaneously.
* @param _account The address of the juror.
* @param _subcourtID The ID of the subcourt.
* @param _stake The new stake.
* @param _penalty Penalized amount won't be transferred back to juror when the stake is lowered.
* @return succeeded True if the call succeeded, false otherwise.
*/
function setStakeForAccount(
address _account,
uint96 _subcourtID,
uint256 _stake,
uint256 _penalty
) internal returns (bool succeeded) {
// Input and transfer checks //
if (_subcourtID > courts.length) return false;
Juror storage juror = jurors[_account];
bytes32 stakePathID = accountAndSubcourtIDToStakePathID(_account, _subcourtID);
uint256 currentStake = sortitionSumTrees.stakeOf(bytes32(uint256(_subcourtID)), stakePathID);
if (_stake != 0) {
// Check against locked tokens in case the min stake was lowered.
if (_stake < courts[_subcourtID].minStake || _stake < juror.lockedTokens[_subcourtID]) return false;
if (currentStake == 0 && juror.subcourtIDs.length >= MAX_STAKE_PATHS) return false;
}
// Delayed action logic.
if (phase != Phase.staking) {
delayedStakes[++delayedStakeWriteIndex] = DelayedStake({
account: _account,
subcourtID: _subcourtID,
stake: _stake,
penalty: _penalty
});
return true;
}
uint256 transferredAmount;
if (_stake >= currentStake) {
transferredAmount = _stake - currentStake;
if (transferredAmount > 0) {
// TODO: handle transfer reverts.
if (!pinakion.transferFrom(_account, address(this), transferredAmount)) return false;
}
} else if (_stake == 0) {
// Keep locked tokens in the contract and release them after dispute is executed.
transferredAmount = currentStake - juror.lockedTokens[_subcourtID] - _penalty;
if (transferredAmount > 0) {
if (!pinakion.transfer(_account, transferredAmount)) return false;
}
} else {
transferredAmount = currentStake - _stake - _penalty;
if (transferredAmount > 0) {
if (!pinakion.transfer(_account, transferredAmount)) return false;
}
}
// State update //
if (_stake != 0) {
if (currentStake == 0) {
juror.subcourtIDs.push(_subcourtID);
}
} else {
for (uint256 i = 0; i < juror.subcourtIDs.length; i++) {
if (juror.subcourtIDs[i] == _subcourtID) {
juror.subcourtIDs[i] = juror.subcourtIDs[juror.subcourtIDs.length - 1];
juror.subcourtIDs.pop();
break;
}
}
}
// Update juror's records.
uint256 newTotalStake = juror.stakedTokens[_subcourtID] - currentStake + _stake;
juror.stakedTokens[_subcourtID] = newTotalStake;
// Update subcourt parents.
bool finished = false;
uint256 currentSubcourtID = _subcourtID;
while (!finished) {
sortitionSumTrees.set(bytes32(currentSubcourtID), _stake, stakePathID);
if (currentSubcourtID == 0) finished = true;
else currentSubcourtID = courts[currentSubcourtID].parent;
}
emit StakeSet(_account, _subcourtID, _stake, newTotalStake);
return true;
}
/** @dev Gets a subcourt ID, the minimum number of jurors and an ID of a dispute kit from a specified extra data bytes array.
* Note that if extradata contains an incorrect value then this value will be switched to default.
* @param _extraData The extra data bytes array. The first 32 bytes are the subcourt ID, the next are the minimum number of jurors and the last are the dispute kit ID.
* @return subcourtID The subcourt ID.
* @return minJurors The minimum number of jurors required.
* @return disputeKitID The ID of the dispute kit.
*/
function extraDataToSubcourtIDMinJurorsDisputeKit(bytes memory _extraData)
internal
view
returns (
uint96 subcourtID,
uint256 minJurors,
uint8 disputeKitID
)
{
// Note that if the extradata doesn't contain 32 bytes for the dispute kit ID it'll return the default 0 index.
if (_extraData.length >= 64) {
assembly {
// solium-disable-line security/no-inline-assembly
subcourtID := mload(add(_extraData, 0x20))
minJurors := mload(add(_extraData, 0x40))
disputeKitID := mload(add(_extraData, 0x60))
}
if (subcourtID >= courts.length) subcourtID = 0;
if (minJurors == 0) minJurors = MIN_JURORS;
if (disputeKits[disputeKitID] == IDisputeKit(address(0))) disputeKitID = 0;
} else {
subcourtID = 0;
minJurors = MIN_JURORS;
disputeKitID = 0;
}
}
/** @dev Packs an account and a subcourt ID into a stake path ID.
* @param _account The address of the juror to pack.
* @param _subcourtID The subcourt ID to pack.
* @return stakePathID The stake path ID.
*/
function accountAndSubcourtIDToStakePathID(address _account, uint96 _subcourtID)
internal
pure
returns (bytes32 stakePathID)
{
assembly {
// solium-disable-line security/no-inline-assembly
let ptr := mload(0x40)
for {
let i := 0x00
} lt(i, 0x14) {
i := add(i, 0x01)
} {
mstore8(add(ptr, i), byte(add(0x0c, i), _account))
}
for {
let i := 0x14
} lt(i, 0x20) {
i := add(i, 0x01)
} {
mstore8(add(ptr, i), byte(i, _subcourtID))
}
stakePathID := mload(ptr)
}
}
}
| Creates a dispute. Must be called by the arbitrable contract. _numberOfChoices Number of choices for the jurors to choose from. _extraData Additional info about the dispute. We use it to pass the ID of the dispute's subcourt (first 32 bytes), the minimum number of jurors required (next 32 bytes) and the ID of the specific dispute kit (last 32 bytes). return disputeID The ID of the created dispute./ | function createDispute(uint256 _numberOfChoices, bytes memory _extraData)
external
payable
override
returns (uint256 disputeID)
{
require(msg.value >= arbitrationCost(_extraData), "Not enough ETH to cover arbitration cost.");
(uint96 subcourtID, , uint8 disputeKitID) = extraDataToSubcourtIDMinJurorsDisputeKit(_extraData);
require(
(bitToCheck & courts[subcourtID].supportedDisputeKits) == bitToCheck,
"The dispute kit is not supported by this subcourt"
);
disputeID = disputes.length;
Dispute storage dispute = disputes.push();
dispute.subcourtID = subcourtID;
dispute.arbitrated = IArbitrable(msg.sender);
IDisputeKit disputeKit = disputeKits[disputeKitID];
dispute.disputeKit = disputeKit;
dispute.lastPeriodChange = block.timestamp;
dispute.nbVotes = msg.value / courts[dispute.subcourtID].feeForJuror;
Round storage round = dispute.rounds.push();
round.tokensAtStakePerJuror =
(courts[dispute.subcourtID].minStake * courts[dispute.subcourtID].alpha) /
ALPHA_DIVISOR;
round.totalFeesForJurors = msg.value;
disputeKit.createDispute(disputeID, _numberOfChoices, _extraData, dispute.nbVotes);
ActiveDisputeKit storage activeDK = activeKitInfo[disputeKit];
if (!activeDK.added) {
activeDK.index = activeDisputeKits.length;
activeDisputeKits.push(disputeKit);
activeDK.added = true;
}
emit DisputeCreation(disputeID, IArbitrable(msg.sender));
}
| 12,944,276 |
pragma solidity 0.5.17;
library SafeMath {
function MUL922(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function DIV682(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 SUB426(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b <= a);
return a - b;
}
function ADD438(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OWNERSHIPTRANSFERRED626(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor() public {
owner = msg.sender;
}
modifier ONLYOWNER539() { //inject NONSTANDARD NAMING
require(msg.sender == owner);
_;
}
function TRANSFEROWNERSHIP867(address newOwner) ONLYOWNER539 public { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED626(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function BALANCEOF550(address who) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER247(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
event TRANSFER814(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
function TRANSFER247(address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0) && _to != address(this));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].SUB426(_value);
balances[_to] = balances[_to].ADD438(_value);
emit TRANSFER814(msg.sender, _to, _value);
return true;
}
function BALANCEOF550(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function ALLOWANCE624(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFERFROM452(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
function APPROVE694(address spender, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
event APPROVAL612(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function TRANSFERFROM452(address _from, address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0) && _to != address(this));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].SUB426(_value);
balances[_to] = balances[_to].ADD438(_value);
allowed[_from][msg.sender] = _allowance.SUB426(_value);
emit TRANSFER814(_from, _to, _value);
return true;
}
function APPROVE694(address _spender, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = _value;
emit APPROVAL612(msg.sender, _spender, _value);
return true;
}
function ALLOWANCE624(address _owner, address _spender) public view returns (uint256 remaining) { //inject NONSTANDARD NAMING
return allowed[_owner][_spender];
}
function INCREASEAPPROVAL555 (address _spender, uint _addedValue) public //inject NONSTANDARD NAMING
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].ADD438(_addedValue);
emit APPROVAL612(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function DECREASEAPPROVAL969 (address _spender, uint _subtractedValue) public //inject NONSTANDARD NAMING
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.SUB426(_subtractedValue);
}
emit APPROVAL612(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
interface tokenRecipient {
function RECEIVEAPPROVAL835(address _from, uint256 _value, bytes calldata _extraData) external; //inject NONSTANDARD NAMING
}
contract BurnableToken is StandardToken {
event BURN972(address indexed burner, uint256 value); //inject NONSTANDARD NAMING
function BURN583(address burner, uint256 _value) internal { //inject NONSTANDARD NAMING
require(_value > 0);
require(_value <= balances[burner]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[burner] = balances[burner].SUB426(_value);
totalSupply = totalSupply.SUB426(_value);
emit TRANSFER814(burner, address(0), _value);
emit BURN972(burner, _value);
}
}
contract DKING is BurnableToken, Ownable {
address public stakingAddress;
string public constant name593 = "Deflationary King"; //inject NONSTANDARD NAMING
string public constant symbol894 = "DKING"; //inject NONSTANDARD NAMING
uint public constant decimals497 = 18; //inject NONSTANDARD NAMING
// there is no problem in using * here instead of .mul()
uint256 public constant initialsupply444 = 1000000 * (10 ** uint256(decimals497)); //inject NONSTANDARD NAMING
function SETSTAKINGADDRESS222(address _addr) public ONLYOWNER539 { //inject NONSTANDARD NAMING
stakingAddress = _addr;
}
function TRANSFER247(address to, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
uint _amountToBurn = amount.MUL922(400).DIV682(10000);
uint _amountToDisburse = amount.MUL922(400).DIV682(10000);
uint _amountAfterFee = amount.SUB426(_amountToBurn).SUB426(_amountToDisburse);
BURN583(msg.sender, _amountToBurn);
require(super.TRANSFER247(stakingAddress, _amountToDisburse), "Cannot disburse rewards.");
if (stakingAddress != address(0)) {
tokenRecipient(stakingAddress).RECEIVEAPPROVAL835(msg.sender, _amountToDisburse, "");
}
require(super.TRANSFER247(to, _amountAfterFee), "Cannot transfer tokens.");
return true;
}
function TRANSFERFROM452(address from, address to, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
require(to != address(0) && to != address(this));
uint _amountToBurn = amount.MUL922(400).DIV682(10000);
uint _amountToDisburse = amount.MUL922(400).DIV682(10000);
uint _amountAfterFee = amount.SUB426(_amountToBurn).SUB426(_amountToDisburse);
uint256 _allowance = allowed[from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[from] = balances[from].SUB426(_amountAfterFee);
balances[to] = balances[to].ADD438(_amountAfterFee);
balances[from] = balances[from].SUB426(_amountToDisburse);
balances[stakingAddress] = balances[stakingAddress].ADD438(_amountToDisburse);
allowed[from][msg.sender] = _allowance.SUB426(amount);
BURN583(from, _amountToBurn);
emit TRANSFER814(from, stakingAddress, _amountToDisburse);
emit TRANSFER814(from, to, _amountAfterFee);
if (stakingAddress != address(0)) {
tokenRecipient(stakingAddress).RECEIVEAPPROVAL835(msg.sender, _amountToDisburse, "");
}
return true;
}
// Constructors
constructor () public {
totalSupply = initialsupply444;
balances[msg.sender] = initialsupply444; // Send all tokens to owner
emit TRANSFER814(address(0), msg.sender, initialsupply444);
}
function TRANSFERANYERC20TOKEN616(address _tokenAddress, address _to, uint _amount) public ONLYOWNER539 { //inject NONSTANDARD NAMING
ERC20(_tokenAddress).TRANSFER247(_to, _amount);
}
} | inject NONSTANDARD NAMING | function BALANCEOF550(address who) public view returns (uint256); | 964,885 |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Lockable.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
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: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @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() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./MultiRole.sol";
import "../interfaces/ExpandedIERC20.sol";
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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 {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// 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.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts 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), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts 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), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI)
* @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note:
* this token should never be used to store real value since it allows permissionless minting.
*/
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
/**
* Withdrawable contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MultiRole.sol";
/**
* @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds.
*/
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Interface for Balancer.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract Balancer {
function getSpotPriceSansFee(address tokenIn, address tokenOut) external view virtual returns (uint256 spotPrice);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes the decimals read only method.
*/
interface IERC20Standard is IERC20 {
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05`
* (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value
* {ERC20} uses, unless {_setupDecimals} is called.
*
* NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic
* of the contract, including {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
abstract contract OneSplit {
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) public view virtual returns (uint256 returnAmount, uint256[] memory distribution);
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public payable virtual returns (uint256 returnAmount);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
// This is an interface to interact with a deployed implementation by https://github.com/kleros/action-callback-bots for
// batching on-chain transactions.
// See deployed implementation here: https://etherscan.io/address/0x82458d1c812d7c930bb3229c9e159cbabd9aa8cb.
abstract contract TransactionBatcher {
function batchSend(
address[] memory targets,
uint256[] memory values,
bytes[] memory datas
) public payable virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Interface for Uniswap v2.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract Uniswap {
// Called after every swap showing the new uniswap "price" for this token pair.
event Sync(uint112 reserve0, uint112 reserve1);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/Balancer.sol";
/**
* @title Balancer Mock
*/
contract BalancerMock is Balancer {
uint256 price = 0;
// these params arent used in the mock, but this is to maintain compatibility with balancer API
function getSpotPriceSansFee(address tokenIn, address tokenOut)
external
view
virtual
override
returns (uint256 spotPrice)
{
return price;
}
// this is not a balancer call, but for testing for changing price.
function setPrice(uint256 newPrice) external {
price = newPrice;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Implements only the required ERC20 methods. This contract is used
* test how contracts handle ERC20 contracts that have not implemented `decimals()`
* @dev Mostly copied from Consensys EIP-20 implementation:
* https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol
*/
contract BasicERC20 is IERC20 {
uint256 private constant MAX_UINT256 = 2**256 - 1;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
uint256 private _totalSupply;
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
_totalSupply = _initialAmount;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public override returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/*
MultiRoleTest contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/MultiRole.sol";
// The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes.
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/OneSplit.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title OneSplit Mock that allows manual price injection.
*/
contract OneSplitMock is OneSplit {
address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
mapping(bytes32 => uint256) prices;
receive() external payable {}
// Sets price of 1 FROM = <PRICE> TO
function setPrice(
address from,
address to,
uint256 price
) external {
prices[keccak256(abi.encodePacked(from, to))] = price;
}
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) public view override returns (uint256 returnAmount, uint256[] memory distribution) {
returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount;
return (returnAmount, distribution);
}
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public payable override returns (uint256 returnAmount) {
uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount;
require(amountReturn >= minReturn, "Min Amount not reached");
if (destToken == ETH_ADDRESS) {
msg.sender.transfer(amountReturn);
} else {
require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Tests reentrancy guards defined in Lockable.sol.
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol.
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// The Reentrancy Checker causes failures if it is successfully able to re-enter a contract.
// How to use:
// 1. Call setTransactionData with the transaction data you want the Reentrancy Checker to reenter the calling
// contract with.
// 2. Get the calling contract to call into the reentrancy checker with any call. The fallback function will receive
// this call and reenter the contract with the transaction data provided in 1. If that reentrancy call does not
// revert, then the reentrancy checker reverts the initial call, likely causeing the entire transaction to revert.
//
// Note: the reentrancy checker has a guard to prevent an infinite cycle of reentrancy. Inifinite cycles will run out
// of gas in all cases, potentially causing a revert when the contract is adequately protected from reentrancy.
contract ReentrancyChecker {
bytes public txnData;
bool hasBeenCalled;
// Used to prevent infinite cycles where the reentrancy is cycled forever.
modifier skipIfReentered {
if (hasBeenCalled) {
return;
}
hasBeenCalled = true;
_;
hasBeenCalled = false;
}
function setTransactionData(bytes memory _txnData) public {
txnData = _txnData;
}
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool success) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
}
fallback() external skipIfReentered {
// Attampt to re-enter with the set txnData.
bool success = _executeCall(msg.sender, 0, txnData);
// Fail if the call succeeds because that means the re-entrancy was successful.
require(!success, "Re-entrancy was successful");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Lockable.sol";
import "./ReentrancyAttack.sol";
// Tests reentrancy guards defined in Lockable.sol.
// Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol.
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract SignedFixedPointTest {
using FixedPoint for FixedPoint.Signed;
using FixedPoint for int256;
using SafeMath for int256;
function wrapFromSigned(int256 a) external pure returns (uint256) {
return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue;
}
function wrapFromUnsigned(uint256 a) external pure returns (int256) {
return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue;
}
function wrapFromUnscaledInt(int256 a) external pure returns (int256) {
return FixedPoint.fromUnscaledInt(a).rawValue;
}
function wrapIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b));
}
function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(b);
}
function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b));
}
function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b));
}
function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Signed(b));
}
function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMin(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue;
}
function wrapMax(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue;
}
function wrapAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(b).rawValue;
}
function wrapSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) {
return a.sub(FixedPoint.Signed(b)).rawValue;
}
function wrapMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue;
}
function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(b).rawValue;
}
function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue;
}
function wrapDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue;
}
function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(b).rawValue;
}
function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) {
return a.div(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(int256 a, uint256 b) external pure returns (int256) {
return FixedPoint.Signed(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Testable.sol";
// TestableTest is derived from the abstract contract Testable for testing purposes.
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/Uniswap.sol";
/**
* @title Uniswap v2 Mock that allows manual price injection.
*/
contract UniswapMock is Uniswap {
function setPrice(uint112 reserve0, uint112 reserve1) external {
emit Sync(reserve0, reserve1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract UnsignedFixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Withdrawable.sol";
// WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes.
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title EmergencyShutdownable contract.
* @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable.
* This contract provides modifiers that can be used by children contracts to determine if the contract is
* in the shutdown state. The child contract is expected to implement the logic that happens
* once a shutdown occurs.
*/
abstract contract EmergencyShutdownable {
using SafeMath for uint256;
/****************************************
* EMERGENCY SHUTDOWN DATA STRUCTURES *
****************************************/
// Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered.
uint256 public emergencyShutdownTimestamp;
/****************************************
* MODIFIERS *
****************************************/
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
/****************************************
* EXTERNAL FUNCTIONS *
****************************************/
constructor() public {
emergencyShutdownTimestamp = 0;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _notEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp == 0);
}
function _isEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp != 0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/interfaces/StoreInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/AdministrateeInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is AdministrateeInterface, Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees virtual {
// Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the
// regular fee applied linearly since the last update. This implies that the compounding rate depends on the
// frequency of update transactions that have this modifier, and it never reaches the ideal of continuous
// compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the
// complexity of compounding data on-chain.
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) {
StoreInterface store = _getStore();
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral from which to pay fees.
if (collateralPool.isEqual(0)) {
// Note: set the lastPaymentTime in this case so the contract is credited for paying during periods when it
// has no locked collateral.
lastPaymentTime = time;
return totalPaid;
}
// Exit early if fees were already paid during this block.
if (lastPaymentTime == time) {
return totalPaid;
}
(FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) =
store.computeRegularFee(lastPaymentTime, time, collateralPool);
lastPaymentTime = time;
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return totalPaid;
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/**
* @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors.
* @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively
* pays all sponsors a pro-rata portion of the excess collateral.
* @dev This will revert if PfC is 0 and this contract's collateral balance > 0.
*/
function gulp() external nonReentrant() {
_gulp();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
// Note: revert reason removed to save bytecode.
require(collateralPool.isGreaterThan(amount));
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _gulp() internal {
FixedPoint.Unsigned memory currentPfc = _pfc();
FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
if (currentPfc.isLessThan(currentBalance)) {
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc));
}
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../common/implementation/FixedPoint.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
/**
* @title Financial product library contract
* @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom
* Financial product library implementations.
*/
abstract contract FinancialProductLibrary {
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Transforms a given oracle price using the financial product libraries transformation logic.
* @param oraclePrice input price returned by the DVM to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedOraclePrice input oraclePrice with the transformation function applied.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
virtual
returns (FixedPoint.Unsigned memory)
{
return oraclePrice;
}
/**
* @notice Transforms a given collateral requirement using the financial product libraries transformation logic.
* @param oraclePrice input price returned by DVM used to transform the collateral requirement.
* @param collateralRequirement input collateral requirement to be transformed.
* @return transformedCollateralRequirement input collateral requirement with the transformation function applied.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view virtual returns (FixedPoint.Unsigned memory) {
return collateralRequirement;
}
/**
* @notice Transforms a given price identifier using the financial product libraries transformation logic.
* @param priceIdentifier input price identifier defined for the financial contract.
* @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier.
* @return transformedPriceIdentifier input price identifier with the transformation function applied.
*/
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
virtual
returns (bytes32)
{
return priceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Pre-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made before expiration then a transformation is made to the identifier
* & if it is at or after expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration.
* @dev Note: a) Only the owner (deployer) of this library can set identifier transformations b) The identifier can't
* be set to blank. c) A transformed price can only be set once to prevent the deployer from changing it after the fact.
* d) financialProduct must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
onlyOwner
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is before contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return financialProductTransformedIdentifiers[msg.sender];
} else {
return identifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Structured Note Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If
* ETHUSD is above that strike, the contract pays out a given dollar amount of ETH.
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH
* If ETHUSD < $400 at expiry, token is redeemed for 1 ETH.
* If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM.
*/
contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => FixedPoint.Unsigned) financialProductStrikes;
/**
* @notice Enables the deployer of the library to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the structured note to be applied to the financial product.
* @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) financialProduct must exposes an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
onlyOwner
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the structured note payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThan(strike)) {
return FixedPoint.fromUnscaledUint(1);
} else {
// Token expires to be worth strike $ worth of collateral.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH.
return strike.div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price
* of the structured note is greater than the strike then the collateral requirement scales down accordingly.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If the price is less than the strike than the original collateral requirement is used.
if (oraclePrice.isLessThan(strike)) {
return collateralRequirement;
} else {
// If the price is more than the strike then the collateral requirement is scaled by the strike. For example
// a strike of $400 and a CR of 1.2 would yield:
// ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292
// ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96
return collateralRequirement.mul(strike.div(oraclePrice));
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/implementation/Constants.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../perpetual-multiparty/ConfigStoreInterface.sol";
import "./EmergencyShutdownable.sol";
import "./FeePayer.sol";
/**
* @title FundingRateApplier contract.
* @notice Provides funding rate payment functionality for the Perpetual contract.
*/
abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/****************************************
* FUNDING RATE APPLIER DATA STRUCTURES *
****************************************/
struct FundingRate {
// Current funding rate value.
FixedPoint.Signed rate;
// Identifier to retrieve the funding rate.
bytes32 identifier;
// Tracks the cumulative funding payments that have been paid to the sponsors.
// The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment).
// Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ...
// For example:
// The cumulativeFundingRateMultiplier should start at 1.
// If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01.
// If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201).
FixedPoint.Unsigned cumulativeMultiplier;
// Most recent time that the funding rate was updated.
uint256 updateTime;
// Most recent time that the funding rate was applied and changed the cumulative multiplier.
uint256 applicationTime;
// The time for the active (if it exists) funding rate proposal. 0 otherwise.
uint256 proposalTime;
}
FundingRate public fundingRate;
// Remote config store managed an owner.
ConfigStoreInterface public configStore;
/****************************************
* EVENTS *
****************************************/
event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward);
/****************************************
* MODIFIERS *
****************************************/
// This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate.
modifier fees override {
// Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the
// rate applied linearly since the last update. This implies that the compounding rate depends on the frequency
// of update transactions that have this modifier, and it never reaches the ideal of continuous compounding.
// This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of
// compounding data on-chain.
applyFundingRate();
_;
}
// Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees.
modifier regularFees {
payRegularFees();
_;
}
/**
* @notice Constructs the FundingRateApplier contract. Called by child contracts.
* @param _fundingRateIdentifier identifier that tracks the funding rate of this contract.
* @param _collateralAddress address of the collateral token.
* @param _finderAddress Finder used to discover financial-product-related contracts.
* @param _configStoreAddress address of the remote configuration store managed by an external owner.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress address of the timer contract in test envs, otherwise 0x0.
*/
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() {
uint256 currentTime = getCurrentTime();
fundingRate.updateTime = currentTime;
fundingRate.applicationTime = currentTime;
// Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are
// applied over time.
fundingRate.cumulativeMultiplier = _tokenScaling;
fundingRate.identifier = _fundingRateIdentifier;
configStore = ConfigStoreInterface(_configStoreAddress);
}
/**
* @notice This method takes 3 distinct actions:
* 1. Pays out regular fees.
* 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards.
* 3. Applies the prevailing funding rate over the most recent period.
*/
function applyFundingRate() public regularFees() nonReentrant() {
_applyEffectiveFundingRate();
}
/**
* @notice Proposes a new funding rate. Proposer receives a reward if correct.
* @param rate funding rate being proposed.
* @param timestamp time at which the funding rate was computed.
*/
function proposeNewRate(FixedPoint.Signed memory rate, uint256 timestamp)
external
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalBond)
{
require(fundingRate.proposalTime == 0, "Proposal in progress");
_validateFundingRate(rate);
// Timestamp must be after the last funding rate update time, within the last 30 minutes.
uint256 currentTime = getCurrentTime();
uint256 updateTime = fundingRate.updateTime;
require(
timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit),
"Invalid proposal time"
);
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Set up optimistic oracle.
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Note: requestPrice will revert if `timestamp` is less than the current block timestamp.
optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0);
totalBond = FixedPoint.Unsigned(
optimisticOracle.setBond(
identifier,
timestamp,
ancillaryData,
_pfc().mul(_getConfig().proposerBondPct).rawValue
)
);
// Pull bond from caller and send to optimistic oracle.
if (totalBond.isGreaterThan(0)) {
collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue);
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue);
}
optimisticOracle.proposePriceFor(
msg.sender,
address(this),
identifier,
timestamp,
ancillaryData,
rate.rawValue
);
}
// Returns a token amount scaled by the current funding rate multiplier.
// Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value.
function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
internal
view
returns (FixedPoint.Unsigned memory tokenDebt)
{
return rawTokenDebt.mul(fundingRate.cumulativeMultiplier);
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) {
return configStore.updateAndGetCurrentConfig();
}
function _getLatestFundingRate() internal returns (FixedPoint.Signed memory) {
uint256 proposalTime = fundingRate.proposalTime;
// If there is no pending proposal then return the current funding rate, otherwise
// check to see if we can update the funding rate.
if (proposalTime != 0) {
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Try to get the price from the optimistic oracle. This call will revert if the request has not resolved
// yet. If the request has not resolved yet, then we need to do additional checks to see if we should
// "forget" the pending proposal and allow new proposals to update the funding rate.
try optimisticOracle.getPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
// If successful, determine if the funding rate state needs to be updated.
// If the request is more recent than the last update then we should update it.
uint256 lastUpdateTime = fundingRate.updateTime;
if (proposalTime >= lastUpdateTime) {
// Update funding rates
fundingRate.rate = FixedPoint.Signed(price);
fundingRate.updateTime = proposalTime;
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0);
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer == address(0)) {
reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime));
if (reward.isGreaterThan(0)) {
_adjustCumulativeFeeMultiplier(reward, _pfc());
collateralCurrency.safeTransfer(request.proposer, reward.rawValue);
}
}
// This event will only be emitted after the fundingRate struct's "updateTime" has been set
// to the latest proposal's proposalTime, indicating that the proposal has been published.
// So, it suffices to just emit fundingRate.updateTime here.
emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue);
}
// Set proposal time to 0 since this proposal has now been resolved.
fundingRate.proposalTime = 0;
} catch {
// Stop tracking and allow other proposals to come in if:
// - The requester address is empty, indicating that the Oracle does not know about this funding rate
// request. This is possible if the Oracle is replaced while the price request is still pending.
// - The request has been disputed.
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer != address(0) || request.proposer == address(0)) {
fundingRate.proposalTime = 0;
}
}
}
return fundingRate.rate;
}
// Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the
// perpetual's security. For example, let's examine the case where the max and min funding rates
// are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a
// proposer who can deter honest proposers for 74 hours:
// 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%.
// How would attack work? Imagine that the market is very volatile currently and that the "true" funding
// rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500%
// (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding
// rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value.
function _validateFundingRate(FixedPoint.Signed memory rate) internal {
require(
rate.isLessThanOrEqual(_getConfig().maxFundingRate) &&
rate.isGreaterThanOrEqual(_getConfig().minFundingRate)
);
}
// Fetches a funding rate from the Store, determines the period over which to compute an effective fee,
// and multiplies the current multiplier by the effective fee.
// A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier.
// Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat
// values < 1 as "negative".
function _applyEffectiveFundingRate() internal {
// If contract is emergency shutdown, then the funding rate multiplier should no longer change.
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
_getLatestFundingRate(),
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
function _calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) {
// Note: this method uses named return variables to save a little bytecode.
// The overall formula that this function is performing:
// newCumulativeFundingRateMultiplier =
// (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier.
FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1);
// Multiply the per-second rate over the number of seconds that have elapsed to get the period rate.
FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds));
// Add one to create the multiplier to scale the existing fee multiplier.
FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate);
// Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned.
FixedPoint.Unsigned memory unsignedPeriodMultiplier =
FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0)));
// Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new
// cumulative funding rate multiplier.
newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier);
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(_getTokenAddress());
}
function _getTokenAddress() internal view virtual returns (address);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 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} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length of a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function getPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
interface ConfigStoreInterface {
// All of the configuration settings available for querying by a perpetual.
struct ConfigSettings {
// Liveness period (in seconds) for an update to currentConfig to become official.
uint256 timelockLiveness;
// Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%.
FixedPoint.Unsigned rewardRatePerSecond;
// Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%.
FixedPoint.Unsigned proposerBondPct;
// Maximum funding rate % per second that can be proposed.
FixedPoint.Signed maxFundingRate;
// Minimum funding rate % per second that can be proposed.
FixedPoint.Signed minFundingRate;
// Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest
// update time.
uint256 proposalTimePastLimit;
}
function updateAndGetCurrentConfig() external returns (ConfigSettings memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external override nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external override nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external override nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./SyntheticToken.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
/**
*Submitted for verification at Etherscan.io on 2017-12-12
*/
// Copyright (C) 2015, 2016, 2017 Dapphub
// 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/>.
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Copied from the verified code from Etherscan:
// https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code
// And then updated for Solidity version 0.6. Specific changes:
// * Change `function() public` into `receive() external` and `fallback() external`
// * Change `this.balance` to `address(this).balance`
// * Ran prettier
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
receive() external payable {
deposit();
}
fallback() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint256) {
return address(this).balance;
}
function approve(address guy, uint256 wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint256 wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(
address src,
address dst,
uint256 wad
) public returns (bool) {
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../common/FeePayer.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/implementation/ContractCreator.sol";
/**
* @title Token Deposit Box
* @notice This is a minimal example of a financial template that depends on price requests from the DVM.
* This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral.
* The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount.
* When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM.
* For simplicty, the user is constrained to have one outstanding withdrawal request at any given time.
* Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box,
* and final fees are charged on each price request.
*
* This example is intended to accompany a technical tutorial for how to integrate the DVM into a project.
* The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price
* requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework.
*
* The typical user flow would be:
* - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit
* box is therefore wETH.
* The user can subsequently make withdrawal requests for USD-denominated amounts of wETH.
* - User deposits 10 wETH into their deposit box.
* - User later requests to withdraw $100 USD of wETH.
* - DepositBox asks DVM for latest wETH/USD exchange rate.
* - DVM resolves the exchange rate at: 1 wETH is worth 200 USD.
* - DepositBox transfers 0.5 wETH to user.
*/
contract DepositBox is FeePayer, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/FinderInterface.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "./Registry.sol";
import "./Constants.sol";
/**
* @title Base contract for all financial contract creators
*/
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../interfaces/RegistryInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Registry for financial contracts and approved financial contract creators.
* @dev Maintains a whitelist of financial contract creators that are allowed
* to register new financial contracts and stores party members of a financial contract.
*/
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view override returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view override returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view override returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for a registry of contracts and contract creators.
*/
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Liquidatable.sol";
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./PricelessPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
address financialProductLibraryAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPct;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPct;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPct;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.minSponsorTokens,
params.timerAddress,
params.financialProductLibraryAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1), "CR must be more than 100%");
require(
params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1),
"Rewards are more than 100%"
);
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPct = params.disputeBondPct;
sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
disputerDisputeRewardPct = params.disputerDisputeRewardPct;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.PreDispute,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPct` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.PendingDispute;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePriceLiquidation(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.PreDispute) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/**
* @notice Accessor method to calculate a transformed collateral requirement using the finanical product library
specified during contract deployment. If no library was provided then no modification to the collateral requirement is done.
* @param price input price used as an input to transform the collateral requirement.
* @return transformedCollateralRequirement collateral requirement with transformation applied to it.
* @dev This method should never revert.
*/
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformCollateralRequirement(price);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return.
// If the liquidation is in the PendingDispute state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == PendingDispute and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.PendingDispute) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform
// Collateral requirement method applies a from the financial Product library to change the scaled the collateral
// requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change.
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice));
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)),
"Liquidation not withdrawable"
);
}
function _transformCollateralRequirement(FixedPoint.Unsigned memory price)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FeePayer.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
using Address for address;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend
// the functionality of the EMP to support a wider range of financial products.
FinancialProductLibrary public financialProductLibrary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
* @param _financialProductLibraryAddress Contract providing contract state transformations.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _financialProductLibraryAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime());
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
// Initialize the financialProductLibrary at the provided address.
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
)
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime()
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0);
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// Final fees do not need to be paid when sending a request to the optimistic oracle.
_requestOraclePriceExpiration(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress());
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePriceExpiration(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev TODO: This method does not account for any pending regular fees that have not yet been withdrawn
* from this contract, for example if the `lastPaymentTime != currentTime`. Future work should be to add
* logic to this method to account for any such pending fees.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
/**
* @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract
* deployment. If no library was provided then no modification to the price is done.
* @param price input price to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformPrice(price, requestTime);
}
/**
* @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified
* at contract deployment. If no library was provided then no modification to the identifier is done.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) {
return _transformPriceIdentifier(requestTime);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceExpiration(uint256 requestedTime) internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees();
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue);
optimisticOracle.requestPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData(),
collateralCurrency,
reward.rawValue // Reward is equal to the final fee
);
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.hasPrice(
address(this),
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
),
"Unresolved oracle price"
);
int256 optimisticOraclePrice =
optimisticOracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData());
// For now we don't want to deal with negative prices in positions.
if (optimisticOraclePrice < 0) {
optimisticOraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceLiquidation(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) {
if (!address(financialProductLibrary).isContract()) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(address(tokenCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./ExpiringMultiPartyLib.sol";
/**
* @title Expiring Multi Party Contract creator.
* @notice Factory contract to create and register new instances of expiring multiparty contracts.
* Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints
* that are applied to newly created expiring multi party contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address financialProductLibraryAddress;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
// Create a new synthetic token using the params.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method, then a default precision of 18 will be
// applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedExpiringMultiParty(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPct = params.disputeBondPct;
constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ExpiringMultiParty.sol";
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConfigStoreInterface.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it
* to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded
* by a privileged account and the upgraded changes are timelocked.
*/
contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* STORE DATA STRUCTURES *
****************************************/
// Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig
// if its liveness has expired.
ConfigStoreInterface.ConfigSettings private currentConfig;
// Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config.
ConfigStoreInterface.ConfigSettings public pendingConfig;
uint256 public pendingPassedTimestamp;
/****************************************
* EVENTS *
****************************************/
event ProposedNewConfigSettings(
address indexed proposer,
uint256 rewardRate,
uint256 proposerBond,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit,
uint256 proposalPassedTimestamp
);
event ChangedConfigSettings(
uint256 rewardRate,
uint256 proposerBond,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit
);
/****************************************
* MODIFIERS *
****************************************/
// Update config settings if possible.
modifier updateConfig() {
_updateConfig();
_;
}
/**
* @notice Construct the Config Store. An initial configuration is provided and set on construction.
* @param _initialConfig Configuration settings to initialize `currentConfig` with.
* @param _timerAddress Address of testable Timer contract.
*/
constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) {
_validateConfig(_initialConfig);
currentConfig = _initialConfig;
}
/**
* @notice Returns current config or pending config if pending liveness has expired.
* @return ConfigSettings config settings that calling financial contract should view as "live".
*/
function updateAndGetCurrentConfig()
external
override
updateConfig()
nonReentrant()
returns (ConfigStoreInterface.ConfigSettings memory)
{
return currentConfig;
}
/**
* @notice Propose new configuration settings. New settings go into effect after a liveness period passes.
* @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now.
* @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal.
*/
function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() {
_validateConfig(newConfig);
// Warning: This overwrites a pending proposal!
pendingConfig = newConfig;
// Use current config's liveness period to timelock this proposal.
pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness);
emit ProposedNewConfigSettings(
msg.sender,
newConfig.rewardRatePerSecond.rawValue,
newConfig.proposerBondPct.rawValue,
newConfig.timelockLiveness,
newConfig.maxFundingRate.rawValue,
newConfig.minFundingRate.rawValue,
newConfig.proposalTimePastLimit,
pendingPassedTimestamp
);
}
/**
* @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness.
*/
function publishPendingConfig() external nonReentrant() updateConfig() {}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
// If liveness has passed, publish proposed configuration settings.
if (_pendingProposalPassed()) {
currentConfig = pendingConfig;
_deletePendingConfig();
emit ChangedConfigSettings(
currentConfig.rewardRatePerSecond.rawValue,
currentConfig.proposerBondPct.rawValue,
currentConfig.timelockLiveness,
currentConfig.maxFundingRate.rawValue,
currentConfig.minFundingRate.rawValue,
currentConfig.proposalTimePastLimit
);
}
}
function _deletePendingConfig() internal {
delete pendingConfig;
pendingPassedTimestamp = 0;
}
function _pendingProposalPassed() internal view returns (bool) {
return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime());
}
// Use this method to constrain values with which you can set ConfigSettings.
function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure {
// We don't set limits on proposal timestamps because there are already natural limits:
// - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints.
// - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30
// mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time.
// Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself
// before a vulnerability drains its collateral.
require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness");
// The reward rate should be modified as needed to incentivize honest proposers appropriately.
// Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs
// = 0.0000033
FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7);
require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond");
// We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer
// were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer
// could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest
// proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their
// PfC for each proposal liveness window. The downside of not limiting this is that the config store owner
// can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the
// proposal bond based on the configuration's funding rate range like in this discussion:
// https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383
// We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude
// funding rates in extraordinarily volatile market situations. Note, that even though we do not bound
// the max/min, we still recommend that the deployer of this contract set the funding rate max/min values
// to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year].
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./PerpetualLiquidatable.sol";
/**
* @title Perpetual Multiparty Contract.
* @notice Convenient wrapper for Liquidatable.
*/
contract Perpetual is PerpetualLiquidatable {
/**
* @notice Constructs the Perpetual contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualLiquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PerpetualPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title PerpetualLiquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
*/
contract PerpetualLiquidatable is PerpetualPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PerpetualPositionManager only.
uint256 withdrawalLiveness;
address configStoreAddress;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
// Params specifically for PerpetualLiquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPct;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPct;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPct;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualPositionManager(
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.fundingRateIdentifier,
params.minSponsorTokens,
params.configStoreAddress,
params.tokenScaling,
params.timerAddress
)
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPct = params.disputeBondPct;
sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
disputerDisputeRewardPct = params.disputerDisputeRewardPct;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position
// are not funding-rate adjusted because the multiplier only affects their redemption value, not their
// notional.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.PreDispute,
liquidationTime: getCurrentTime(),
tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated),
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
_getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPct` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.PendingDispute;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
// TODO: Do we also need to apply some sort of funding rate adjustment to account for multiplier changes
// since liquidation time?
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.PreDispute) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return.
// If the liquidation is in the PendingDispute state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == PendingDispute and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.PendingDispute) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)),
"Liquidation not withdrawable"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FundingRateApplier.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PerpetualPositionManager is FundingRateApplier {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
/****************************************
* EVENTS *
****************************************/
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract.
* @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
*/
constructor(
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
bytes32 _fundingRateIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
// No pending withdrawal require message removed to save bytecode.
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0);
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens));
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
// Note: revert reason removed to save bytecode.
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this
* function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert.
if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) {
emergencyShutdownPrice = _getOracleEmergencyShutdownPrice();
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral =
_getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with
// the funding rate applied to the outstanding token debt.
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
_getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() {
// Note: revert reason removed to save bytecode.
require(msg.sender == _getFinancialContractsAdminAddress());
emergencyShutdownTimestamp = getCurrentTime();
_requestOraclePrice(emergencyShutdownTimestamp);
emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev TODO: This method does not account for any pending regular fees that have not yet been withdrawn
* from this contract, for example if the `lastPaymentTime != currentTime`. Future work should be to add
* logic to this method to account for any such pending fees.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the PerpetualPositionManager.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFundingRateAppliedTokenDebt(rawTokenDebt);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove);
require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens));
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
_getOracle().requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) {
return _getOraclePrice(emergencyShutdownTimestamp);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyCollateralizedPosition(address sponsor) internal view {
require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0));
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens);
}
function _getTokenAddress() internal view override returns (address) {
return address(tokenCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./PerpetualLib.sol";
import "./ConfigStore.sol";
/**
* @title Perpetual Contract creator.
* @notice Factory contract to create and register new instances of perpetual contracts.
* Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints
* that are applied to newly created contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract PerpetualCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* PERP CREATOR DATA STRUCTURES *
****************************************/
// Immutable params for perpetual contract.
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress);
event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress);
/**
* @notice Constructs the Perpetual contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of perpetual and registers it within the registry.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed contract.
*/
function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings)
public
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
// Create new config settings store for this contract and reset ownership to the deployer.
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
// Create a new synthetic token using the params.
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method,
// then a default precision of 18 will be applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore)));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedPerpetual(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(
Params memory params,
ExpandedIERC20 newTokenCurrency,
address configStore
) private view returns (Perpetual.ConstructorParams memory constructorParams) {
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want perpetual deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the perpetual unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// To avoid precision loss or overflows, prevent the token scaling from being too large or too small.
FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10
FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10
require(
params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling),
"Invalid tokenScaling"
);
// Input from function call.
constructorParams.configStoreAddress = configStore;
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.fundingRateIdentifier = params.fundingRateIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPct = params.disputeBondPct;
constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.tokenScaling = params.tokenScaling;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Perpetual.sol";
/**
* @title Provides convenient Perpetual Multi Party contract utilities.
* @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode.
*/
library PerpetualLib {
/**
* @notice Returns address of new Perpetual deployed with given `params` configuration.
* @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed Perpetual contract
*/
function deploy(Perpetual.ConstructorParams memory params) public returns (address) {
Perpetual derivative = new Perpetual(params);
return address(derivative);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
contract ExpiringMultiPartyMock is Testable {
using FixedPoint for FixedPoint.Unsigned;
FinancialProductLibrary public financialProductLibrary;
uint256 public expirationTimestamp;
FixedPoint.Unsigned public collateralRequirement;
bytes32 public priceIdentifier;
constructor(
address _financialProductLibraryAddress,
uint256 _expirationTimestamp,
FixedPoint.Unsigned memory _collateralRequirement,
bytes32 _priceIdentifier,
address _timerAddress
) public Testable(_timerAddress) {
expirationTimestamp = _expirationTimestamp;
collateralRequirement = _collateralRequirement;
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
priceIdentifier = _priceIdentifier;
}
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) {
if (address(financialProductLibrary) == address(0)) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
// Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations.
contract FinancialProductLibraryTest is FinancialProductLibrary {
FixedPoint.Unsigned public priceTransformationScalar;
FixedPoint.Unsigned public collateralRequirementTransformationScalar;
bytes32 public transformedPriceIdentifier;
bool public shouldRevert;
constructor(
FixedPoint.Unsigned memory _priceTransformationScalar,
FixedPoint.Unsigned memory _collateralRequirementTransformationScalar,
bytes32 _transformedPriceIdentifier
) public {
priceTransformationScalar = _priceTransformationScalar;
collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar;
transformedPriceIdentifier = _transformedPriceIdentifier;
}
// Set the mocked methods to revert to test failed library computation.
function setShouldRevert(bool _shouldRevert) public {
shouldRevert = _shouldRevert;
}
// Create a simple price transformation function that scales the input price by the scalar for testing.
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
returns (FixedPoint.Unsigned memory)
{
require(!shouldRevert, "set to always reverts");
return oraclePrice.mul(priceTransformationScalar);
}
// Create a simple collateral requirement transformation that doubles the input collateralRequirement.
function transformCollateralRequirement(
FixedPoint.Unsigned memory price,
FixedPoint.Unsigned memory collateralRequirement
) public view override returns (FixedPoint.Unsigned memory) {
require(!shouldRevert, "set to always reverts");
return collateralRequirement.mul(collateralRequirementTransformationScalar);
}
// Create a simple transformPriceIdentifier function that returns the transformed price identifier.
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
override
returns (bytes32)
{
require(!shouldRevert, "set to always reverts");
return transformedPriceIdentifier;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/FundingRateApplier.sol";
import "../../common/implementation/FixedPoint.sol";
// Implements FundingRateApplier internal methods to enable unit testing.
contract FundingRateApplierTest is FundingRateApplier {
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{}
function calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) public pure returns (FixedPoint.Unsigned memory) {
return
_calculateEffectiveFundingRate(
paymentPeriodSeconds,
fundingRatePerSecond,
currentCumulativeFundingRateMultiplier
);
}
// Required overrides.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) {
return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
}
function emergencyShutdown() external override {}
function remargin() external override {}
function _getTokenAddress() internal view override returns (address) {
return address(collateralCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Used internally by Truffle migrations.
* @dev See https://www.trufflesuite.com/docs/truffle/getting-started/running-migrations#initial-migration for details.
*/
contract Migrations {
address public owner;
uint256 public last_completed_migration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner) _;
}
function setCompleted(uint256 completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/FinderInterface.sol";
import "./Constants.sol";
/**
* @title Proxy to allow voting from another address.
* @dev Allows a UMA token holder to designate another address to vote on their behalf.
* Each voter must deploy their own instance of this contract.
*/
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingInterface.Commitment[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingInterface.Reveal[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingInterface.PendingRequest[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingInterface) {
return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "./VotingAncillaryInterface.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Withdrawable.sol";
import "./DesignatedVoting.sol";
/**
* @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances.
* @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract.
*/
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/AdministrateeInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Admin for financial contracts in the UMA system.
* @dev Allows appropriately permissioned admin roles to interact with financial contracts.
*/
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/FinderInterface.sol";
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces.
*/
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view override returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OracleInterface.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Takes proposals for certain governance actions and allows UMA token holders to vote on them.
*/
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/IdentifierWhitelistInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Stores a whitelist of supported identifiers that the oracle can provide prices for.
*/
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view override returns (bool) {
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/StoreInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OptimisticOracleInterface.sol";
import "./Constants.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/AddressWhitelist.sol";
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
*/
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param refund refund received in the case that refundOnDispute was enabled.
*/
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param price price that was resolved by the escalation process.
*/
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
/**
* @title Optimistic Oracle.
* @notice Pre-DVM escalation contract that allows faster settlement.
*/
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
// Finder to provide addresses for DVM contracts.
FinderInterface public finder;
// Default liveness value for all price requests.
uint256 public defaultLiveness;
/**
* @notice Constructor.
* @param _liveness default liveness applied to each price request.
* @param _finderAddress finder to use to get addresses of DVM contracts.
* @param _timerAddress address of the timer contract. Should be 0x0 in prod.
*/
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier");
require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency");
require(timestamp <= getCurrentTime(), "Timestamp in future");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee);
// This function returns the initial proposal bond for this request, which can be customized by calling
// setBond() with the same identifier and timestamp.
return finalFee.mul(2);
}
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested");
Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
// Total bond is the final fee + the newly set bond.
return bond.add(request.finalFee);
}
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setRefundOnDispute: Requested"
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true;
}
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setCustomLiveness: Requested"
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness;
}
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), "proposer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Requested,
"proposePriceFor: Requested"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
// If a custom liveness has been set, use it instead of the default.
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
// Event.
emit ProposePrice(requester, proposer, identifier, timestamp, ancillaryData, proposedPrice);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {}
}
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice);
}
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
totalBond = request.bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
if (finalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), finalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(finalFee));
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
// Compute refund.
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
// Event.
emit DisputePrice(requester, request.proposer, disputer, identifier, timestamp, ancillaryData);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {}
}
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function getPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice;
}
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed;
}
return
_getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester))
? State.Resolved
: State.Disputed;
}
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return state == State.Settled || state == State.Resolved || state == State.Expired;
}
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stampped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) {
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData));
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
// Set it to settled so this function can never be entered again.
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
// In the expiry case, just pay back the proposer's bond and final fee along with the reward.
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
// In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward).
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
payout = request.bond.mul(2).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout);
} else {
revert("_settle: not settleable");
}
// Event.
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
// Callback.
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, "Liveness too large");
require(_liveness > 0, "Liveness cannot be 0");
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it.
function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) {
return abi.encodePacked(ancillaryData, "OptimisticOracle", requester);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Computes vote results.
* @dev The result is the mode of the added votes. Otherwise, the vote is unresolved.
*/
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/StoreInterface.sol";
/**
* @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token.
*/
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Governor.sol";
// GovernorTest exposes internal methods in the Governor for testing.
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/AdministrateeInterface.sol";
// A mock implementation of AdministrateeInterface, taking the place of a financial contract.
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
function pfc() external view override returns (FixedPoint.Unsigned memory) {
return FixedPoint.fromUnscaledUint(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../OptimisticOracle.sol";
// This is just a test contract to make requests to the optimistic oracle.
contract OptimisticRequesterTest is OptimisticRequester {
OptimisticOracle optimisticOracle;
bool public shouldRevert = false;
// State variables to track incoming calls.
bytes32 public identifier;
uint256 public timestamp;
bytes public ancillaryData;
uint256 public refund;
int256 public price;
constructor(OptimisticOracle _optimisticOracle) public {
optimisticOracle = _optimisticOracle;
}
function requestPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
IERC20 currency,
uint256 reward
) external {
currency.approve(address(optimisticOracle), reward);
optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward);
}
function getPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external returns (int256) {
return optimisticOracle.getPrice(_identifier, _timestamp, _ancillaryData);
}
function setBond(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 bond
) external {
optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond);
}
function setRefundOnDispute(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external {
optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData);
}
function setCustomLiveness(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 customLiveness
) external {
optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness);
}
function setRevert(bool _shouldRevert) external {
shouldRevert = _shouldRevert;
}
function clearState() external {
delete identifier;
delete timestamp;
delete refund;
delete price;
}
function priceProposed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
}
function priceDisputed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 _refund
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
refund = _refund;
}
function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _price
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
price = _price;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ResultComputation.sol";
import "../../../common/implementation/FixedPoint.sol";
// Wraps the library ResultComputation for testing purposes.
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../interfaces/VotingInterface.sol";
import "../VoteTiming.sol";
// Wraps the library VoteTiming for testing purposes.
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/VotingInterface.sol";
/**
* @title Library to compute rounds and phases for an equal length commit-reveal voting cycle.
*/
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Voting.sol";
import "../../../common/implementation/FixedPoint.sol";
// Test contract used to access internal variables in the Voting contract.
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "./Registry.sol";
import "./ResultComputation.sol";
import "./VoteTiming.sol";
import "./VotingToken.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title Voting system for Oracle.
* @dev Handles receiving and resolving price requests via a commit-reveal voting scheme.
*/
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface, // Interface to support ancillary data with price requests.
VotingInterface,
VotingAncillaryInterface // Interface to support ancillary data with voting rounds.
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
// Max length in bytes of ancillary data that can be appended to a price request.
// As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily
// comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to
// storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function
// well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here:
// - https://etherscan.io/chart/gaslimit
// - https://github.com/djrtwo/evm-opcode-gas-costs
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported. The length of the ancillary data
* is limited such that this method abides by the EVM transaction gas limit.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, "");
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
return hasPrice(identifier, time, "");
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
return getPrice(identifier, time, "");
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = "";
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit,
"Cannot commit in reveal phase"
);
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, "", hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// Scoping to get rid of a stack too deep error.
{
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) ==
voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
}
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, "", salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, "", hash);
commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = "";
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = "";
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = "";
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
/**
* @title Ownership of this token allows a voter to respond to price requests.
* @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards.
*/
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
* stonkbase.org
* tw StonkBase
*/
constructor() public ExpandedERC20("StonkBase", "SBF", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
pragma solidity ^0.6.0;
import "../math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.6.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);
}
}
pragma solidity ^0.6.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 {
/**
* @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) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// 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(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* 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));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "./VotingToken.sol";
/**
* @title Migration contract for VotingTokens.
* @dev Handles migrating token holders from one token to the next.
*/
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracleAncillary is OracleAncillaryInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time, ancillaryData));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) external {
verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time][ancillaryData];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data.
abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/VotingInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data.
abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip15Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
}
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set current Voting contract to migrated.
existingVoting.setMigrated(newVoting);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
} | Fetches a funding rate from the Store, determines the period over which to compute an effective fee, and multiplies the current multiplier by the effective fee. A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat values < 1 as "negative". If contract is emergency shutdown, then the funding rate multiplier should no longer change. | function _applyEffectiveFundingRate() internal {
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
_getLatestFundingRate(),
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
| 591,032 |
./partial_match/1/0xD72f617b374292bC45dB1be95EE7cf69D39219A2/sources/LendfMeData.sol | if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. else the user meets the collateral ratio and has account liquidity. accountShortfall = borrows - supplies accountLiquidity = supplies - borrows | function calculateAccountLiquidity(address userAddress) internal view returns (Error, Exp memory, Exp memory) {
Error err;
uint sumSupplyValuesMantissa;
uint sumBorrowValuesMantissa;
(err, sumSupplyValuesMantissa, sumBorrowValuesMantissa) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
}
Exp memory result;
if (err != Error.NO_ERROR) {
}
if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) {
(err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal);
(err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal);
}
}
| 2,824,412 |
./full_match/43114/0x21499643B1Dd73168807eb1eDfa0b43b50b8F30F/sources/cache/solpp-generated-contracts/StakingV1.sol | @inheritdoc IStakingV1 | function protocolMemberUnstake(
address _stakerAddress,
uint256 _amount,
uint256 _unstakingPeriod
) external onlyProtocolMember whenNotPaused {
_unstake(_stakerAddress, _amount, _unstakingPeriod);
}
| 4,624,960 |
./partial_match/42/0xD93f022e857A97B646DC4e6Fa447f29Ab177C633/sources/UniverseChart.sol | Utils function to change default company address _referrer The referrer address;/ | function register(address _referrer) external {
require(
accounts[_referrer].id != 0 || _referrer == accountIds[0],
"Invalid referrer address"
);
require(accounts[msg.sender].id == 0, "Account has been registered");
Account memory account =
accounts[msg.sender] = account;
accountIds[lastId] = msg.sender;
emit Register(lastId++, msg.sender, _referrer);
}
| 8,855,686 |
./full_match/43113/0x1F760267Ccb23AB0895358a92b1DB5f27B7971Ad/sources/fMesoMasterChef.sol | Only update before start of farm | function updateStartBlock(uint256 _newStartBlock) external onlyOwner {
require(block.number < startBlock, "FARM ALREADY STARTED");
require(block.number < _newStartBlock, "INCORRECT INPUT");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
pool.lastRewardBlock = _newStartBlock;
}
startBlock = _newStartBlock;
emit UpdateStartBlock(startBlock);
}
| 7,142,303 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@bancor/contracts-solidity/solidity/contracts/token/interfaces/IDSToken.sol";
struct PoolProgram {
uint256 startTime;
uint256 endTime;
uint256 rewardRate;
IERC20[2] reserveTokens;
uint32[2] rewardShares;
}
struct PoolRewards {
uint256 lastUpdateTime;
uint256 rewardPerToken;
uint256 totalClaimedRewards;
}
struct ProviderRewards {
uint256 rewardPerToken;
uint256 pendingBaseRewards;
uint256 totalClaimedRewards;
uint256 effectiveStakingTime;
uint256 baseRewardsDebt;
uint32 baseRewardsDebtMultiplier;
}
interface IStakingRewardsStore {
function isPoolParticipating(IDSToken poolToken) external view returns (bool);
function isReserveParticipating(IDSToken poolToken, IERC20 reserveToken) external view returns (bool);
function addPoolProgram(
IDSToken poolToken,
IERC20[2] calldata reserveTokens,
uint32[2] calldata rewardShares,
uint256 endTime,
uint256 rewardRate
) external;
function removePoolProgram(IDSToken poolToken) external;
function setPoolProgramEndTime(IDSToken poolToken, uint256 newEndTime) external;
function poolProgram(IDSToken poolToken)
external
view
returns (
uint256,
uint256,
uint256,
IERC20[2] memory,
uint32[2] memory
);
function poolPrograms()
external
view
returns (
IDSToken[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
IERC20[2][] memory,
uint32[2][] memory
);
function poolRewards(IDSToken poolToken, IERC20 reserveToken)
external
view
returns (
uint256,
uint256,
uint256
);
function updatePoolRewardsData(
IDSToken poolToken,
IERC20 reserveToken,
uint256 lastUpdateTime,
uint256 rewardPerToken,
uint256 totalClaimedRewards
) external;
function providerRewards(
address provider,
IDSToken poolToken,
IERC20 reserveToken
)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint32
);
function updateProviderRewardsData(
address provider,
IDSToken poolToken,
IERC20 reserveToken,
uint256 rewardPerToken,
uint256 pendingBaseRewards,
uint256 totalClaimedRewards,
uint256 effectiveStakingTime,
uint256 baseRewardsDebt,
uint32 baseRewardsDebtMultiplier
) external;
function updateProviderLastClaimTime(address provider) external;
function providerLastClaimTime(address provider) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@bancor/token-governance/contracts/ITokenGovernance.sol";
import "@bancor/contracts-solidity/solidity/contracts/utility/ContractRegistryClient.sol";
import "@bancor/contracts-solidity/solidity/contracts/utility/Utils.sol";
import "@bancor/contracts-solidity/solidity/contracts/utility/Time.sol";
import "@bancor/contracts-solidity/solidity/contracts/utility/interfaces/ICheckpointStore.sol";
import "@bancor/contracts-solidity/solidity/contracts/liquidity-protection/interfaces/ILiquidityProtection.sol";
import "@bancor/contracts-solidity/solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionEventsSubscriber.sol";
import "./IStakingRewardsStore.sol";
/**
* @dev This contract manages the distribution of the staking rewards
*/
contract StakingRewards is ILiquidityProtectionEventsSubscriber, AccessControl, Time, Utils, ContractRegistryClient {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// the role is used to globally govern the contract and its governing roles.
bytes32 public constant ROLE_SUPERVISOR = keccak256("ROLE_SUPERVISOR");
// the roles is used to restrict who is allowed to publish liquidity protection events.
bytes32 public constant ROLE_PUBLISHER = keccak256("ROLE_PUBLISHER");
// the roles is used to restrict who is allowed to update/cache provider rewards.
bytes32 public constant ROLE_UPDATER = keccak256("ROLE_UPDATER");
uint32 private constant PPM_RESOLUTION = 1000000;
// the weekly 25% increase of the rewards multiplier (in units of PPM).
uint32 private constant MULTIPLIER_INCREMENT = PPM_RESOLUTION / 4;
// the maximum weekly 200% rewards multiplier (in units of PPM).
uint32 private constant MAX_MULTIPLIER = PPM_RESOLUTION + MULTIPLIER_INCREMENT * 4;
// since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases
// where the total amount in the denominator is higher than the product of the rewards rate and staking duration. In
// order to avoid this imprecision, we will amplify the reward rate by the units amount.
uint256 private constant REWARD_RATE_FACTOR = 1e18;
uint256 private constant MAX_UINT256 = uint256(-1);
// the staking rewards settings.
IStakingRewardsStore private immutable _store;
// the permissioned wrapper around the network token which should allow this contract to mint staking rewards.
ITokenGovernance private immutable _networkTokenGovernance;
// the address of the network token.
IERC20 private immutable _networkToken;
// the checkpoint store recording last protected position removal times.
ICheckpointStore private immutable _lastRemoveTimes;
/**
* @dev triggered when pending rewards are being claimed
*
* @param provider the owner of the liquidity
* @param amount the total rewards amount
*/
event RewardsClaimed(address indexed provider, uint256 amount);
/**
* @dev triggered when pending rewards are being staked in a pool
*
* @param provider the owner of the liquidity
* @param poolToken the pool token representing the rewards pool
* @param amount the reward amount
* @param newId the ID of the new position
*/
event RewardsStaked(address indexed provider, IDSToken indexed poolToken, uint256 amount, uint256 indexed newId);
/**
* @dev initializes a new StakingRewards contract
*
* @param store the staking rewards store
* @param networkTokenGovernance the permissioned wrapper around the network token
* @param lastRemoveTimes the checkpoint store recording last protected position removal times
* @param registry address of a contract registry contract
*/
constructor(
IStakingRewardsStore store,
ITokenGovernance networkTokenGovernance,
ICheckpointStore lastRemoveTimes,
IContractRegistry registry
)
public
validAddress(address(store))
validAddress(address(networkTokenGovernance))
validAddress(address(lastRemoveTimes))
ContractRegistryClient(registry)
{
_store = store;
_networkTokenGovernance = networkTokenGovernance;
_networkToken = networkTokenGovernance.token();
_lastRemoveTimes = lastRemoveTimes;
// set up administrative roles.
_setRoleAdmin(ROLE_SUPERVISOR, ROLE_SUPERVISOR);
_setRoleAdmin(ROLE_PUBLISHER, ROLE_SUPERVISOR);
_setRoleAdmin(ROLE_UPDATER, ROLE_SUPERVISOR);
// allow the deployer to initially govern the contract.
_setupRole(ROLE_SUPERVISOR, _msgSender());
}
modifier onlyPublisher() {
_onlyPublisher();
_;
}
function _onlyPublisher() internal view {
require(hasRole(ROLE_PUBLISHER, msg.sender), "ERR_ACCESS_DENIED");
}
modifier onlyUpdater() {
_onlyUpdater();
_;
}
function _onlyUpdater() internal view {
require(hasRole(ROLE_UPDATER, msg.sender), "ERR_ACCESS_DENIED");
}
/**
* @dev liquidity provision notification callback. The callback should be called *before* the liquidity is added in
* the LP contract.
*
* @param provider the owner of the liquidity
* @param poolAnchor the pool token representing the rewards pool
* @param reserveToken the reserve token of the added liquidity
*/
function onAddingLiquidity(
address provider,
IConverterAnchor poolAnchor,
IERC20 reserveToken,
uint256, /* poolAmount */
uint256 /* reserveAmount */
) external override onlyPublisher validExternalAddress(provider) {
IDSToken poolToken = IDSToken(address(poolAnchor));
PoolProgram memory program = poolProgram(poolToken);
if (program.startTime == 0) {
return;
}
updateRewards(provider, poolToken, reserveToken, program, liquidityProtectionStats());
}
/**
* @dev liquidity removal callback. The callback must be called *before* the liquidity is removed in the LP
* contract
*
* @param provider the owner of the liquidity
* @param poolAnchor the pool token representing the rewards pool
*/
function onRemovingLiquidity(
uint256, /* id */
address provider,
IConverterAnchor poolAnchor,
IERC20, /* reserveToken */
uint256, /* poolAmount */
uint256 /* reserveAmount */
) external override onlyPublisher validExternalAddress(provider) {
IDSToken poolToken = IDSToken(address(poolAnchor));
PoolProgram memory program = poolProgram(poolToken);
if (program.startTime == 0) {
return;
}
ILiquidityProtectionStats lpStats = liquidityProtectionStats();
// make sure that all pending rewards are properly stored for future claims, with retroactive rewards
// multipliers.
storeRewards(provider, lpStats.providerPools(provider), lpStats);
}
/**
* @dev returns the staking rewards store
*
* @return the staking rewards store
*/
function store() external view returns (IStakingRewardsStore) {
return _store;
}
/**
* @dev returns the network token governance
*
* @return the network token governance
*/
function networkTokenGovernance() external view returns (ITokenGovernance) {
return _networkTokenGovernance;
}
/**
* @dev returns the last remove times
*
* @return the last remove times
*/
function lastRemoveTimes() external view returns (ICheckpointStore) {
return _lastRemoveTimes;
}
/**
* @dev returns specific provider's pending rewards for all participating pools
*
* @param provider the owner of the liquidity
*
* @return all pending rewards
*/
function pendingRewards(address provider) external view returns (uint256) {
return pendingRewards(provider, liquidityProtectionStats());
}
/**
* @dev returns specific provider's pending rewards for a specific participating pool/reserve
*
* @param provider the owner of the liquidity
* @param poolToken the pool token representing the new rewards pool
* @param reserveToken the reserve token representing the liquidity in the pool
*
* @return all pending rewards
*/
function pendingReserveRewards(
address provider,
IDSToken poolToken,
IERC20 reserveToken
) external view returns (uint256) {
PoolProgram memory program = poolProgram(poolToken);
return pendingRewards(provider, poolToken, reserveToken, program, liquidityProtectionStats());
}
/**
* @dev returns specific provider's pending rewards for all participating pools
*
* @param provider the owner of the liquidity
* @param lpStats liquidity protection statistics store
*
* @return all pending rewards
*/
function pendingRewards(address provider, ILiquidityProtectionStats lpStats) private view returns (uint256) {
return pendingRewards(provider, lpStats.providerPools(provider), lpStats);
}
/**
* @dev returns specific provider's pending rewards for a specific list of participating pools
*
* @param provider the owner of the liquidity
* @param poolTokens the list of participating pools to query
* @param lpStats liquidity protection statistics store
*
* @return all pending rewards
*/
function pendingRewards(
address provider,
IDSToken[] memory poolTokens,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
uint256 reward = 0;
uint256 length = poolTokens.length;
for (uint256 i = 0; i < length; ++i) {
uint256 poolReward = pendingRewards(provider, poolTokens[i], lpStats);
reward = reward.add(poolReward);
}
return reward;
}
/**
* @dev returns specific provider's pending rewards for a specific pool
*
* @param provider the owner of the liquidity
* @param poolToken the pool to query
* @param lpStats liquidity protection statistics store
*
* @return reward all pending rewards
*/
function pendingRewards(
address provider,
IDSToken poolToken,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
uint256 reward = 0;
PoolProgram memory program = poolProgram(poolToken);
for (uint256 i = 0; i < program.reserveTokens.length; ++i) {
uint256 reserveReward = pendingRewards(provider, poolToken, program.reserveTokens[i], program, lpStats);
reward = reward.add(reserveReward);
}
return reward;
}
/**
* @dev returns specific provider's pending rewards for a specific pool/reserve
*
* @param provider the owner of the liquidity
* @param poolToken the pool to query
* @param reserveToken the reserve token representing the liquidity in the pool
* @param program the pool program info
* @param lpStats liquidity protection statistics store
*
* @return reward all pending rewards
*/
function pendingRewards(
address provider,
IDSToken poolToken,
IERC20 reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
// calculate the new reward rate per-token
PoolRewards memory poolRewardsData = poolRewards(poolToken, reserveToken);
// rewardPerToken must be calculated with the previous value of lastUpdateTime.
poolRewardsData.rewardPerToken = rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats);
poolRewardsData.lastUpdateTime = Math.min(time(), program.endTime);
// update provider's rewards with the newly claimable base rewards and the new reward rate per-token.
ProviderRewards memory providerRewards = providerRewards(provider, poolToken, reserveToken);
// if this is the first liquidity provision - set the effective staking time to the current time.
if (
providerRewards.effectiveStakingTime == 0 &&
lpStats.totalProviderAmount(provider, poolToken, reserveToken) == 0
) {
providerRewards.effectiveStakingTime = time();
}
// pendingBaseRewards must be calculated with the previous value of providerRewards.rewardPerToken.
providerRewards.pendingBaseRewards = providerRewards.pendingBaseRewards.add(
baseRewards(provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats)
);
providerRewards.rewardPerToken = poolRewardsData.rewardPerToken;
// get full rewards and the respective rewards multiplier.
(uint256 fullReward, ) =
fullRewards(provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats);
return fullReward;
}
/**
* @dev claims specific provider's pending rewards for a specific list of participating pools
*
* @param provider the owner of the liquidity
* @param poolTokens the list of participating pools to query
* @param maxAmount an optional bound on the rewards to claim (when partial claiming is required)
* @param lpStats liquidity protection statistics store
* @param resetStakingTime true to reset the effective staking time, false to keep it as is
*
* @return all pending rewards
*/
function claimPendingRewards(
address provider,
IDSToken[] memory poolTokens,
uint256 maxAmount,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private returns (uint256) {
uint256 reward = 0;
uint256 length = poolTokens.length;
for (uint256 i = 0; i < length && maxAmount > 0; ++i) {
uint256 poolReward = claimPendingRewards(provider, poolTokens[i], maxAmount, lpStats, resetStakingTime);
reward = reward.add(poolReward);
if (maxAmount != MAX_UINT256) {
maxAmount = maxAmount.sub(poolReward);
}
}
return reward;
}
/**
* @dev claims specific provider's pending rewards for a specific pool
*
* @param provider the owner of the liquidity
* @param poolToken the pool to query
* @param maxAmount an optional bound on the rewards to claim (when partial claiming is required)
* @param lpStats liquidity protection statistics store
* @param resetStakingTime true to reset the effective staking time, false to keep it as is
*
* @return reward all pending rewards
*/
function claimPendingRewards(
address provider,
IDSToken poolToken,
uint256 maxAmount,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private returns (uint256) {
uint256 reward = 0;
PoolProgram memory program = poolProgram(poolToken);
for (uint256 i = 0; i < program.reserveTokens.length && maxAmount > 0; ++i) {
uint256 reserveReward =
claimPendingRewards(
provider,
poolToken,
program.reserveTokens[i],
program,
maxAmount,
lpStats,
resetStakingTime
);
reward = reward.add(reserveReward);
if (maxAmount != MAX_UINT256) {
maxAmount = maxAmount.sub(reserveReward);
}
}
return reward;
}
/**
* @dev claims specific provider's pending rewards for a specific pool/reserve
*
* @param provider the owner of the liquidity
* @param poolToken the pool to query
* @param reserveToken the reserve token representing the liquidity in the pool
* @param program the pool program info
* @param maxAmount an optional bound on the rewards to claim (when partial claiming is required)
* @param lpStats liquidity protection statistics store
* @param resetStakingTime true to reset the effective staking time, false to keep it as is
*
* @return reward all pending rewards
*/
function claimPendingRewards(
address provider,
IDSToken poolToken,
IERC20 reserveToken,
PoolProgram memory program,
uint256 maxAmount,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private returns (uint256) {
// update all provider's pending rewards, in order to apply retroactive reward multipliers.
(PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards) =
updateRewards(provider, poolToken, reserveToken, program, lpStats);
// get full rewards and the respective rewards multiplier.
(uint256 fullReward, uint32 multiplier) =
fullRewards(provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats);
// mark any debt as repaid.
providerRewards.baseRewardsDebt = 0;
providerRewards.baseRewardsDebtMultiplier = 0;
if (maxAmount != MAX_UINT256 && fullReward > maxAmount) {
// get the amount of the actual base rewards that were claimed.
if (multiplier == PPM_RESOLUTION) {
providerRewards.baseRewardsDebt = fullReward.sub(maxAmount);
} else {
providerRewards.baseRewardsDebt = fullReward.sub(maxAmount).mul(PPM_RESOLUTION).div(multiplier);
}
// store the current multiplier for future retroactive rewards correction.
providerRewards.baseRewardsDebtMultiplier = multiplier;
// grant only maxAmount rewards.
fullReward = maxAmount;
}
// update pool rewards data total claimed rewards.
_store.updatePoolRewardsData(
poolToken,
reserveToken,
poolRewardsData.lastUpdateTime,
poolRewardsData.rewardPerToken,
poolRewardsData.totalClaimedRewards.add(fullReward)
);
// update provider rewards data with the remaining pending rewards and if needed, set the effective
// staking time to the timestamp of the current block.
_store.updateProviderRewardsData(
provider,
poolToken,
reserveToken,
providerRewards.rewardPerToken,
0,
providerRewards.totalClaimedRewards.add(fullReward),
resetStakingTime ? time() : providerRewards.effectiveStakingTime,
providerRewards.baseRewardsDebt,
providerRewards.baseRewardsDebtMultiplier
);
return fullReward;
}
/**
* @dev returns the current rewards multiplier for a provider in a given pool
*
* @param provider the owner of the liquidity
* @param poolToken the pool to query
* @param reserveToken the reserve token representing the liquidity in the pool
*
* @return rewards multiplier
*/
function rewardsMultiplier(
address provider,
IDSToken poolToken,
IERC20 reserveToken
) external view returns (uint32) {
ProviderRewards memory providerRewards = providerRewards(provider, poolToken, reserveToken);
PoolProgram memory program = poolProgram(poolToken);
return rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program);
}
/**
* @dev returns specific provider's total claimed rewards from all participating pools
*
* @param provider the owner of the liquidity
*
* @return total claimed rewards from all participating pools
*/
function totalClaimedRewards(address provider) external view returns (uint256) {
uint256 totalRewards = 0;
ILiquidityProtectionStats lpStats = liquidityProtectionStats();
IDSToken[] memory poolTokens = lpStats.providerPools(provider);
for (uint256 i = 0; i < poolTokens.length; ++i) {
IDSToken poolToken = poolTokens[i];
PoolProgram memory program = poolProgram(poolToken);
for (uint256 j = 0; j < program.reserveTokens.length; ++j) {
IERC20 reserveToken = program.reserveTokens[j];
ProviderRewards memory providerRewards = providerRewards(provider, poolToken, reserveToken);
totalRewards = totalRewards.add(providerRewards.totalClaimedRewards);
}
}
return totalRewards;
}
/**
* @dev claims pending rewards from all participating pools
*
* @return all claimed rewards
*/
function claimRewards() external returns (uint256) {
return claimRewards(msg.sender, liquidityProtectionStats());
}
/**
* @dev claims specific provider's pending rewards from all participating pools
*
* @param provider the owner of the liquidity
* @param lpStats liquidity protection statistics store
*
* @return all claimed rewards
*/
function claimRewards(address provider, ILiquidityProtectionStats lpStats) private returns (uint256) {
return claimRewards(provider, lpStats.providerPools(provider), MAX_UINT256, lpStats);
}
/**
* @dev claims specific provider's pending rewards for a specific list of participating pools
*
* @param provider the owner of the liquidity
* @param poolTokens the list of participating pools to query
* @param maxAmount an optional cap on the rewards to claim
* @param lpStats liquidity protection statistics store
*
* @return all pending rewards
*/
function claimRewards(
address provider,
IDSToken[] memory poolTokens,
uint256 maxAmount,
ILiquidityProtectionStats lpStats
) private returns (uint256) {
uint256 amount = claimPendingRewards(provider, poolTokens, maxAmount, lpStats, true);
if (amount == 0) {
return amount;
}
// make sure to update the last claim time so that it'll be taken into effect when calculating the next rewards
// multiplier.
_store.updateProviderLastClaimTime(provider);
// mint the reward tokens directly to the provider.
_networkTokenGovernance.mint(provider, amount);
emit RewardsClaimed(provider, amount);
return amount;
}
/**
* @dev stakes specific pending rewards from all participating pools
*
* @param maxAmount an optional cap on the rewards to stake
* @param poolToken the pool token representing the new rewards pool
* @return all staked rewards and the ID of the new position
*/
function stakeRewards(uint256 maxAmount, IDSToken poolToken) external returns (uint256, uint256) {
return stakeRewards(msg.sender, maxAmount, poolToken, liquidityProtectionStats());
}
/**
* @dev stakes specific provider's pending rewards from all participating pools
*
* @param provider the owner of the liquidity
* @param maxAmount an optional cap on the rewards to stake
* @param poolToken the pool token representing the new rewards pool
* @param lpStats liquidity protection statistics store
*
* @return all staked rewards and the ID of the new position
*/
function stakeRewards(
address provider,
uint256 maxAmount,
IDSToken poolToken,
ILiquidityProtectionStats lpStats
) private returns (uint256, uint256) {
return stakeRewards(provider, lpStats.providerPools(provider), maxAmount, poolToken, lpStats);
}
/**
* @dev claims and stakes specific provider's pending rewards for a specific list of participating pools
*
* @param provider the owner of the liquidity
* @param poolTokens the list of participating pools to query
* @param newPoolToken the pool token representing the new rewards pool
* @param maxAmount an optional cap on the rewards to stake
* @param lpStats liquidity protection statistics store
*
* @return all staked rewards and the ID of the new position
*/
function stakeRewards(
address provider,
IDSToken[] memory poolTokens,
uint256 maxAmount,
IDSToken newPoolToken,
ILiquidityProtectionStats lpStats
) private returns (uint256, uint256) {
uint256 amount = claimPendingRewards(provider, poolTokens, maxAmount, lpStats, false);
if (amount == 0) {
return (amount, 0);
}
// approve the LiquidityProtection contract to pull the rewards.
ILiquidityProtection liquidityProtection = liquidityProtection();
address liquidityProtectionAddress = address(liquidityProtection);
uint256 allowance = _networkToken.allowance(address(this), liquidityProtectionAddress);
if (allowance < amount) {
if (allowance > 0) {
_networkToken.safeApprove(liquidityProtectionAddress, 0);
}
_networkToken.safeApprove(liquidityProtectionAddress, amount);
}
// mint the reward tokens directly to the staking contract, so that the LiquidityProtection could pull the
// rewards and attribute them to the provider.
_networkTokenGovernance.mint(address(this), amount);
uint256 newId =
liquidityProtection.addLiquidityFor(provider, newPoolToken, IERC20(address(_networkToken)), amount);
// please note, that in order to incentivize staking, we won't be updating the time of the last claim, thus
// preserving the rewards bonus multiplier.
emit RewardsStaked(provider, newPoolToken, amount, newId);
return (amount, newId);
}
/**
* @dev store pending rewards for a list of providers in a specific pool for future claims
*
* @param providers owners of the liquidity
* @param poolToken the participating pool to update
*/
function storePoolRewards(address[] calldata providers, IDSToken poolToken) external onlyUpdater {
ILiquidityProtectionStats lpStats = liquidityProtectionStats();
PoolProgram memory program = poolProgram(poolToken);
for (uint256 i = 0; i < providers.length; ++i) {
for (uint256 j = 0; j < program.reserveTokens.length; ++j) {
storeRewards(providers[i], poolToken, program.reserveTokens[j], program, lpStats, false);
}
}
}
/**
* @dev store specific provider's pending rewards for future claims
*
* @param provider the owner of the liquidity
* @param poolTokens the list of participating pools to query
* @param lpStats liquidity protection statistics store
*
*/
function storeRewards(
address provider,
IDSToken[] memory poolTokens,
ILiquidityProtectionStats lpStats
) private {
for (uint256 i = 0; i < poolTokens.length; ++i) {
IDSToken poolToken = poolTokens[i];
PoolProgram memory program = poolProgram(poolToken);
for (uint256 j = 0; j < program.reserveTokens.length; ++j) {
storeRewards(provider, poolToken, program.reserveTokens[j], program, lpStats, true);
}
}
}
/**
* @dev store specific provider's pending rewards for future claims
*
* @param provider the owner of the liquidity
* @param poolToken the participating pool to query
* @param reserveToken the reserve token representing the liquidity in the pool
* @param program the pool program info
* @param lpStats liquidity protection statistics store
* @param resetStakingTime true to reset the effective staking time, false to keep it as is
*
*/
function storeRewards(
address provider,
IDSToken poolToken,
IERC20 reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private {
// update all provider's pending rewards, in order to apply retroactive reward multipliers.
(PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards) =
updateRewards(provider, poolToken, reserveToken, program, lpStats);
// get full rewards and the respective rewards multiplier.
(uint256 fullReward, uint32 multiplier) =
fullRewards(provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats);
// if we're setting the effective staking time, then we'd have to store the rewards multiplier in order to
// account for it in the future.
if (resetStakingTime) {
// get the amount of the actual base rewards that were claimed.
if (multiplier == PPM_RESOLUTION) {
providerRewards.baseRewardsDebt = fullReward;
} else {
providerRewards.baseRewardsDebt = fullReward.mul(PPM_RESOLUTION).div(multiplier);
}
} else {
multiplier = PPM_RESOLUTION;
providerRewards.baseRewardsDebt = fullReward;
}
// update store data with the store pending rewards and set the last update time to the timestamp of the
// current block.
_store.updateProviderRewardsData(
provider,
poolToken,
reserveToken,
providerRewards.rewardPerToken,
0,
providerRewards.totalClaimedRewards,
resetStakingTime ? time() : providerRewards.effectiveStakingTime,
providerRewards.baseRewardsDebt,
multiplier
);
}
/**
* @dev updates pool rewards.
*
* @param poolToken the pool token representing the rewards pool
* @param reserveToken the reserve token representing the liquidity in the pool
* @param program the pool program info
* @param lpStats liquidity protection statistics store
*/
function updateReserveRewards(
IDSToken poolToken,
IERC20 reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private returns (PoolRewards memory) {
// calculate the new reward rate per-token and update it in the store.
PoolRewards memory poolRewardsData = poolRewards(poolToken, reserveToken);
bool update = false;
// rewardPerToken must be calculated with the previous value of lastUpdateTime.
uint256 newRewardPerToken = rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats);
if (poolRewardsData.rewardPerToken != newRewardPerToken) {
poolRewardsData.rewardPerToken = newRewardPerToken;
update = true;
}
uint256 newLastUpdateTime = Math.min(time(), program.endTime);
if (poolRewardsData.lastUpdateTime != newLastUpdateTime) {
poolRewardsData.lastUpdateTime = newLastUpdateTime;
update = true;
}
if (update) {
_store.updatePoolRewardsData(
poolToken,
reserveToken,
poolRewardsData.lastUpdateTime,
poolRewardsData.rewardPerToken,
poolRewardsData.totalClaimedRewards
);
}
return poolRewardsData;
}
/**
* @dev updates provider rewards. this function is called during every liquidity changes
*
* @param provider the owner of the liquidity
* @param poolToken the pool token representing the rewards pool
* @param reserveToken the reserve token representing the liquidity in the pool
* @param program the pool program info
* @param lpStats liquidity protection statistics store
*/
function updateProviderRewards(
address provider,
IDSToken poolToken,
IERC20 reserveToken,
PoolRewards memory poolRewardsData,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private returns (ProviderRewards memory) {
// update provider's rewards with the newly claimable base rewards and the new reward rate per-token.
ProviderRewards memory providerRewards = providerRewards(provider, poolToken, reserveToken);
bool update = false;
// if this is the first liquidity provision - set the effective staking time to the current time.
if (
providerRewards.effectiveStakingTime == 0 &&
lpStats.totalProviderAmount(provider, poolToken, reserveToken) == 0
) {
providerRewards.effectiveStakingTime = time();
update = true;
}
// pendingBaseRewards must be calculated with the previous value of providerRewards.rewardPerToken.
uint256 rewards =
baseRewards(provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats);
if (rewards != 0) {
providerRewards.pendingBaseRewards = providerRewards.pendingBaseRewards.add(rewards);
update = true;
}
if (providerRewards.rewardPerToken != poolRewardsData.rewardPerToken) {
providerRewards.rewardPerToken = poolRewardsData.rewardPerToken;
update = true;
}
if (update) {
_store.updateProviderRewardsData(
provider,
poolToken,
reserveToken,
providerRewards.rewardPerToken,
providerRewards.pendingBaseRewards,
providerRewards.totalClaimedRewards,
providerRewards.effectiveStakingTime,
providerRewards.baseRewardsDebt,
providerRewards.baseRewardsDebtMultiplier
);
}
return providerRewards;
}
/**
* @dev updates pool and provider rewards. this function is called during every liquidity changes
*
* @param provider the owner of the liquidity
* @param poolToken the pool token representing the rewards pool
* @param reserveToken the reserve token representing the liquidity in the pool
* @param program the pool program info
* @param lpStats liquidity protection statistics store
*/
function updateRewards(
address provider,
IDSToken poolToken,
IERC20 reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private returns (PoolRewards memory, ProviderRewards memory) {
PoolRewards memory poolRewardsData = updateReserveRewards(poolToken, reserveToken, program, lpStats);
ProviderRewards memory providerRewards =
updateProviderRewards(provider, poolToken, reserveToken, poolRewardsData, program, lpStats);
return (poolRewardsData, providerRewards);
}
/**
* @dev returns the aggregated reward rate per-token
*
* @param poolToken the participating pool to query
* @param reserveToken the reserve token representing the liquidity in the pool
* @param poolRewardsData the rewards data of the pool
* @param program the pool program info
* @param lpStats liquidity protection statistics store
*
* @return the aggregated reward rate per-token
*/
function rewardPerToken(
IDSToken poolToken,
IERC20 reserveToken,
PoolRewards memory poolRewardsData,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
// if there is no longer any liquidity in this reserve, return the historic rate (i.e., rewards won't accrue).
uint256 totalReserveAmount = lpStats.totalReserveAmount(poolToken, reserveToken);
if (totalReserveAmount == 0) {
return poolRewardsData.rewardPerToken;
}
// don't grant any rewards before the starting time of the program.
uint256 currentTime = time();
if (currentTime < program.startTime) {
return 0;
}
uint256 stakingEndTime = Math.min(currentTime, program.endTime);
uint256 stakingStartTime = Math.max(program.startTime, poolRewardsData.lastUpdateTime);
if (stakingStartTime == stakingEndTime) {
return poolRewardsData.rewardPerToken;
}
// since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases
// where the total amount in the denominator is higher than the product of the rewards rate and staking duration.
// in order to avoid this imprecision, we will amplify the reward rate by the units amount.
return
poolRewardsData.rewardPerToken.add( // the aggregated reward rate
stakingEndTime
.sub(stakingStartTime) // the duration of the staking
.mul(program.rewardRate) // multiplied by the rate
.mul(REWARD_RATE_FACTOR) // and factored to increase precision
.mul(rewardShare(reserveToken, program)) // and applied the specific token share of the whole reward
.div(totalReserveAmount.mul(PPM_RESOLUTION)) // and divided by the total protected tokens amount in the pool
);
}
/**
* @dev returns the base rewards since the last claim
*
* @param provider the owner of the liquidity
* @param poolToken the participating pool to query
* @param reserveToken the reserve token representing the liquidity in the pool
* @param poolRewardsData the rewards data of the pool
* @param providerRewards the rewards data of the provider
* @param program the pool program info
* @param lpStats liquidity protection statistics store
*
* @return the base rewards since the last claim
*/
function baseRewards(
address provider,
IDSToken poolToken,
IERC20 reserveToken,
PoolRewards memory poolRewardsData,
ProviderRewards memory providerRewards,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
uint256 totalProviderAmount = lpStats.totalProviderAmount(provider, poolToken, reserveToken);
uint256 newRewardPerToken = rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats);
return
totalProviderAmount // the protected tokens amount held by the provider
.mul(newRewardPerToken.sub(providerRewards.rewardPerToken)) // multiplied by the difference between the previous and the current rate
.div(REWARD_RATE_FACTOR); // and factored back
}
/**
* @dev returns the full rewards since the last claim
*
* @param provider the owner of the liquidity
* @param poolToken the participating pool to query
* @param reserveToken the reserve token representing the liquidity in the pool
* @param poolRewardsData the rewards data of the pool
* @param providerRewards the rewards data of the provider
* @param program the pool program info
* @param lpStats liquidity protection statistics store
*
* @return full rewards and the respective rewards multiplier
*/
function fullRewards(
address provider,
IDSToken poolToken,
IERC20 reserveToken,
PoolRewards memory poolRewardsData,
ProviderRewards memory providerRewards,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256, uint32) {
// calculate the claimable base rewards (since the last claim).
uint256 newBaseRewards =
baseRewards(provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats);
// make sure that we aren't exceeding the reward rate for any reason.
verifyBaseReward(newBaseRewards, providerRewards.effectiveStakingTime, reserveToken, program);
// calculate pending rewards and apply the rewards multiplier.
uint32 multiplier = rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program);
uint256 fullReward = providerRewards.pendingBaseRewards.add(newBaseRewards);
if (multiplier != PPM_RESOLUTION) {
fullReward = fullReward.mul(multiplier).div(PPM_RESOLUTION);
}
// add any debt, while applying the best retroactive multiplier.
fullReward = fullReward.add(
applyHigherMultiplier(
providerRewards.baseRewardsDebt,
multiplier,
providerRewards.baseRewardsDebtMultiplier
)
);
// make sure that we aren't exceeding the full reward rate for any reason.
verifyFullReward(fullReward, reserveToken, poolRewardsData, program);
return (fullReward, multiplier);
}
/**
* @dev returns the specific reserve token's share of all rewards
*
* @param reserveToken the reserve token representing the liquidity in the pool
* @param program the pool program info
*/
function rewardShare(IERC20 reserveToken, PoolProgram memory program) private pure returns (uint32) {
if (reserveToken == program.reserveTokens[0]) {
return program.rewardShares[0];
}
return program.rewardShares[1];
}
/**
* @dev returns the rewards multiplier for the specific provider
*
* @param provider the owner of the liquidity
* @param stakingStartTime the staking time in the pool
* @param program the pool program info
*
* @return the rewards multiplier for the specific provider
*/
function rewardsMultiplier(
address provider,
uint256 stakingStartTime,
PoolProgram memory program
) private view returns (uint32) {
uint256 effectiveStakingEndTime = Math.min(time(), program.endTime);
uint256 effectiveStakingStartTime =
Math.max( // take the latest of actual staking start time and the latest multiplier reset
Math.max(stakingStartTime, program.startTime), // don't count staking before the start of the program
Math.max(_lastRemoveTimes.checkpoint(provider), _store.providerLastClaimTime(provider)) // get the latest multiplier reset timestamp
);
// check that the staking range is valid. for example, it can be invalid when calculating the multiplier when
// the staking has started before the start of the program, in which case the effective staking start time will
// be in the future, compared to the effective staking end time (which will be the time of the current block).
if (effectiveStakingStartTime >= effectiveStakingEndTime) {
return PPM_RESOLUTION;
}
uint256 effectiveStakingDuration = effectiveStakingEndTime.sub(effectiveStakingStartTime);
// given x representing the staking duration (in seconds), the resulting multiplier (in PPM) is:
// * for 0 <= x <= 1 weeks: 100% PPM
// * for 1 <= x <= 2 weeks: 125% PPM
// * for 2 <= x <= 3 weeks: 150% PPM
// * for 3 <= x <= 4 weeks: 175% PPM
// * for x > 4 weeks: 200% PPM
return PPM_RESOLUTION + MULTIPLIER_INCREMENT * uint32(Math.min(effectiveStakingDuration.div(1 weeks), 4));
}
/**
* @dev returns the pool program for a specific pool
*
* @param poolToken the pool token representing the rewards pool
*
* @return the pool program for a specific pool
*/
function poolProgram(IDSToken poolToken) private view returns (PoolProgram memory) {
PoolProgram memory program;
(program.startTime, program.endTime, program.rewardRate, program.reserveTokens, program.rewardShares) = _store
.poolProgram(poolToken);
return program;
}
/**
* @dev returns pool rewards for a specific pool and reserve
*
* @param poolToken the pool token representing the rewards pool
* @param reserveToken the reserve token representing the liquidity in the pool
*
* @return pool rewards for a specific pool and reserve
*/
function poolRewards(IDSToken poolToken, IERC20 reserveToken) private view returns (PoolRewards memory) {
PoolRewards memory data;
(data.lastUpdateTime, data.rewardPerToken, data.totalClaimedRewards) = _store.poolRewards(
poolToken,
reserveToken
);
return data;
}
/**
* @dev returns provider rewards for a specific pool and reserve
*
* @param provider the owner of the liquidity
* @param poolToken the pool token representing the rewards pool
* @param reserveToken the reserve token representing the liquidity in the pool
*
* @return provider rewards for a specific pool and reserve
*/
function providerRewards(
address provider,
IDSToken poolToken,
IERC20 reserveToken
) private view returns (ProviderRewards memory) {
ProviderRewards memory data;
(
data.rewardPerToken,
data.pendingBaseRewards,
data.totalClaimedRewards,
data.effectiveStakingTime,
data.baseRewardsDebt,
data.baseRewardsDebtMultiplier
) = _store.providerRewards(provider, poolToken, reserveToken);
return data;
}
/**
* @dev applies the best of two rewards multipliers on the provided amount
*
* @param amount the amount of the reward
* @param multiplier1 the first multiplier
* @param multiplier2 the second multiplier
*
* @return new reward amount
*/
function applyHigherMultiplier(
uint256 amount,
uint32 multiplier1,
uint32 multiplier2
) private pure returns (uint256) {
uint256 bestMultiplier = Math.max(multiplier1, multiplier2);
if (bestMultiplier == PPM_RESOLUTION) {
return amount;
}
return amount.mul(bestMultiplier).div(PPM_RESOLUTION);
}
/**
* @dev performs a sanity check on the newly claimable base rewards
*
* @param baseReward the base reward to check
* @param stakingStartTime the staking time in the pool
* @param reserveToken the reserve token representing the liquidity in the pool
* @param program the pool program info
*/
function verifyBaseReward(
uint256 baseReward,
uint256 stakingStartTime,
IERC20 reserveToken,
PoolProgram memory program
) private view {
// don't grant any rewards before the starting time of the program or for stakes after the end of the program.
uint256 currentTime = time();
if (currentTime < program.startTime || stakingStartTime >= program.endTime) {
require(baseReward == 0, "ERR_BASE_REWARD_TOO_HIGH");
return;
}
uint256 effectiveStakingStartTime = Math.max(stakingStartTime, program.startTime);
uint256 effectiveStakingEndTime = Math.min(currentTime, program.endTime);
// make sure that we aren't exceeding the base reward rate for any reason.
require(
baseReward <=
program
.rewardRate
.mul(effectiveStakingEndTime.sub(effectiveStakingStartTime))
.mul(rewardShare(reserveToken, program))
.div(PPM_RESOLUTION),
"ERR_BASE_REWARD_RATE_TOO_HIGH"
);
}
/**
* @dev performs a sanity check on the newly claimable full rewards
*
* @param fullReward the full reward to check
* @param reserveToken the reserve token representing the liquidity in the pool
* @param poolRewardsData the rewards data of the pool
* @param program the pool program info
*/
function verifyFullReward(
uint256 fullReward,
IERC20 reserveToken,
PoolRewards memory poolRewardsData,
PoolProgram memory program
) private pure {
uint256 maxClaimableReward =
(
program
.rewardRate
.mul(program.endTime.sub(program.startTime))
.mul(rewardShare(reserveToken, program))
.mul(MAX_MULTIPLIER)
.div(PPM_RESOLUTION)
.div(PPM_RESOLUTION)
)
.sub(poolRewardsData.totalClaimedRewards);
// make sure that we aren't exceeding the full reward rate for any reason.
require(fullReward <= maxClaimableReward, "ERR_REWARD_RATE_TOO_HIGH");
}
/**
* @dev returns the liquidity protection stats data contract
*
* @return the liquidity protection store data contract
*/
function liquidityProtectionStats() private view returns (ILiquidityProtectionStats) {
return liquidityProtection().stats();
}
/**
* @dev returns the liquidity protection contract
*
* @return the liquidity protection contract
*/
function liquidityProtection() private view returns (ILiquidityProtection) {
return ILiquidityProtection(addressOf(LIQUIDITY_PROTECTION));
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../utility/interfaces/IOwned.sol";
/*
Converter Anchor interface
*/
interface IConverterAnchor is IOwned {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./ILiquidityProtectionStore.sol";
import "./ILiquidityProtectionStats.sol";
import "./ILiquidityProtectionSettings.sol";
import "./ILiquidityProtectionSystemStore.sol";
import "../../utility/interfaces/ITokenHolder.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
/*
Liquidity Protection interface
*/
interface ILiquidityProtection {
function store() external view returns (ILiquidityProtectionStore);
function stats() external view returns (ILiquidityProtectionStats);
function settings() external view returns (ILiquidityProtectionSettings);
function systemStore() external view returns (ILiquidityProtectionSystemStore);
function wallet() external view returns (ITokenHolder);
function addLiquidityFor(
address owner,
IConverterAnchor poolAnchor,
IERC20 reserveToken,
uint256 amount
) external payable returns (uint256);
function addLiquidity(
IConverterAnchor poolAnchor,
IERC20 reserveToken,
uint256 amount
) external payable returns (uint256);
function removeLiquidity(uint256 id, uint32 portion) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
/**
* @dev Liquidity protection events subscriber interface
*/
interface ILiquidityProtectionEventsSubscriber {
function onAddingLiquidity(
address provider,
IConverterAnchor poolAnchor,
IERC20 reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function onRemovingLiquidity(
uint256 id,
address provider,
IConverterAnchor poolAnchor,
IERC20 reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./ILiquidityProtectionEventsSubscriber.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
/*
Liquidity Protection Store Settings interface
*/
interface ILiquidityProtectionSettings {
function isPoolWhitelisted(IConverterAnchor poolAnchor) external view returns (bool);
function poolWhitelist() external view returns (address[] memory);
function subscribers() external view returns (address[] memory);
function isPoolSupported(IConverterAnchor poolAnchor) external view returns (bool);
function minNetworkTokenLiquidityForMinting() external view returns (uint256);
function defaultNetworkTokenMintingLimit() external view returns (uint256);
function networkTokenMintingLimits(IConverterAnchor poolAnchor) external view returns (uint256);
function addLiquidityDisabled(IConverterAnchor poolAnchor, IERC20 reserveToken) external view returns (bool);
function minProtectionDelay() external view returns (uint256);
function maxProtectionDelay() external view returns (uint256);
function minNetworkCompensation() external view returns (uint256);
function lockDuration() external view returns (uint256);
function averageRateMaxDeviation() external view returns (uint32);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../token/interfaces/IDSToken.sol";
/*
Liquidity Protection Stats interface
*/
interface ILiquidityProtectionStats {
function increaseTotalAmounts(
address provider,
IDSToken poolToken,
IERC20 reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function decreaseTotalAmounts(
address provider,
IDSToken poolToken,
IERC20 reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function addProviderPool(address provider, IDSToken poolToken) external returns (bool);
function removeProviderPool(address provider, IDSToken poolToken) external returns (bool);
function totalPoolAmount(IDSToken poolToken) external view returns (uint256);
function totalReserveAmount(IDSToken poolToken, IERC20 reserveToken) external view returns (uint256);
function totalProviderAmount(
address provider,
IDSToken poolToken,
IERC20 reserveToken
) external view returns (uint256);
function providerPools(address provider) external view returns (IDSToken[] memory);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../token/interfaces/IDSToken.sol";
import "../../utility/interfaces/IOwned.sol";
/*
Liquidity Protection Store interface
*/
interface ILiquidityProtectionStore is IOwned {
function withdrawTokens(
IERC20 _token,
address _to,
uint256 _amount
) external;
function protectedLiquidity(uint256 _id)
external
view
returns (
address,
IDSToken,
IERC20,
uint256,
uint256,
uint256,
uint256,
uint256
);
function addProtectedLiquidity(
address _provider,
IDSToken _poolToken,
IERC20 _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount,
uint256 _reserveRateN,
uint256 _reserveRateD,
uint256 _timestamp
) external returns (uint256);
function updateProtectedLiquidityAmounts(
uint256 _id,
uint256 _poolNewAmount,
uint256 _reserveNewAmount
) external;
function removeProtectedLiquidity(uint256 _id) external;
function lockedBalance(address _provider, uint256 _index) external view returns (uint256, uint256);
function lockedBalanceRange(
address _provider,
uint256 _startIndex,
uint256 _endIndex
) external view returns (uint256[] memory, uint256[] memory);
function addLockedBalance(
address _provider,
uint256 _reserveAmount,
uint256 _expirationTime
) external returns (uint256);
function removeLockedBalance(address _provider, uint256 _index) external;
function systemBalance(IERC20 _poolToken) external view returns (uint256);
function incSystemBalance(IERC20 _poolToken, uint256 _poolAmount) external;
function decSystemBalance(IERC20 _poolToken, uint256 _poolAmount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
/*
Liquidity Protection System Store interface
*/
interface ILiquidityProtectionSystemStore {
function systemBalance(IERC20 poolToken) external view returns (uint256);
function incSystemBalance(IERC20 poolToken, uint256 poolAmount) external;
function decSystemBalance(IERC20 poolToken, uint256 poolAmount) external;
function networkTokensMinted(IConverterAnchor poolAnchor) external view returns (uint256);
function incNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external;
function decNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../utility/interfaces/IOwned.sol";
/*
DSToken interface
*/
interface IDSToken is IConverterAnchor, IERC20 {
function issue(address _to, uint256 _amount) external;
function destroy(address _from, uint256 _amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./Owned.sol";
import "./Utils.sol";
import "./interfaces/IContractRegistry.sol";
/**
* @dev This is the base contract for ContractRegistry clients.
*/
contract ContractRegistryClient is Owned, Utils {
bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory";
bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder";
bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader";
bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry";
bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
bytes32 internal constant BNT_TOKEN = "BNTToken";
bytes32 internal constant BANCOR_X = "BancorX";
bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
bytes32 internal constant LIQUIDITY_PROTECTION = "LiquidityProtection";
IContractRegistry public registry; // address of the current contract-registry
IContractRegistry public prevRegistry; // address of the previous contract-registry
bool public onlyOwnerCanUpdateRegistry; // only an owner can update the contract-registry
/**
* @dev verifies that the caller is mapped to the given contract name
*
* @param _contractName contract name
*/
modifier only(bytes32 _contractName) {
_only(_contractName);
_;
}
// error message binary size optimization
function _only(bytes32 _contractName) internal view {
require(msg.sender == addressOf(_contractName), "ERR_ACCESS_DENIED");
}
/**
* @dev initializes a new ContractRegistryClient instance
*
* @param _registry address of a contract-registry contract
*/
constructor(IContractRegistry _registry) internal validAddress(address(_registry)) {
registry = IContractRegistry(_registry);
prevRegistry = IContractRegistry(_registry);
}
/**
* @dev updates to the new contract-registry
*/
function updateRegistry() public {
// verify that this function is permitted
require(msg.sender == owner || !onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED");
// get the new contract-registry
IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY));
// verify that the new contract-registry is different and not zero
require(newRegistry != registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY");
// verify that the new contract-registry is pointing to a non-zero contract-registry
require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
// save a backup of the current contract-registry before replacing it
prevRegistry = registry;
// replace the current contract-registry with the new contract-registry
registry = newRegistry;
}
/**
* @dev restores the previous contract-registry
*/
function restoreRegistry() public ownerOnly {
// restore the previous contract-registry
registry = prevRegistry;
}
/**
* @dev restricts the permission to update the contract-registry
*
* @param _onlyOwnerCanUpdateRegistry indicates whether or not permission is restricted to owner only
*/
function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) public ownerOnly {
// change the permission to update the contract-registry
onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
}
/**
* @dev returns the address associated with the given contract name
*
* @param _contractName contract name
*
* @return contract address
*/
function addressOf(bytes32 _contractName) internal view returns (address) {
return registry.addressOf(_contractName);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./interfaces/IOwned.sol";
/**
* @dev This contract provides support and utilities for contract ownership.
*/
contract Owned is IOwned {
address public override owner;
address public newOwner;
/**
* @dev triggered when the owner is updated
*
* @param _prevOwner previous owner
* @param _newOwner new owner
*/
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
_ownerOnly();
_;
}
// error message binary size optimization
function _ownerOnly() internal view {
require(msg.sender == owner, "ERR_ACCESS_DENIED");
}
/**
* @dev allows transferring the contract ownership
* the new owner still needs to accept the transfer
* can only be called by the contract owner
*
* @param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public override ownerOnly {
require(_newOwner != owner, "ERR_SAME_OWNER");
newOwner = _newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public override {
require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/*
Time implementing contract
*/
contract Time {
/**
* @dev returns the current time
*/
function time() internal view virtual returns (uint256) {
return block.timestamp;
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 _value) {
_greaterThanZero(_value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 _value) internal pure {
require(_value > 0, "ERR_ZERO_VALUE");
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
_validAddress(_address);
_;
}
// error message binary size optimization
function _validAddress(address _address) internal pure {
require(_address != address(0), "ERR_INVALID_ADDRESS");
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
_notThis(_address);
_;
}
// error message binary size optimization
function _notThis(address _address) internal view {
require(_address != address(this), "ERR_ADDRESS_IS_SELF");
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address _address) {
_validExternalAddress(_address);
_;
}
// error message binary size optimization
function _validExternalAddress(address _address) internal view {
require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS");
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev Checkpoint store contract interface
*/
interface ICheckpointStore {
function addCheckpoint(address _address) external;
function addPastCheckpoint(address _address, uint256 _time) external;
function addPastCheckpoints(address[] calldata _addresses, uint256[] calldata _times) external;
function checkpoint(address _address) external view returns (uint256);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/*
Contract Registry interface
*/
interface IContractRegistry {
function addressOf(bytes32 _contractName) external view returns (address);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/*
Owned contract interface
*/
interface IOwned {
// this function isn't since the compiler emits automatically generated getter functions as external
function owner() external view returns (address);
function transferOwnership(address _newOwner) external;
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IOwned.sol";
/*
Token Holder interface
*/
interface ITokenHolder is IOwned {
function withdrawTokens(
IERC20 _token,
address _to,
uint256 _amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/// @title Claimable contract interface
interface IClaimable {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IClaimable.sol";
/// @title Mintable Token interface
interface IMintableToken is IERC20, IClaimable {
function issue(address to, uint256 amount) external;
function destroy(address from, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IMintableToken.sol";
/// @title The interface for mintable/burnable token governance.
interface ITokenGovernance {
// The address of the mintable ERC20 token.
function token() external view returns (IMintableToken);
/// @dev Mints new tokens.
///
/// @param to Account to receive the new amount.
/// @param amount Amount to increase the supply by.
///
function mint(address to, uint256 amount) external;
/// @dev Burns tokens from the caller.
///
/// @param amount Amount to decrease the supply by.
///
function burn(uint256 amount) external;
}
// 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;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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.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));
}
} | Liquidity protection events subscriber interface/ | interface ILiquidityProtectionEventsSubscriber {
function onAddingLiquidity(
address provider,
IConverterAnchor poolAnchor,
IERC20 reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function onRemovingLiquidity(
uint256 id,
address provider,
IConverterAnchor poolAnchor,
IERC20 reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
pragma solidity 0.6.12;
}
| 10,349,372 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
/// @title BRZ token Bridge
/// @author Solange Gueiros
// Inpired on
// https://github.com/rsksmart/tokenbridge/blob/master/bridge/contracts/Bridge.sol
// https://github.com/DistributedCollective/Bridge-SC/blob/master/sovryn-token-bridge/bridge/contracts/Bridge_v3.sol
// AccessControl.sol : https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/access/AccessControl.sol
// Pausable.sol : https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/security/Pausable.sol
import "./ozeppelin/access/AccessControl.sol";
import "./ozeppelin/security/Pausable.sol";
import "./IBridge.sol";
struct BlockchainStruct {
uint256 minTokenAmount;
uint256 minBRZFee; // quoteETH_BRZ * gasAcceptTransfer * minGasPrice
uint256 minGasPrice; // in Wei
bool checkAddress; // to verify is an address is EVM compatible is this blockchain
}
/**
* @dev BRZ token Bridge
*
* Author: Solange Gueiros
*
* Smart contract to cross the BRZ token between EVM compatible blockchains.
*
* The tokens are crossed by TransferoSwiss, the company that controls the issuance of BRZs.
*
* It uses [Open Zeppelin Contracts]
* (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/)
*
*/
contract Bridge is AccessControl, IBridge, Pausable {
address private constant ZERO_ADDRESS = address(0);
bytes32 private constant NULL_HASH = bytes32(0);
bytes32 public constant MONITOR_ROLE = keccak256("MONITOR_ROLE");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
/**
* @dev DECIMALPERCENT is the representation of 100% using (2) decimal places
* 100.00 = percentage accuracy (2) to 100%
*/
uint256 public constant DECIMALPERCENT = 10000;
IERC20 public token;
uint256 public totalFeeReceivedBridge; // fee received per Bridge, not for transaction in other blockchain
/**
* @dev Fee percentage bridge.
*
* For each amount received in the bridge, a fee percentage is discounted.
* This function returns this fee percentage bridge.
* Include 2 decimal places.
*/
uint256 public feePercentageBridge;
/**
* Estimative for function acceptTransfer: 100000 wei, it can change in EVM cost updates
*
* It is used to calculate minBRZFee in destination,
* which can not accept a BRZ fee less than minBRZFee (per blockchain).
*/
uint256 public gasAcceptTransfer;
/**
* @dev the quote of pair ETH / BRZ.
*
* (1 ETH = the amount of BRZ returned)
*
* in BRZ in minor unit (4 decimal places).
*
* It is used to calculate minBRZFee in destination
* which can not accept a BRZ fee less than minBRZFee (per blockchain).
*
*/
uint256 public quoteETH_BRZ;
mapping(bytes32 => bool) public processed;
mapping(string => uint256) private blockchainIndex;
BlockchainStruct[] private blockchainInfo;
string[] public blockchain;
/**
* @dev Function called only when the smart contract is deployed.
*
* Parameters:
* - address tokenAddress - address of BRZ token used in this blockchain network
*
* Actions:
* - the transaction's sender will be added in the DEFAULT_ADMIN_ROLE.
* - the token will be defined by the parameter tokenAddress
* - the feePercentageBridge default value is be setted in 10, which means 0.1%
*/
constructor(address tokenAddress) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
token = IERC20(tokenAddress);
feePercentageBridge = 10; //0.1%
gasAcceptTransfer = 100000; //Estimative function acceptTransfer: 100000 wei
}
/**
* @dev Modifier which verifies if the caller is an owner,
* it means he has the role `DEFAULT_ADMIN_ROLE`.
*
* The role `DEFAULT_ADMIN_ROLE` is defined by Open Zeppelin's AccessControl smart contract.
*
* By default (setted in the constructor) the account which deployed this smart contract is in this role.
*
* This owner can add / remove other owners.
*/
modifier onlyOwner() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "not owner");
_;
}
/**
* @dev Modifier which verifies if the caller is a monitor,
* it means he has the role `MONITOR_ROLE`.
*
* Role MONITOR are referred to its `bytes32` identifier,
* defined in the `public constant` called MONITOR_ROLE.
* It should be exposed in the external API and be unique.
*
* Role MONITOR is used to manage the permissions of monitor's addresses.
*/
modifier onlyMonitor() {
require(hasRole(MONITOR_ROLE, _msgSender()), "not monitor");
_;
}
/**
* @dev Modifier which verifies if the caller is a monitor,
* it means he has the role `ADMIN_ROLE`.
*
* Role ADMIN are referred to its `bytes32` identifier,
* defined in the `public constant` called ADMIN_ROLE.
* It should be exposed in the external API and be unique.
*
* Role ADMIN is used to manage the permissions for update minimum fee per blockchain.
*/
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, _msgSender()), "not admin");
_;
}
/**
* @dev Function which returns the bridge's version.
*
* This is a fixed value define in source code.
*
* Parameters: none
*
* Returns: string
*/
function version() external pure override returns (string memory) {
return "v0";
}
/**
* @dev Private function to compare two strings
* and returns `true` if the strings are equal,
* otherwise it returns false.
*
* Parameters: stringA, stringB
*
* Returns: bool
*/
function compareStrings(string memory a, string memory b)
private
pure
returns (bool)
{
return (keccak256(abi.encodePacked((a))) ==
keccak256(abi.encodePacked((b))));
}
/**
* @dev This function starts the process of crossing tokens in the Bridge.
*
* > Any account / person can call it!
*
* Can not be called if the Bridge is paused.
*
* Parameters:
* - amount - gross amount of tokens to be crossed.
* - The Bridge fee will be deducted from this amount.
* - transactionFee - array with the fees:
* - transactionFee[0] - fee in BRL - this fee will be added to amount transfered from caller's account.
* - transactionFee[1] - gas price for fee in destiny currency(minor unit) - this information will be
* used in the destination Blockchain,
* by the monitor who will create the transaction and send using this fee defined here.
* - toBlockchain - the amount will be sent to this blockchain.
* - toAddress - the amount will be sent to this address. It can be diferent from caller's address.
* This is a string because some blockchain could not have the same pattern from Ethereum / RSK / BSC.
*
* Returns: bool - true if it is sucessful.
*
* > Before call this function, the caller MUST have called function `approve` in BRZ token,
* > allowing the bridge's smart contract address to use the BRZ tokens,
* > calling the function `transferFrom`.
*
* References:
*
* ERC-20 tokens approve and transferFrom pattern:
* [eip-20#transferfrom](https://eips.ethereum.org/EIPS/eip-20#transferfrom)
*
* Requirements:
* - fee in BRZ (transactionFee[0]) must be at least (BRZFactorFee[blockchainName] * minGasPrice[toBlockchain]).
* - gasPrice (transactionFee[1]) in destiny blockchain (minor unit) greater than minGasPrice in toBlockchain.
* - toBlockchain exists.
* - toAddress is not an empty string.
* - amount must be greater than minTokenAmount in toBlockchain.
* - amount greater than zero.
*
* Actions:
* - add the blockchain fee in BRZ to amount in BRZ, in totalAmount.
* - calculate bridge's fee using the original amount to be sent.
* - discount bridge's fee from the original amount, in amountMinusFees.
* - add bridge's fee to `totalFeeReceivedBridge`, a variable to store all the fees received by the bridge.
* - BRZ transfer totalAmount from the caller's address to bridge address.
* - emit `CrossRequest` event, with the parameters:
* - from - address of the caller's function.
* - amount - the net amount to be transfered in the destination blockchain.
* - toFee - the gas price fee, which must be used to send the transfer transaction in the destination blockchain.
* - toAddress - string representing the address which will receive the tokens.
* - toBlockchain - the destination blockchain.
*
* > The `CrossRequest` event is very important because it must be listened by the monitor,
* an external program which will
* send the transaction on the destination blockchain.
*
* #### More info about fees
*
* - Blockchain / transaction fee in BRL (transactionFee[0])
* It will be transfered from user's account,
* along with the amount he would like to receive in the account.
*
* This will be spent in `toBlockchain`.
* Does not depend of amount, but of destination blockchain.
*
* It must be at least the minBRZFee per blockchain.
*
* It is used in the function acceptTransfer,
* which can not accept a BRZ fee less than minBRZFee (per blockchain).
*
* - gas price (transactionFee[1])
* It must be at least the minGasPrice per blockchain.
*
* - Bridge Fee - it is deducted from the requested amount.
* It is a percentage of the requested amount.
* Cannot include the transaction fee in order to be calculated.
*
*/
function receiveTokens(
uint256 amount,
uint256[2] memory transactionFee,
string memory toBlockchain,
string memory toAddress
) external override whenNotPaused returns (bool) {
require(existsBlockchain(toBlockchain), "toBlockchain not exists");
require(!compareStrings(toAddress, ""), "toAddress is null");
uint256 index = blockchainIndex[toBlockchain] - 1;
require(
transactionFee[0] >= blockchainInfo[index].minBRZFee,
"feeBRZ is less than minimum"
);
require(
transactionFee[1] >= blockchainInfo[index].minGasPrice,
"gasPrice is less than minimum"
);
require(amount > 0, "amount is 0");
require(
amount >= blockchainInfo[index].minTokenAmount,
"amount is less than minimum"
);
if (blockchainInfo[index].checkAddress) {
require(bytes(toAddress).length == 42, "invalid destination address");
}
//The total amount is the amount desired plus the blockchain fee to destination, in the token unit
uint256 totalAmount = amount + transactionFee[0];
//Bridge fee or service fee
uint256 bridgeFee = (amount * feePercentageBridge) / DECIMALPERCENT;
uint256 amountMinusFees = amount - bridgeFee;
totalFeeReceivedBridge += bridgeFee;
//This is the message for Monitor off-chain manage the transaction and send the tokens on the other Blockchain
emit CrossRequest(
_msgSender(),
amountMinusFees,
transactionFee[1],
toAddress,
toBlockchain
);
//Transfer the tokens on IERC20, they should be already approved for the bridge Address to use them
token.transferFrom(_msgSender(), address(this), totalAmount);
return true;
}
/**
* @dev This function calculate a transaction id hash.
*
* Any person can call it.
*
* Parameters:
* - hashes - from transaction in the origin blockchain:
* - blockHash - hash of the block where was the transaction `receiveTokens`
* - transactionHash - hash of the transaction `receiveTokens` with the event `CrossRequest`.
* - receiver - the address which will receive the tokens.
* - amount - the net amount to be transfered.
* - logIndex - the index of the event `CrossRequest` in the logs of transaction.
* - sender - address who sent the transaction `receiveTokens`, it is a string to be compatible with any blockchain.
*
* Returns: a bytes32 hash of all the information sent.
*
* Notes:
* It did not use origin blockchain and sender address
* because the possibility of having the same origin transaction from different blockchain source is minimal.
*
* It is a point to be evaluated in an audit.
*
*/
function getTransactionId(
bytes32[2] calldata hashes, //blockHash, transactionHash
address receiver,
uint256 amount,
uint32 logIndex
) public pure override returns (bytes32) {
return
keccak256(
abi.encodePacked(hashes[0], hashes[1], receiver, amount, logIndex)
);
}
/**
* @dev This function update the variable processed for a transaction
*
* > Only monitor can call it!
*
* This variable is a public mapping.
*
* Each bytes32 which represents a Transaction Id has his boolen value stored.
*
*/
function _processTransaction(
bytes32[2] calldata hashes, //blockHash, transactionHash
address receiver,
uint256 amount,
uint32 logIndex
) private {
bytes32 transactionId = getTransactionId(
hashes,
receiver,
amount,
logIndex
);
require(!processed[transactionId], "processed");
processed[transactionId] = true;
}
/**
* @dev This function transfer tokens from the the internal balance of bridge smart contract
* to the internal balance of the destination address.
*
* The token.balanceOf(bridgeAddress) must always be greather than or equal the total amount to be claimed by users,
* as there may be tokens not yet claimed.
*
* Can not be called if the Bridge is paused.
*
* > Only monitor can call it!
*
*/
function _sendToken(address to, uint256 amount) private returns (bool) {
require(token.balanceOf(address(this)) >= amount, "insufficient balance");
token.transfer(to, amount);
return true;
}
/**
* @dev This function accept the cross of token,
* which means it is called in the destination blockchain,
* who will send the tokens accepted to be crossed.
*
* > Only monitor can call it!
*
* Can not be called if the Bridge is paused.
*
* Parameters:
* - receiver - the address which will receive the tokens.
* - amount - the net amount to be transfered.
* - sender - string representing the address of the token's sender.
* - fromBlockchain - the origin blockchain.
* - hashes - from transaction in the origin blockchain:
* - blockHash - hash of the block where was the transaction `receiveTokens`.
* - transactionHash - hash of the transaction `receiveTokens` with the event `CrossRequest`.
* - logIndex - the index of the event `CrossRequest` in the transaction logs.
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - receiver is not a zero address.
* - amount greater than zero.
* - sender is not an empty string.
* - fromBlockchain exists.
* - blockHash is not null hash.
* - transactionHash is not hash.
*
* Actions:
* - processTransaction:
* - getTransactionId
* - verify if the transactionId was already processed
* - update the status processed for transactionId
* - sendToken:
* - check if the bridge has in his balance at least the amount required to do the transfer
* - transfer the amount tokens to destination address
*
*/
function acceptTransfer(
address receiver,
uint256 amount,
string calldata fromBlockchain,
bytes32[2] calldata hashes, //blockHash, transactionHash
uint32 logIndex
) external override onlyMonitor whenNotPaused returns (bool) {
require(receiver != ZERO_ADDRESS, "receiver is zero");
require(amount > 0, "amount is 0");
require(existsBlockchain(fromBlockchain), "fromBlockchain not exists");
require(hashes[0] != NULL_HASH, "blockHash is null");
require(hashes[1] != NULL_HASH, "transactionHash is null");
_processTransaction(hashes, receiver, amount, logIndex);
_sendToken(receiver, amount);
return true;
}
/**
* @dev Returns token balance in bridge.
*
* Parameters: none
*
* Returns: integer amount of tokens in bridge
*
*/
function getTokenBalance() external view override returns (uint256) {
return token.balanceOf(address(this));
}
/**
* @dev Withdraw tokens from bridge
*
* Only owner can call it.
*
* Can be called even if the Bridge is paused,
* because can happens a problem and it is necessary to withdraw tokens,
* maybe to create a new version of bridge, for example.
*
* The tokens only can be sent to the caller's function.
*
* Parameters: integer amount of tokens
*
* Returns: true if it is successful
*
* Requirements:
* - amount less or equal balance of tokens in bridge.
*
*/
function withdrawToken(uint256 amount) external onlyOwner returns (bool) {
require(amount <= token.balanceOf(address(this)), "insuficient balance");
token.transfer(_msgSender(), amount);
return true;
}
/**
* @dev This function add an address in the `MONITOR_ROLE`.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: address of monitor to be added
*
* Returns: bool - true if it is sucessful
*
*/
function addMonitor(address account)
external
onlyOwner
whenNotPaused
returns (bool)
{
require(!hasRole(ADMIN_ROLE, account), "is admin");
grantRole(MONITOR_ROLE, account);
return true;
}
/**
* @dev This function excludes an address in the `MONITOR_ROLE`.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: address of monitor to be excluded
*
* Returns: bool - true if it is sucessful
*
*/
function delMonitor(address account)
external
onlyOwner
whenNotPaused
returns (bool)
{
//Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE
revokeRole(MONITOR_ROLE, account);
return true;
}
/**
* @dev This function add an address in the `ADMIN_ROLE`.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: address of admin to be added
*
* Returns: bool - true if it is sucessful
*
*/
function addAdmin(address account)
external
onlyOwner
whenNotPaused
returns (bool)
{
require(!hasRole(MONITOR_ROLE, account), "is monitor");
grantRole(ADMIN_ROLE, account);
return true;
}
/**
* @dev This function excludes an address in the `ADMIN_ROLE`.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: address of admin to be excluded
*
* Returns: bool - true if it is sucessful
*
*/
function delAdmin(address account)
external
onlyOwner
whenNotPaused
returns (bool)
{
//Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE
revokeRole(ADMIN_ROLE, account);
return true;
}
/**
* @dev This function allows a user to renounce a role
*
* Parameters: bytes32 role, address account
*
* Returns: none
*
* Requirements:
*
* - An owner can not renounce the role DEFAULT_ADMIN_ROLE.
* - Can only renounce roles for your own account.
*
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(role != DEFAULT_ADMIN_ROLE, "can not renounce role owner");
require(account == _msgSender(), "can only renounce roles for self");
super.renounceRole(role, account);
}
/**
* @dev This function allows to revoke a role
*
* Parameters: bytes32 role, address account
*
* Returns: none
*
* Requirements:
*
* - An owner can not revoke yourself in the role DEFAULT_ADMIN_ROLE.
*
*/
function revokeRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
if (role == DEFAULT_ADMIN_ROLE) {
require(account != _msgSender(), "can not revoke yourself in role owner");
}
super.revokeRole(role, account);
}
/**
* @dev This function update the minimum blockchain fee - gas price - in the minor unit.
*
* It is an internal function, called when quoteETH_BRZ, gasAcceptTransfer
*
* Returns: bool - true if it is sucessful
*
* Emit the event `MinBRZFeeChanged(blockchain, oldFee, newFee)`.
*
*/
function _updateMinBRZFee() internal returns (bool) {
for (uint8 i = 0; i < blockchainInfo.length; i++) {
if (blockchainInfo[i].minGasPrice > 0) {
uint256 newFee = (gasAcceptTransfer *
blockchainInfo[i].minGasPrice *
quoteETH_BRZ) / (1 ether);
emit MinBRZFeeChanged(
blockchain[i],
blockchainInfo[i].minBRZFee,
newFee
);
blockchainInfo[i].minBRZFee = newFee;
}
}
return true;
}
/**
* @dev This function update quote of pair ETH / BRZ.
*
* (1 ETH = the amount of BRZ defined)
*
* Only admin can call it.
*
* Each time quoteETH_BRZ is updated, the MinBRZFee is updated too.
*
* Parameters: integer, the new quote
*
* Returns: bool - true if it is sucessful
*
* Emit the event `QuoteETH_BRZChanged(oldValue, newValue)`.
*
*/
function setQuoteETH_BRZ(uint256 newValue) public onlyAdmin returns (bool) {
emit QuoteETH_BRZChanged(quoteETH_BRZ, newValue);
quoteETH_BRZ = newValue;
require(_updateMinBRZFee(), "updateMinBRZFee error");
return true;
}
/**
* @dev Returns the minimum gas price to cross tokens.
*
* The function acceptTransfer can not accept less than the minimum gas price per blockchain.
*
* Parameters: string, blockchain name
*
* Returns: integer
*
*/
function getMinGasPrice(string memory blockchainName)
external
view
override
returns (uint256)
{
return blockchainInfo[blockchainIndex[blockchainName] - 1].minGasPrice;
}
/**
* @dev This function update the minimum blockchain fee - gas price - in the minor unit.
*
* Each time setMinGasPrice is updated, the MinBRZFee is updated too.
*
* Only admin can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: integer, the new fee
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - blockchain must exists.
*
* Emit the event `MinGasPriceChanged(blockchain, oldFee, newFee)`.
*
*/
function setMinGasPrice(string memory blockchainName, uint256 newFee)
public
onlyAdmin
whenNotPaused
returns (bool)
{
require(existsBlockchain(blockchainName), "blockchain not exists");
uint256 index = blockchainIndex[blockchainName] - 1;
emit MinGasPriceChanged(
blockchainName,
blockchainInfo[index].minGasPrice,
newFee
);
blockchainInfo[index].minGasPrice = newFee;
blockchainInfo[index].minBRZFee =
(gasAcceptTransfer * newFee * quoteETH_BRZ) /
(1 ether);
return true;
}
/**
* @dev Returns the minimum destination blockchain fee in BRZ,
* in minor unit (4 decimal places)
*
* It is updated when one of these itens be updated:
* - gasAcceptTransfer
* - quoteETH_BRZ
* - minGasPrice per Blockchain
*
* It is used in the function acceptTransfer,
* which can not accept a BRZ fee less than minBRZFee (per blockchain).
*
* Parameters: string, blockchain name
*
* Returns: integer
*
*/
function getMinBRZFee(string memory blockchainName)
external
view
override
returns (uint256)
{
return blockchainInfo[blockchainIndex[blockchainName] - 1].minBRZFee;
}
/**
* @dev This function update the estimative of the gas amount used in function AcceptTransfer.
*
* It will only change if happen some EVM cost update.
*
* Only owner can call it.
*
* Each time gasAcceptTransfer is updated, the MinBRZFee is updated too.
*
* Parameters: integer, the new gas amount
*
* Returns: bool - true if it is sucessful
*
* Emit the event `GasAcceptTransferChanged(oldValue, newValue)`.
*
*/
function setGasAcceptTransfer(uint256 newValue)
public
onlyOwner
returns (bool)
{
emit GasAcceptTransferChanged(gasAcceptTransfer, newValue);
gasAcceptTransfer = newValue;
require(_updateMinBRZFee(), "updateMinBRZFee error");
return true;
}
/**
* @dev Returns the minimum token amount to cross.
*
* The function acceptTransfer can not accpept less than the minimum per blockchain.
*
* Parameters: string, blockchain name
*
* Returns: integer
*
*/
function getMinTokenAmount(string memory blockchainName)
external
view
override
returns (uint256)
{
return blockchainInfo[blockchainIndex[blockchainName] - 1].minTokenAmount;
}
/**
* @dev This function update the minimum token's amount to be crossed.
*
* Only admin can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: integer, the new amount
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - blockchain must exists.
*
* Emit the event `MinTokenAmountChanged(blockchain, oldMinimumAmount, newMinimumAmount)`.
*
*/
function setMinTokenAmount(string memory blockchainName, uint256 newAmount)
public
onlyAdmin
whenNotPaused
returns (bool)
{
require(existsBlockchain(blockchainName), "blockchain not exists");
uint256 index = blockchainIndex[blockchainName] - 1;
emit MinTokenAmountChanged(
blockchainName,
blockchainInfo[index].minTokenAmount,
newAmount
);
blockchainInfo[index].minTokenAmount = newAmount;
return true;
}
/**
* @dev This function update the fee percentage bridge.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: integer, the new fee
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - The new fee must be lower than 10% .
*
* Emit the event `FeePercentageBridgeChanged(oldFee, newFee)`.
*
*/
function setFeePercentageBridge(uint256 newFee)
external
onlyOwner
whenNotPaused
returns (bool)
{
require(newFee < (DECIMALPERCENT / 10), "bigger than 10%");
emit FeePercentageBridgeChanged(feePercentageBridge, newFee);
feePercentageBridge = newFee;
return true;
}
/**
* @dev This function update the BRZ token.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: address of new BRZ token
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - The token address must not be a zero address.
*
* Emit the event `TokenChanged(tokenAddress)`.
*
*/
function setToken(address tokenAddress)
external
onlyOwner
whenNotPaused
returns (bool)
{
require(tokenAddress != ZERO_ADDRESS, "zero address");
emit TokenChanged(tokenAddress);
token = IERC20(tokenAddress);
return true;
}
/**
* @dev Returns if a blockchain is in the list of allowed blockchains to cross tokens using the bridge.
*
* Parameters: string name of blockchain
*
* Returns: boolean true if it is in the list
*
*/
function existsBlockchain(string memory name)
public
view
override
returns (bool)
{
if (blockchainIndex[name] == 0) return false;
else return true;
}
/**
* @dev List of blockchains allowed to cross tokens using the bridge.
*
* Parameters: none
*
* Returns: an array of strings containing the blockchain list
*
*/
function listBlockchain() external view override returns (string[] memory) {
return blockchain;
}
/**
* @dev This function include a new blockchain in the list of allowed blockchains used in the bridge.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters:
* - string name of blockchain to be added
* - minGasPrice
* - minTokenAmount
* - check address EVM compatible
*
* Returns: index of blockchain.
*
* Important:
* - index start in 1, not 0.
* - index 0 means that the blockchain does no exist.
* - index 1 means that it is the position 0 in the array.
*
* Requirements:
* - blockchain not exists.
* - onlyOwner
* - whenNotPaused
*/
function addBlockchain(
string memory name,
uint256 minGasPrice,
uint256 minTokenAmount,
bool checkAddress
) external onlyOwner whenNotPaused returns (uint256) {
require(!existsBlockchain(name), "blockchain exists");
BlockchainStruct memory b;
b.minGasPrice = minGasPrice;
b.minTokenAmount = minTokenAmount;
b.minBRZFee = (gasAcceptTransfer * minGasPrice * quoteETH_BRZ) / (1 ether);
b.checkAddress = checkAddress;
blockchainInfo.push(b);
blockchain.push(name);
uint256 index = blockchainInfo.length;
blockchainIndex[name] = index;
return (index);
}
/**
* @dev This function exclude a blockchain in the list of allowed blockchains used in the bridge.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: string name of blockchain to be excluded
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - blockchain exists.
* - there must be at least one blockchain left.
*
*/
function delBlockchain(string memory name)
external
onlyOwner
whenNotPaused
returns (bool)
{
require(existsBlockchain(name), "blockchain not exists");
require(blockchainInfo.length > 1, "requires at least 1 blockchain");
uint256 indexToDelete = blockchainIndex[name] - 1;
uint256 indexToMove = blockchainInfo.length - 1;
//string memory keyToMove = blockchainInfo[indexToMove].name;
string memory keyToMove = blockchain[indexToMove];
blockchainInfo[indexToDelete] = blockchainInfo[indexToMove];
blockchain[indexToDelete] = blockchain[indexToMove];
blockchainIndex[keyToMove] = indexToDelete + 1;
delete blockchainIndex[name];
blockchainInfo.pop();
blockchain.pop();
return true;
}
/**
* @dev This function pauses the bridge.
*
* Only owner can call it.
*
* Parameters: none
*
* Returns: none
*
* Requirements:
*
* - The contract must not be paused.
*
*/
function pause() external onlyOwner {
/**
* @dev See {Pausable-_pause}.
*
* Requirements:
*
* - The contract must not be paused.
*/
_pause();
}
/**
* @dev This function unpauses the bridge.
*
* Only owner can call it.
*
* Parameters: none
*
* Returns: none
*
* Requirements:
*
* - The contract must be paused.
*/
function unpause() external onlyOwner {
/**
* @dev See {Pausable-_unpause}.
*
* Requirements:
*
* - The contract must be paused.
*/
_unpause();
}
}
| This function pauses the bridge. Only owner can call it. Parameters: none Returns: none Requirements: - The contract must not be paused./ | function pause() external onlyOwner {
_pause();
| 12,927,610 |
//Address: 0xd73be539d6b2076bab83ca6ba62dfe189abc6bbe
//Contract name: BlockchainCutiesCore
//Balance: 20.223731891324013681 Ether
//Verification Date: 4/25/2018
//Transacion Count: 8014
// CODE STARTS HERE
pragma solidity ^0.4.20;
/// BlockchainCuties: Collectible and breedable cuties on the Ethereum blockchain.
/// https://blockchaincuties.co/
/// @title defined the interface that will be referenced in main Cutie contract
contract GeneMixerInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isGeneMixer() external pure returns (bool);
/// @dev given genes of cutie 1 & 2, return a genetic combination - may have a random factor
/// @param genes1 genes of mom
/// @param genes2 genes of dad
/// @return the genes that are supposed to be passed down the child
function mixGenes(uint256 genes1, uint256 genes2) public view returns (uint256);
function canBreed(uint40 momId, uint256 genes1, uint40 dadId, uint256 genes2) public view returns (bool);
}
/// @author https://BlockChainArchitect.iocontract Bank is CutiePluginBase
contract PluginInterface
{
/// @dev simply a boolean to indicate this is the contract we expect to be
function isPluginInterface() public pure returns (bool);
function onRemove() public;
/// @dev Begins new feature.
/// @param _cutieId - ID of token to auction, sender must be owner.
/// @param _parameter - arbitrary parameter
/// @param _seller - Old owner, if not the message sender
function run(
uint40 _cutieId,
uint256 _parameter,
address _seller
)
public
payable;
/// @dev Begins new feature, approved and signed by COO.
/// @param _cutieId - ID of token to auction, sender must be owner.
/// @param _parameter - arbitrary parameter
function runSigned(
uint40 _cutieId,
uint256 _parameter,
address _owner
)
external
payable;
function withdraw() public;
}
/// @title Auction Market for Blockchain Cuties.
/// @author https://BlockChainArchitect.io
contract MarketInterface
{
function withdrawEthFromBalance() external;
function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public payable;
function bid(uint40 _cutieId) public payable;
function cancelActiveAuctionWhenPaused(uint40 _cutieId) public;
function getAuctionInfo(uint40 _cutieId)
public
view
returns
(
address seller,
uint128 startPrice,
uint128 endPrice,
uint40 duration,
uint40 startedAt,
uint128 featuringFee
);
}
/// @title BlockchainCuties: Collectible and breedable cuties on the Ethereum blockchain.
/// @author https://BlockChainArchitect.io
/// @dev This is the BlockchainCuties configuration. It can be changed redeploying another version.
contract ConfigInterface
{
function isConfig() public pure returns (bool);
function getCooldownIndexFromGeneration(uint16 _generation) public view returns (uint16);
function getCooldownEndTimeFromIndex(uint16 _cooldownIndex) public view returns (uint40);
function getCooldownIndexCount() public view returns (uint256);
function getBabyGen(uint16 _momGen, uint16 _dadGen) public pure returns (uint16);
function getTutorialBabyGen(uint16 _dadGen) public pure returns (uint16);
function getBreedingFee(uint40 _momId, uint40 _dadId) public pure returns (uint256);
}
/// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. This function MUST use 50,000 gas or less. Return of other
/// than the magic value MUST result in the transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _from The sending address
/// @param _tokenId The NFT identifier which is being transfered
/// @param data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
/// @title BlockchainCuties: Collectible and breedable cuties on the Ethereum blockchain.
/// @author https://BlockChainArchitect.io
/// @dev This is the main BlockchainCuties contract. For separated logical sections the code is divided in
// several separately-instantiated sibling contracts that handle auctions and the genetic combination algorithm.
// By keeping auctions separate it is possible to upgrade them without disrupting the main contract that tracks
// the ownership of the cutie. The genetic combination algorithm is kept separate so that all of the rest of the
// code can be open-sourced.
// The contracts:
//
// - BlockchainCuties: The fundamental code, including main data storage, constants and data types, as well as
// internal functions for managing these items ans ERC-721 implementation.
// Various addresses and constraints for operations can be executed only by specific roles -
// Owner, Operator and Parties.
// Methods for interacting with additional features (Plugins).
// The methods for breeding and keeping track of breeding offers, relies on external genetic combination
// contract.
// Public methods for auctioning or bidding or breeding.
//
// - SaleMarket and BreedingMarket: The actual auction functionality is handled in two sibling contracts - one
// for sales and one for breeding. Auction creation and bidding is mostly mediated through this side of
// the core contract.
//
// - Effects: Contracts allow to use item effects on cuties, implemented as plugins. Items are not stored in
// blockchain to not overload Ethereum network. Operator generates signatures, and Plugins check it
// and perform effect.
//
// - ItemMarket: Plugin contract used to transfer money from buyer to seller.
//
// - Bank: Plugin contract used to receive payments for payed features.
contract BlockchainCutiesCore /*is ERC721, CutieCoreInterface*/
{
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure returns (string _name)
{
return "BlockchainCuties";
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure returns (string _symbol)
{
return "BC";
}
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external pure returns (bool)
{
return
interfaceID == 0x6466353c ||
interfaceID == bytes4(keccak256('supportsInterface(bytes4)'));
}
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @dev The Birth event is fired as soon as a new cutie is created. This
/// is any time a cutie comes into existence through the giveBirth method, as well as
/// when a new gen0 cutie is created.
event Birth(address indexed owner, uint40 cutieId, uint40 momId, uint40 dadId, uint256 genes);
/// @dev This struct represents a blockchain Cutie. It was ensured that struct fits well into
/// exactly two 256-bit words. The order of the members in this structure
/// matters because of the Ethereum byte-packing rules.
/// Reference: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Cutie
{
// The Cutie's genetic code is in these 256-bits. Cutie's genes never change.
uint256 genes;
// The timestamp from the block when this cutie was created.
uint40 birthTime;
// The minimum timestamp after which the cutie can start breeding
// again.
uint40 cooldownEndTime;
// The cutie's parents ID is set to 0 for gen0 cuties.
// Because of using 32-bit unsigned integers the limit is 4 billion cuties.
// Current Ethereum annual limit is about 500 million transactions.
uint40 momId;
uint40 dadId;
// Set the index in the cooldown array (see below) that means
// the current cooldown duration for this Cutie. Starts at 0
// for gen0 cats, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding, regardless
// of being cutie mom or cutie dad.
uint16 cooldownIndex;
// The "generation number" of the cutie. Cutioes minted by the contract
// for sale are called "gen0" with generation number of 0. All other cuties'
// generation number is the larger of their parents' two generation
// numbers, plus one (i.e. max(mom.generation, dad.generation) + 1)
uint16 generation;
// Some optional data used by external contracts
// Cutie struct is 2x256 bits long.
uint64 optional;
}
/// @dev An array containing the Cutie struct for all Cuties in existence. The ID
/// of each cutie is actually an index into this array. ID 0 is the parent
/// of all generation 0 cats, and both parents to itself. It is an invalid genetic code.
Cutie[] public cuties;
/// @dev A mapping from cutie IDs to the address that owns them. All cuties have
/// some valid owner address, even gen0 cuties are created with a non-zero owner.
mapping (uint40 => address) public cutieIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev A mapping from CutieIDs to an address that has been approved to call
/// transferFrom(). A Cutie can have one approved address for transfer
/// at any time. A zero value means that there is no outstanding approval.
mapping (uint40 => address) public cutieIndexToApproved;
/// @dev A mapping from CutieIDs to an address that has been approved to use
/// this Cutie for breeding via breedWith(). A Cutie can have one approved
/// address for breeding at any time. A zero value means that there is no outstanding approval.
mapping (uint40 => address) public sireAllowedToAddress;
/// @dev The address of the Market contract used to sell cuties. This
/// contract used both peer-to-peer sales and the gen0 sales that are
/// initiated each 15 minutes.
MarketInterface public saleMarket;
/// @dev The address of a custom Market subclassed contract used for breeding
/// auctions. Is to be separated from saleMarket as the actions taken on success
/// after a sales and breeding auction are quite different.
MarketInterface public breedingMarket;
// Modifiers to check that inputs can be safely stored with a certain
// number of bits.
modifier canBeStoredIn40Bits(uint256 _value) {
require(_value <= 0xFFFFFFFFFF);
_;
}
/// @notice Returns the total number of Cuties in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() external view returns (uint256)
{
return cuties.length - 1;
}
/// @notice Returns the total number of Cuties in existence.
/// @dev Required for ERC-721 compliance.
function _totalSupply() internal view returns (uint256)
{
return cuties.length - 1;
}
// Internal utility functions assume that their input arguments
// are valid. Public methods sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a certain Cutie.
/// @param _claimant the address we are validating against.
/// @param _cutieId cutie id, only valid when > 0
function _isOwner(address _claimant, uint40 _cutieId) internal view returns (bool)
{
return cutieIndexToOwner[_cutieId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a certain Cutie.
/// @param _claimant the address we are confirming the cutie is approved for.
/// @param _cutieId cutie id, only valid when > 0
function _approvedFor(address _claimant, uint40 _cutieId) internal view returns (bool)
{
return cutieIndexToApproved[_cutieId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is done on purpose:
/// _approve() and transferFrom() are used together for putting Cuties on auction.
/// There is no value in spamming the log with Approval events in that case.
function _approve(uint40 _cutieId, address _approved) internal
{
cutieIndexToApproved[_cutieId] = _approved;
}
/// @notice Returns the number of Cuties owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) external view returns (uint256 count)
{
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Cutie to another address. When transferring to a smart
/// contract, ensure that it is aware of ERC-721 (or
/// BlockchainCuties specifically), otherwise the Cutie may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _cutieId The ID of the Cutie to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _cutieId) external whenNotPaused canBeStoredIn40Bits(_cutieId)
{
// You can only send your own cutie.
require(_isOwner(msg.sender, uint40(_cutieId)));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, uint40(_cutieId));
}
/// @notice Grant another address the right to transfer a perticular Cutie via transferFrom().
/// This flow is preferred for transferring NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to clear all approvals.
/// @param _cutieId The ID of the Cutie that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _cutieId) external whenNotPaused canBeStoredIn40Bits(_cutieId)
{
// Only cutie's owner can grant transfer approval.
require(_isOwner(msg.sender, uint40(_cutieId)));
// Registering approval replaces any previous approval.
_approve(uint40(_cutieId), _to);
// Emit approval event.
emit Approval(msg.sender, _to, _cutieId);
}
/// @notice Transfers the ownership of an NFT from one address to another address.
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data)
external whenNotPaused canBeStoredIn40Bits(_tokenId)
{
require(_to != address(0));
require(_to != address(this));
require(_to != address(saleMarket));
require(_to != address(breedingMarket));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, uint40(_tokenId)) || _isApprovedForAll(_from, msg.sender));
require(_isOwner(_from, uint40(_tokenId)));
// Reassign ownership, clearing pending approvals and emitting Transfer event.
_transfer(_from, _to, uint40(_tokenId));
ERC721TokenReceiver (_to).onERC721Received(_from, _tokenId, data);
}
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to ""
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
external whenNotPaused canBeStoredIn40Bits(_tokenId)
{
require(_to != address(0));
require(_to != address(this));
require(_to != address(saleMarket));
require(_to != address(breedingMarket));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, uint40(_tokenId)) || _isApprovedForAll(_from, msg.sender));
require(_isOwner(_from, uint40(_tokenId)));
// Reassign ownership, clearing pending approvals and emitting Transfer event.
_transfer(_from, _to, uint40(_tokenId));
}
/// @notice Transfer a Cutie owned by another address, for which the calling address
/// has been granted transfer approval by the owner.
/// @param _from The address that owns the Cutie to be transfered.
/// @param _to Any address, including the caller address, can take ownership of the Cutie.
/// @param _tokenId The ID of the Cutie to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint256 _tokenId)
external whenNotPaused canBeStoredIn40Bits(_tokenId)
{
// Check for approval and valid ownership
require(_approvedFor(msg.sender, uint40(_tokenId)) || _isApprovedForAll(_from, msg.sender));
require(_isOwner(_from, uint40(_tokenId)));
// Reassign ownership, clearing pending approvals and emitting Transfer event.
_transfer(_from, _to, uint40(_tokenId));
}
/// @notice Returns the address currently assigned ownership of a given Cutie.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _cutieId)
external
view
canBeStoredIn40Bits(_cutieId)
returns (address owner)
{
owner = cutieIndexToOwner[uint40(_cutieId)];
require(owner != address(0));
}
/// @notice Returns the nth Cutie assigned to an address, with n specified by the
/// _index argument.
/// @param _owner The owner of the Cuties we are interested in.
/// @param _index The zero-based index of the cutie within the owner's list of cuties.
/// Must be less than balanceOf(_owner).
/// @dev This method must not be called by smart contract code. It will almost
/// certainly blow past the block gas limit once there are a large number of
/// Cuties in existence. Exists only to allow off-chain queries of ownership.
/// Optional method for ERC-721.
function tokenOfOwnerByIndex(address _owner, uint256 _index)
external
view
returns (uint256 cutieId)
{
uint40 count = 0;
for (uint40 i = 1; i <= _totalSupply(); ++i) {
if (cutieIndexToOwner[i] == _owner) {
if (count == _index) {
return i;
} else {
count++;
}
}
}
revert();
}
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external pure returns (uint256)
{
return _index;
}
/// @dev A mapping from Cuties owner (account) to an address that has been approved to call
/// transferFrom() for all cuties, owned by owner.
/// Only one approved address is permitted for each account for transfer
/// at any time. A zero value means there is no outstanding approval.
mapping (address => address) public addressToApprovedAll;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all your asset.
/// @dev Emits the ApprovalForAll event
/// @param _operator Address to add to the set of authorized operators.
/// @param _approved True if the operators is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external
{
if (_approved)
{
addressToApprovedAll[msg.sender] = _operator;
}
else
{
delete addressToApprovedAll[msg.sender];
}
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId)
external view canBeStoredIn40Bits(_tokenId)
returns (address)
{
require(_tokenId <= _totalSupply());
if (cutieIndexToApproved[uint40(_tokenId)] != address(0))
{
return cutieIndexToApproved[uint40(_tokenId)];
}
address owner = cutieIndexToOwner[uint40(_tokenId)];
return addressToApprovedAll[owner];
}
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool)
{
return addressToApprovedAll[_owner] == _operator;
}
function _isApprovedForAll(address _owner, address _operator) internal view returns (bool)
{
return addressToApprovedAll[_owner] == _operator;
}
ConfigInterface public config;
/// @dev Update the address of the config contract.
/// @param _address An address of a ConfigInterface contract instance to be used from this point forward.
function setConfigAddress(address _address) public onlyOwner
{
ConfigInterface candidateContract = ConfigInterface(_address);
require(candidateContract.isConfig());
// Set the new contract address
config = candidateContract;
}
function getCooldownIndexFromGeneration(uint16 _generation) internal view returns (uint16)
{
return config.getCooldownIndexFromGeneration(_generation);
}
/// @dev An internal method that creates a new cutie and stores it. This
/// method does not check anything and should only be called when the
/// input data is valid for sure. Will generate both a Birth event
/// and a Transfer event.
/// @param _momId The cutie ID of the mom of this cutie (zero for gen0)
/// @param _dadId The cutie ID of the dad of this cutie (zero for gen0)
/// @param _generation The generation number of this cutie, must be computed by caller.
/// @param _genes The cutie's genetic code.
/// @param _owner The initial owner of this cutie, must be non-zero (except for the unCutie, ID 0)
function _createCutie(
uint40 _momId,
uint40 _dadId,
uint16 _generation,
uint16 _cooldownIndex,
uint256 _genes,
address _owner,
uint40 _birthTime
)
internal
returns (uint40)
{
Cutie memory _cutie = Cutie({
genes: _genes,
birthTime: _birthTime,
cooldownEndTime: 0,
momId: _momId,
dadId: _dadId,
cooldownIndex: _cooldownIndex,
generation: _generation,
optional: 0
});
uint256 newCutieId256 = cuties.push(_cutie) - 1;
// Check if id can fit into 40 bits
require(newCutieId256 <= 0xFFFFFFFFFF);
uint40 newCutieId = uint40(newCutieId256);
// emit the birth event
emit Birth(_owner, newCutieId, _cutie.momId, _cutie.dadId, _cutie.genes);
// This will assign ownership, as well as emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newCutieId);
return newCutieId;
}
/// @notice Returns all the relevant information about a certain cutie.
/// @param _id The ID of the cutie of interest.
function getCutie(uint40 _id)
external
view
returns (
uint256 genes,
uint40 birthTime,
uint40 cooldownEndTime,
uint40 momId,
uint40 dadId,
uint16 cooldownIndex,
uint16 generation
) {
Cutie storage cutie = cuties[_id];
genes = cutie.genes;
birthTime = cutie.birthTime;
cooldownEndTime = cutie.cooldownEndTime;
momId = cutie.momId;
dadId = cutie.dadId;
cooldownIndex = cutie.cooldownIndex;
generation = cutie.generation;
}
/// @dev Assigns ownership of a particular Cutie to an address.
function _transfer(address _from, address _to, uint40 _cutieId) internal {
// since the number of cuties is capped to 2^40
// there is no way to overflow this
ownershipTokenCount[_to]++;
// transfer ownership
cutieIndexToOwner[_cutieId] = _to;
// When creating new cuties _from is 0x0, but we cannot account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// once the cutie is transferred also clear breeding allowances
delete sireAllowedToAddress[_cutieId];
// clear any previously approved ownership exchange
delete cutieIndexToApproved[_cutieId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _cutieId);
}
/// @dev For transferring a cutie owned by this contract to the specified address.
/// Used to rescue lost cuties. (There is no "proper" flow where this contract
/// should be the owner of any Cutie. This function exists for us to reassign
/// the ownership of Cuties that users may have accidentally sent to our address.)
/// @param _cutieId - ID of cutie
/// @param _recipient - Address to send the cutie to
function restoreCutieToAddress(uint40 _cutieId, address _recipient) public onlyOperator whenNotPaused {
require(_isOwner(this, _cutieId));
_transfer(this, _recipient, _cutieId);
}
address ownerAddress;
address operatorAddress;
bool public paused = false;
modifier onlyOwner()
{
require(msg.sender == ownerAddress);
_;
}
function setOwner(address _newOwner) public onlyOwner
{
require(_newOwner != address(0));
ownerAddress = _newOwner;
}
modifier onlyOperator() {
require(msg.sender == operatorAddress || msg.sender == ownerAddress);
_;
}
function setOperator(address _newOperator) public onlyOwner {
require(_newOperator != address(0));
operatorAddress = _newOperator;
}
modifier whenNotPaused()
{
require(!paused);
_;
}
modifier whenPaused
{
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused
{
paused = true;
}
string public metadataUrlPrefix = "https://blockchaincuties.co/cutie/";
string public metadataUrlSuffix = ".svg";
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string infoUrl)
{
return
concat(toSlice(metadataUrlPrefix),
toSlice(concat(toSlice(uintToString(_tokenId)), toSlice(metadataUrlSuffix))));
}
function setMetadataUrl(string _metadataUrlPrefix, string _metadataUrlSuffix) public onlyOwner
{
metadataUrlPrefix = _metadataUrlPrefix;
metadataUrlSuffix = _metadataUrlSuffix;
}
mapping(address => PluginInterface) public plugins;
PluginInterface[] public pluginsArray;
mapping(uint40 => address) public usedSignes;
uint40 public minSignId;
event GenesChanged(uint40 indexed cutieId, uint256 oldValue, uint256 newValue);
event CooldownEndTimeChanged(uint40 indexed cutieId, uint40 oldValue, uint40 newValue);
event CooldownIndexChanged(uint40 indexed cutieId, uint16 ololdValue, uint16 newValue);
event GenerationChanged(uint40 indexed cutieId, uint16 oldValue, uint16 newValue);
event OptionalChanged(uint40 indexed cutieId, uint64 oldValue, uint64 newValue);
event SignUsed(uint40 signId, address sender);
event MinSignSet(uint40 signId);
/// @dev Sets the reference to the plugin contract.
/// @param _address - Address of plugin contract.
function addPlugin(address _address) public onlyOwner
{
PluginInterface candidateContract = PluginInterface(_address);
// verify that a contract is what we expect
require(candidateContract.isPluginInterface());
// Set the new contract address
plugins[_address] = candidateContract;
pluginsArray.push(candidateContract);
}
/// @dev Remove plugin and calls onRemove to cleanup
function removePlugin(address _address) public onlyOwner
{
plugins[_address].onRemove();
delete plugins[_address];
uint256 kindex = 0;
while (kindex < pluginsArray.length)
{
if (address(pluginsArray[kindex]) == _address)
{
pluginsArray[kindex] = pluginsArray[pluginsArray.length-1];
pluginsArray.length--;
}
else
{
kindex++;
}
}
}
/// @dev Put a cutie up for plugin feature.
function runPlugin(
address _pluginAddress,
uint40 _cutieId,
uint256 _parameter
)
public
whenNotPaused
payable
{
// If cutie is already on any auction or in adventure, this will throw
// because it will be owned by the other contract.
// If _cutieId is 0, then cutie is not used on this feature.
require(_cutieId == 0 || _isOwner(msg.sender, _cutieId));
require(address(plugins[_pluginAddress]) != address(0));
if (_cutieId > 0)
{
_approve(_cutieId, _pluginAddress);
}
// Plugin contract throws if inputs are invalid and clears
// transfer after escrowing the cutie.
plugins[_pluginAddress].run.value(msg.value)(
_cutieId,
_parameter,
msg.sender
);
}
/// @dev Called from plugin contract when using items as effect
function getGenes(uint40 _id)
public
view
returns (
uint256 genes
)
{
Cutie storage cutie = cuties[_id];
genes = cutie.genes;
}
/// @dev Called from plugin contract when using items as effect
function changeGenes(
uint40 _cutieId,
uint256 _genes)
public
whenNotPaused
{
// if caller is registered plugin contract
require(address(plugins[msg.sender]) != address(0));
Cutie storage cutie = cuties[_cutieId];
if (cutie.genes != _genes)
{
emit GenesChanged(_cutieId, cutie.genes, _genes);
cutie.genes = _genes;
}
}
function getCooldownEndTime(uint40 _id)
public
view
returns (
uint40 cooldownEndTime
) {
Cutie storage cutie = cuties[_id];
cooldownEndTime = cutie.cooldownEndTime;
}
function changeCooldownEndTime(
uint40 _cutieId,
uint40 _cooldownEndTime)
public
whenNotPaused
{
require(address(plugins[msg.sender]) != address(0));
Cutie storage cutie = cuties[_cutieId];
if (cutie.cooldownEndTime != _cooldownEndTime)
{
emit CooldownEndTimeChanged(_cutieId, cutie.cooldownEndTime, _cooldownEndTime);
cutie.cooldownEndTime = _cooldownEndTime;
}
}
function getCooldownIndex(uint40 _id)
public
view
returns (
uint16 cooldownIndex
) {
Cutie storage cutie = cuties[_id];
cooldownIndex = cutie.cooldownIndex;
}
function changeCooldownIndex(
uint40 _cutieId,
uint16 _cooldownIndex)
public
whenNotPaused
{
require(address(plugins[msg.sender]) != address(0));
Cutie storage cutie = cuties[_cutieId];
if (cutie.cooldownIndex != _cooldownIndex)
{
emit CooldownIndexChanged(_cutieId, cutie.cooldownIndex, _cooldownIndex);
cutie.cooldownIndex = _cooldownIndex;
}
}
function changeGeneration(
uint40 _cutieId,
uint16 _generation)
public
whenNotPaused
{
require(address(plugins[msg.sender]) != address(0));
Cutie storage cutie = cuties[_cutieId];
if (cutie.generation != _generation)
{
emit GenerationChanged(_cutieId, cutie.generation, _generation);
cutie.generation = _generation;
}
}
function getGeneration(uint40 _id)
public
view
returns (uint16 generation)
{
Cutie storage cutie = cuties[_id];
generation = cutie.generation;
}
function changeOptional(
uint40 _cutieId,
uint64 _optional)
public
whenNotPaused
{
require(address(plugins[msg.sender]) != address(0));
Cutie storage cutie = cuties[_cutieId];
if (cutie.optional != _optional)
{
emit OptionalChanged(_cutieId, cutie.optional, _optional);
cutie.optional = _optional;
}
}
function getOptional(uint40 _id)
public
view
returns (uint64 optional)
{
Cutie storage cutie = cuties[_id];
optional = cutie.optional;
}
/// @dev Common function to be used also in backend
function hashArguments(
address _pluginAddress,
uint40 _signId,
uint40 _cutieId,
uint128 _value,
uint256 _parameter)
public pure returns (bytes32 msgHash)
{
msgHash = keccak256(_pluginAddress, _signId, _cutieId, _value, _parameter);
}
/// @dev Common function to be used also in backend
function getSigner(
address _pluginAddress,
uint40 _signId,
uint40 _cutieId,
uint128 _value,
uint256 _parameter,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public pure returns (address)
{
bytes32 msgHash = hashArguments(_pluginAddress, _signId, _cutieId, _value, _parameter);
return ecrecover(msgHash, _v, _r, _s);
}
/// @dev Common function to be used also in backend
function isValidSignature(
address _pluginAddress,
uint40 _signId,
uint40 _cutieId,
uint128 _value,
uint256 _parameter,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
view
returns (bool)
{
return getSigner(_pluginAddress, _signId, _cutieId, _value, _parameter, _v, _r, _s) == operatorAddress;
}
/// @dev Put a cutie up for plugin feature with signature.
/// Can be used for items equip, item sales and other features.
/// Signatures are generated by Operator role.
function runPluginSigned(
address _pluginAddress,
uint40 _signId,
uint40 _cutieId,
uint128 _value,
uint256 _parameter,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
whenNotPaused
payable
{
// If cutie is already on any auction or in adventure, this will throw
// as it will be owned by the other contract.
// If _cutieId is 0, then cutie is not used on this feature.
require(_cutieId == 0 || _isOwner(msg.sender, _cutieId));
require(address(plugins[_pluginAddress]) != address(0));
require (usedSignes[_signId] == address(0));
require (_signId >= minSignId);
// value can also be zero for free calls
require (_value <= msg.value);
require (isValidSignature(_pluginAddress, _signId, _cutieId, _value, _parameter, _v, _r, _s));
usedSignes[_signId] = msg.sender;
emit SignUsed(_signId, msg.sender);
// Plugin contract throws if inputs are invalid and clears
// transfer after escrowing the cutie.
plugins[_pluginAddress].runSigned.value(_value)(
_cutieId,
_parameter,
msg.sender
);
}
/// @dev Sets minimal signId, than can be used.
/// All unused signatures less than signId will be cancelled on off-chain server
/// and unused items will be transfered back to owner.
function setMinSign(uint40 _newMinSignId)
public
onlyOperator
{
require (_newMinSignId > minSignId);
minSignId = _newMinSignId;
emit MinSignSet(minSignId);
}
event BreedingApproval(address indexed _owner, address indexed _approved, uint256 _tokenId);
// Set in case the core contract is broken and an upgrade is required
address public upgradedContractAddress;
function isCutieCore() pure public returns (bool) { return true; }
/// @notice Creates the main BlockchainCuties smart contract instance.
function BlockchainCutiesCore() public
{
// Starts paused.
paused = true;
// the creator of the contract is the initial owner
ownerAddress = msg.sender;
// the creator of the contract is also the initial operator
operatorAddress = msg.sender;
// start with the mythical cutie 0 - so there are no generation-0 parent issues
_createCutie(0, 0, 0, 0, uint256(-1), address(0), 0);
}
event ContractUpgrade(address newContract);
/// @dev Aimed to mark the smart contract as upgraded if there is a crucial
/// bug. This keeps track of the new contract and indicates that the new address is set.
/// Updating to the new contract address is up to the clients. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _newAddress new address
function setUpgradedAddress(address _newAddress) public onlyOwner whenPaused
{
require(_newAddress != address(0));
upgradedContractAddress = _newAddress;
emit ContractUpgrade(upgradedContractAddress);
}
/// @dev Import cuties from previous version of Core contract.
/// @param _oldAddress Old core contract address
/// @param _fromIndex (inclusive)
/// @param _toIndex (inclusive)
function migrate(address _oldAddress, uint40 _fromIndex, uint40 _toIndex) public onlyOwner whenPaused
{
require(_totalSupply() + 1 == _fromIndex);
BlockchainCutiesCore old = BlockchainCutiesCore(_oldAddress);
for (uint40 i = _fromIndex; i <= _toIndex; i++)
{
uint256 genes;
uint40 birthTime;
uint40 cooldownEndTime;
uint40 momId;
uint40 dadId;
uint16 cooldownIndex;
uint16 generation;
(genes, birthTime, cooldownEndTime, momId, dadId, cooldownIndex, generation) = old.getCutie(i);
Cutie memory _cutie = Cutie({
genes: genes,
birthTime: birthTime,
cooldownEndTime: cooldownEndTime,
momId: momId,
dadId: dadId,
cooldownIndex: cooldownIndex,
generation: generation,
optional: 0
});
cuties.push(_cutie);
}
}
/// @dev Import cuties from previous version of Core contract (part 2).
/// @param _oldAddress Old core contract address
/// @param _fromIndex (inclusive)
/// @param _toIndex (inclusive)
function migrate2(address _oldAddress, uint40 _fromIndex, uint40 _toIndex, address saleAddress, address breedingAddress) public onlyOwner whenPaused
{
BlockchainCutiesCore old = BlockchainCutiesCore(_oldAddress);
MarketInterface oldSaleMarket = MarketInterface(saleAddress);
MarketInterface oldBreedingMarket = MarketInterface(breedingAddress);
for (uint40 i = _fromIndex; i <= _toIndex; i++)
{
address owner = old.ownerOf(i);
if (owner == saleAddress)
{
(owner,,,,,) = oldSaleMarket.getAuctionInfo(i);
}
if (owner == breedingAddress)
{
(owner,,,,,) = oldBreedingMarket.getAuctionInfo(i);
}
_transfer(0, owner, i);
}
}
/// @dev Override unpause so it requires upgradedContractAddress not set, because then the contract was upgraded.
function unpause() public onlyOwner whenPaused
{
require(upgradedContractAddress == address(0));
paused = false;
}
// Counts the number of cuties the contract owner has created.
uint40 public promoCutieCreatedCount;
uint40 public gen0CutieCreatedCount;
uint40 public gen0Limit = 50000;
uint40 public promoLimit = 5000;
/// @dev Creates a new gen0 cutie with the given genes and
/// creates an auction for it.
function createGen0Auction(uint256 _genes, uint128 startPrice, uint128 endPrice, uint40 duration) public onlyOperator
{
require(gen0CutieCreatedCount < gen0Limit);
uint40 cutieId = _createCutie(0, 0, 0, 0, _genes, address(this), uint40(now));
_approve(cutieId, saleMarket);
saleMarket.createAuction(
cutieId,
startPrice,
endPrice,
duration,
address(this)
);
gen0CutieCreatedCount++;
}
function createPromoCutie(uint256 _genes, address _owner) public onlyOperator
{
require(promoCutieCreatedCount < promoLimit);
if (_owner == address(0)) {
_owner = operatorAddress;
}
promoCutieCreatedCount++;
gen0CutieCreatedCount++;
_createCutie(0, 0, 0, 0, _genes, _owner, uint40(now));
}
/// @dev Put a cutie up for auction to be dad.
/// Performs checks to ensure the cutie can be dad, then
/// delegates to reverse auction.
/// Optional money amount can be sent to contract to feature auction.
/// Pricea are available on web.
function createBreedingAuction(
uint40 _cutieId,
uint128 _startPrice,
uint128 _endPrice,
uint40 _duration
)
public
whenNotPaused
payable
{
// Auction contract checks input sizes
// If cutie is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_isOwner(msg.sender, _cutieId));
require(canBreed(_cutieId));
_approve(_cutieId, breedingMarket);
// breeding auction function is called if inputs are invalid and clears
// transfer and sire approval after escrowing the cutie.
breedingMarket.createAuction.value(msg.value)(
_cutieId,
_startPrice,
_endPrice,
_duration,
msg.sender
);
}
/// @dev Sets the reference to the breeding auction.
/// @param _breedingAddress - Address of breeding market contract.
/// @param _saleAddress - Address of sale market contract.
function setMarketAddress(address _breedingAddress, address _saleAddress) public onlyOwner
{
//require(address(breedingMarket) == address(0));
//require(address(saleMarket) == address(0));
breedingMarket = MarketInterface(_breedingAddress);
saleMarket = MarketInterface(_saleAddress);
}
/// @dev Completes a breeding auction by bidding.
/// Immediately breeds the winning mom with the dad on auction.
/// @param _dadId - ID of the dad on auction.
/// @param _momId - ID of the mom owned by the bidder.
function bidOnBreedingAuction(
uint40 _dadId,
uint40 _momId
)
public
payable
whenNotPaused
returns (uint256)
{
// Auction contract checks input sizes
require(_isOwner(msg.sender, _momId));
require(canBreed(_momId));
require(_canMateViaMarketplace(_momId, _dadId));
// Take breeding fee
uint256 fee = getBreedingFee(_momId, _dadId);
require(msg.value >= fee);
// breeding auction will throw if the bid fails.
breedingMarket.bid.value(msg.value - fee)(_dadId);
return _breedWith(_momId, _dadId);
}
/// @dev Put a cutie up for auction.
/// Does some ownership trickery for creating auctions in one transaction.
/// Optional money amount can be sent to contract to feature auction.
/// Pricea are available on web.
function createSaleAuction(
uint40 _cutieId,
uint128 _startPrice,
uint128 _endPrice,
uint40 _duration
)
public
whenNotPaused
payable
{
// Auction contract checks input sizes
// If cutie is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_isOwner(msg.sender, _cutieId));
_approve(_cutieId, saleMarket);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the cutie.
saleMarket.createAuction.value(msg.value)(
_cutieId,
_startPrice,
_endPrice,
_duration,
msg.sender
);
}
/// @dev The address of the sibling contract that is used to implement the genetic combination algorithm.
GeneMixerInterface geneMixer;
/// @dev Check if dad has authorized breeding with the mom. True if both dad
/// and mom have the same owner, or if the dad has given breeding permission to
/// the mom's owner (via approveBreeding()).
function _isBreedingPermitted(uint40 _dadId, uint40 _momId) internal view returns (bool)
{
address momOwner = cutieIndexToOwner[_momId];
address dadOwner = cutieIndexToOwner[_dadId];
// Breeding is approved if they have same owner, or if the mom's owner was given
// permission to breed with the dad.
return (momOwner == dadOwner || sireAllowedToAddress[_dadId] == momOwner);
}
/// @dev Update the address of the genetic contract.
/// @param _address An address of a GeneMixer contract instance to be used from this point forward.
function setGeneMixerAddress(address _address) public onlyOwner
{
GeneMixerInterface candidateContract = GeneMixerInterface(_address);
require(candidateContract.isGeneMixer());
// Set the new contract address
geneMixer = candidateContract;
}
/// @dev Checks that a given cutie is able to breed. Requires that the
/// current cooldown is finished (for dads)
function _canBreed(Cutie _cutie) internal view returns (bool)
{
return _cutie.cooldownEndTime <= now;
}
/// @notice Grants approval to another user to sire with one of your Cuties.
/// @param _addr The address that will be able to sire with your Cutie. Set to
/// address(0) to clear all breeding approvals for this Cutie.
/// @param _dadId A Cutie that you own that _addr will now be able to dad with.
function approveBreeding(address _addr, uint40 _dadId) public whenNotPaused
{
require(_isOwner(msg.sender, _dadId));
sireAllowedToAddress[_dadId] = _addr;
emit BreedingApproval(msg.sender, _addr, _dadId);
}
/// @dev Set the cooldownEndTime for the given Cutie, based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _cutie A reference to the Cutie in storage which needs its timer started.
function _triggerCooldown(uint40 _cutieId, Cutie storage _cutie) internal
{
// Compute the end of the cooldown time, based on current cooldownIndex
uint40 oldValue = _cutie.cooldownIndex;
_cutie.cooldownEndTime = config.getCooldownEndTimeFromIndex(_cutie.cooldownIndex);
emit CooldownEndTimeChanged(_cutieId, oldValue, _cutie.cooldownEndTime);
// Increment the breeding count.
if (_cutie.cooldownIndex + 1 < config.getCooldownIndexCount()) {
uint16 oldValue2 = _cutie.cooldownIndex;
_cutie.cooldownIndex++;
emit CooldownIndexChanged(_cutieId, oldValue2, _cutie.cooldownIndex);
}
}
/// @notice Checks that a certain cutie is not
/// in the middle of a breeding cooldown and is able to breed.
/// @param _cutieId reference the id of the cutie, any user can inquire about it
function canBreed(uint40 _cutieId)
public
view
returns (bool)
{
require(_cutieId > 0);
Cutie storage cutie = cuties[_cutieId];
return _canBreed(cutie);
}
/// @dev Check if given mom and dad are a valid mating pair.
function _canPairMate(
Cutie storage _mom,
uint40 _momId,
Cutie storage _dad,
uint40 _dadId
)
private
view
returns(bool)
{
// A Cutie can't breed with itself.
if (_dadId == _momId) {
return false;
}
// Cuties can't breed with their parents.
if (_mom.momId == _dadId) {
return false;
}
if (_mom.dadId == _dadId) {
return false;
}
if (_dad.momId == _momId) {
return false;
}
if (_dad.dadId == _momId) {
return false;
}
// We can short circuit the sibling check (below) if either cat is
// gen zero (has a mom ID of zero).
if (_dad.momId == 0) {
return true;
}
if (_mom.momId == 0) {
return true;
}
// Cuties can't breed with full or half siblings.
if (_dad.momId == _mom.momId) {
return false;
}
if (_dad.momId == _mom.dadId) {
return false;
}
if (_dad.dadId == _mom.momId) {
return false;
}
if (_dad.dadId == _mom.dadId) {
return false;
}
if (geneMixer.canBreed(_momId, _mom.genes, _dadId, _dad.genes)) {
return true;
}
return false;
}
/// @notice Checks to see if two cuties can breed together (checks both
/// ownership and breeding approvals, but does not check if both cuties are ready for
/// breeding).
/// @param _momId The ID of the proposed mom.
/// @param _dadId The ID of the proposed dad.
function canBreedWith(uint40 _momId, uint40 _dadId)
public
view
returns(bool)
{
require(_momId > 0);
require(_dadId > 0);
Cutie storage mom = cuties[_momId];
Cutie storage dad = cuties[_dadId];
return _canPairMate(mom, _momId, dad, _dadId) && _isBreedingPermitted(_dadId, _momId);
}
/// @dev Internal check to see if a given dad and mom are a valid mating pair for
/// breeding via market (this method doesn't check ownership and if mating is allowed).
function _canMateViaMarketplace(uint40 _momId, uint40 _dadId)
internal
view
returns (bool)
{
Cutie storage mom = cuties[_momId];
Cutie storage dad = cuties[_dadId];
return _canPairMate(mom, _momId, dad, _dadId);
}
function getBreedingFee(uint40 _momId, uint40 _dadId)
public
view
returns (uint256)
{
return config.getBreedingFee(_momId, _dadId);
}
/// @notice Breed cuties that you own, or for which you
/// have previously been given Breeding approval. Will either make your cutie give birth, or will
/// fail.
/// @param _momId The ID of the Cutie acting as mom (will end up give birth if successful)
/// @param _dadId The ID of the Cutie acting as dad (will begin its breeding cooldown if successful)
function breedWith(uint40 _momId, uint40 _dadId)
public
whenNotPaused
payable
returns (uint40)
{
// Caller must own the mom.
require(_isOwner(msg.sender, _momId));
// Neither dad nor mom can be on auction during
// breeding.
// For mom: The caller of this function can't be the owner of the mom
// because the owner of a Cutie on auction is the auction house, and the
// auction house will never call breedWith().
// For dad: Similarly, a dad on auction will be owned by the auction house
// and the act of transferring ownership will have cleared any outstanding
// breeding approval.
// Thus we don't need check if either cutie
// is on auction.
// Check that mom and dad are both owned by caller, or that the dad
// has given breeding permission to caller (i.e. mom's owner).
// Will fail for _dadId = 0
require(_isBreedingPermitted(_dadId, _momId));
// Check breeding fee
require(getBreedingFee(_momId, _dadId) <= msg.value);
// Grab a reference to the potential mom
Cutie storage mom = cuties[_momId];
// Make sure mom's cooldown isn't active, or in the middle of a breeding cooldown
require(_canBreed(mom));
// Grab a reference to the potential dad
Cutie storage dad = cuties[_dadId];
// Make sure dad cooldown isn't active, or in the middle of a breeding cooldown
require(_canBreed(dad));
// Test that these cuties are a valid mating pair.
require(_canPairMate(
mom,
_momId,
dad,
_dadId
));
return _breedWith(_momId, _dadId);
}
/// @dev Internal utility function to start breeding, assumes that all breeding
/// requirements have been checked.
function _breedWith(uint40 _momId, uint40 _dadId) internal returns (uint40)
{
// Grab a reference to the Cuties from storage.
Cutie storage dad = cuties[_dadId];
Cutie storage mom = cuties[_momId];
// Trigger the cooldown for both parents.
_triggerCooldown(_dadId, dad);
_triggerCooldown(_momId, mom);
// Clear breeding permission for both parents.
delete sireAllowedToAddress[_momId];
delete sireAllowedToAddress[_dadId];
// Check that the mom is a valid cutie.
require(mom.birthTime != 0);
// Determine the higher generation number of the two parents
uint16 babyGen = config.getBabyGen(mom.generation, dad.generation);
// Call the gene mixing operation.
uint256 childGenes = geneMixer.mixGenes(mom.genes, dad.genes);
// Make the new cutie
address owner = cutieIndexToOwner[_momId];
uint40 cutieId = _createCutie(_momId, _dadId, babyGen, getCooldownIndexFromGeneration(babyGen), childGenes, owner, mom.cooldownEndTime);
// return the new cutie's ID
return cutieId;
}
mapping(address => uint40) isTutorialPetUsed;
/// @dev Completes a breeding tutorial cutie (non existing in blockchain)
/// with auction by bidding. Immediately breeds with dad on auction.
/// @param _dadId - ID of the dad on auction.
function bidOnBreedingAuctionTutorial(
uint40 _dadId
)
public
payable
whenNotPaused
returns (uint)
{
require(isTutorialPetUsed[msg.sender] == 0);
// Take breeding fee
uint256 fee = getBreedingFee(0, _dadId);
require(msg.value >= fee);
// breeding auction will throw if the bid fails.
breedingMarket.bid.value(msg.value - fee)(_dadId);
// Grab a reference to the Cuties from storage.
Cutie storage dad = cuties[_dadId];
// Trigger the cooldown for parent.
_triggerCooldown(_dadId, dad);
// Clear breeding permission for parent.
delete sireAllowedToAddress[_dadId];
uint16 babyGen = config.getTutorialBabyGen(dad.generation);
// tutorial pet genome is zero
uint256 childGenes = geneMixer.mixGenes(0x0, dad.genes);
// tutorial pet id is zero
uint40 cutieId = _createCutie(0, _dadId, babyGen, getCooldownIndexFromGeneration(babyGen), childGenes, msg.sender, 12);
isTutorialPetUsed[msg.sender] = cutieId;
// return the new cutie's ID
return cutieId;
}
address party1address;
address party2address;
address party3address;
address party4address;
address party5address;
/// @dev Setup project owners
function setParties(address _party1, address _party2, address _party3, address _party4, address _party5) public onlyOwner
{
require(_party1 != address(0));
require(_party2 != address(0));
require(_party3 != address(0));
require(_party4 != address(0));
require(_party5 != address(0));
party1address = _party1;
party2address = _party2;
party3address = _party3;
party4address = _party4;
party5address = _party5;
}
/// @dev Reject all Ether which is not from game contracts from being sent here.
function() external payable {
require(
msg.sender == address(saleMarket) ||
msg.sender == address(breedingMarket) ||
address(plugins[msg.sender]) != address(0)
);
}
/// @dev The balance transfer from the market and plugins contract
/// to the CutieCore contract.
function withdrawBalances() external
{
require(
msg.sender == ownerAddress ||
msg.sender == operatorAddress);
saleMarket.withdrawEthFromBalance();
breedingMarket.withdrawEthFromBalance();
for (uint32 i = 0; i < pluginsArray.length; ++i)
{
pluginsArray[i].withdraw();
}
}
/// @dev The balance transfer from CutieCore contract to project owners
function withdrawEthFromBalance() external
{
require(
msg.sender == party1address ||
msg.sender == party2address ||
msg.sender == party3address ||
msg.sender == party4address ||
msg.sender == party5address ||
msg.sender == ownerAddress ||
msg.sender == operatorAddress);
require(party1address != 0);
require(party2address != 0);
require(party3address != 0);
require(party4address != 0);
require(party5address != 0);
uint256 total = address(this).balance;
party1address.transfer(total*105/1000);
party2address.transfer(total*105/1000);
party3address.transfer(total*140/1000);
party4address.transfer(total*140/1000);
party5address.transfer(total*510/1000);
}
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
struct slice
{
uint _len;
uint _ptr;
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string self) internal pure returns (slice)
{
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
function memcpy(uint dest, uint src, uint len) private pure
{
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice self, slice other) internal pure returns (string)
{
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
function uintToString(uint256 a) internal pure returns (string result)
{
string memory r = "";
do
{
uint b = a % 10;
a /= 10;
string memory c = "";
if (b == 0) c = "0";
else if (b == 1) c = "1";
else if (b == 2) c = "2";
else if (b == 3) c = "3";
else if (b == 4) c = "4";
else if (b == 5) c = "5";
else if (b == 6) c = "6";
else if (b == 7) c = "7";
else if (b == 8) c = "8";
else if (b == 9) c = "9";
r = concat(toSlice(c), toSlice(r));
}
while (a > 0);
result = r;
}
}
| Update the address of the genetic contract. _address An address of a GeneMixer contract instance to be used from this point forward. Set the new contract address | function setGeneMixerAddress(address _address) public onlyOwner
{
GeneMixerInterface candidateContract = GeneMixerInterface(_address);
require(candidateContract.isGeneMixer());
geneMixer = candidateContract;
}
| 12,941,826 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import { AddressAliasHelper } from "../../standards/AddressAliasHelper.sol";
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { ICanonicalTransactionChain } from "./ICanonicalTransactionChain.sol";
import { IChainStorageContainer } from "./IChainStorageContainer.sol";
/**
* @title CanonicalTransactionChain
* @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions
* which must be applied to the rollup state. It defines the ordering of rollup transactions by
* writing them to the 'CTC:batches' instance of the Chain Storage Container.
* The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the
* Sequencer will eventually append it to the rollup state.
*
* Runtime target: EVM
*/
contract CanonicalTransactionChain is ICanonicalTransactionChain, Lib_AddressResolver {
/*************
* Constants *
*************/
// L2 tx gas-related
uint256 public constant MIN_ROLLUP_TX_GAS = 100000;
uint256 public constant MAX_ROLLUP_TX_SIZE = 50000;
// The approximate cost of calling the enqueue function
uint256 public enqueueGasCost;
// The ratio of the cost of L1 gas to the cost of L2 gas
uint256 public l2GasDiscountDivisor;
// The amount of L2 gas which can be forwarded to L2 without spam prevention via 'gas burn'.
// Calculated as the product of l2GasDiscountDivisor * enqueueGasCost.
// See comments in enqueue() for further detail.
uint256 public enqueueL2GasPrepaid;
//default l2 chain id
uint256 constant public DEFAULT_CHAINID = 1088;
// Encoding-related (all in bytes)
uint256 internal constant BATCH_CONTEXT_SIZE = 16;
uint256 internal constant BATCH_CONTEXT_LENGTH_POS = 12;
uint256 internal constant BATCH_CONTEXT_START_POS = 15;
uint256 internal constant TX_DATA_HEADER_SIZE = 3;
uint256 internal constant BYTES_TILL_TX_DATA = 65;
/*************
* Variables *
*************/
uint256 public maxTransactionGasLimit;
/***************
* Queue State *
***************/
mapping(uint256=>uint40) private _nextQueueIndex; // index of the first queue element not yet included
mapping(uint256=>Lib_OVMCodec.QueueElement[]) queueElements;
/***************
* Constructor *
***************/
constructor(
address _libAddressManager,
uint256 _maxTransactionGasLimit,
uint256 _l2GasDiscountDivisor,
uint256 _enqueueGasCost
) Lib_AddressResolver(_libAddressManager)
{
maxTransactionGasLimit = _maxTransactionGasLimit;
l2GasDiscountDivisor = _l2GasDiscountDivisor;
enqueueGasCost = _enqueueGasCost;
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
}
/**********************
* Function Modifiers *
**********************/
/**
* Modifier to enforce that, if configured, only the Burn Admin may
* successfully call a method.
*/
modifier onlyBurnAdmin() {
require(msg.sender == libAddressManager.owner(), "Only callable by the Burn Admin.");
_;
}
/*******************************
* Authorized Setter Functions *
*******************************/
/**
* Allows the Burn Admin to update the parameters which determine the amount of gas to burn.
* The value of enqueueL2GasPrepaid is immediately updated as well.
*/
function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost)
external
onlyBurnAdmin
{
enqueueGasCost = _enqueueGasCost;
l2GasDiscountDivisor = _l2GasDiscountDivisor;
// See the comment in enqueue() for the rationale behind this formula.
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
emit L2GasParamsUpdated(l2GasDiscountDivisor, enqueueGasCost, enqueueL2GasPrepaid);
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve("ChainStorageContainer-CTC-batches"));
}
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve("ChainStorageContainer-CTC-queue"));
}
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() public view returns (uint256 _totalElements) {
(uint40 totalElements, , , ) = _getBatchExtraData();
return uint256(totalElements);
}
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() public view returns (uint256 _totalBatches) {
return batches().length();
}
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex() public view returns (uint40) {
return _nextQueueIndex[DEFAULT_CHAINID];
}
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp() public view returns (uint40) {
(, , uint40 lastTimestamp, ) = _getBatchExtraData();
return lastTimestamp;
}
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber() public view returns (uint40) {
(, , , uint40 lastBlockNumber) = _getBatchExtraData();
return lastBlockNumber;
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(uint256 _index)
public
view
returns (Lib_OVMCodec.QueueElement memory _element)
{
return queueElements[DEFAULT_CHAINID][_index];
}
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements() public view returns (uint40) {
return uint40(queueElements[DEFAULT_CHAINID].length) - _nextQueueIndex[DEFAULT_CHAINID];
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength() public view returns (uint40) {
return uint40(queueElements[DEFAULT_CHAINID].length);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
) external {
enqueueByChainId(DEFAULT_CHAINID, _target, _gasLimit, _data);
}
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch() external {
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
assembly {
shouldStartAtElement := shr(216, calldataload(4))
totalElementsToAppend := shr(232, calldataload(9))
numContexts := shr(232, calldataload(12))
}
require(
shouldStartAtElement == getTotalElements(),
"Actual batch start index does not match expected start index."
);
require(
msg.sender == resolve("OVM_Sequencer"),
"Function can only be called by the Sequencer."
);
uint40 nextTransactionPtr = uint40(
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
);
require(msg.data.length >= nextTransactionPtr, "Not enough BatchContexts provided.");
// Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0;
// Cache the _nextQueueIndex storage variable to a temporary stack variable.
// This is safe as long as nothing reads or writes to the storage variable
// until it is updated by the temp variable.
uint40 nextQueueIndex = _nextQueueIndex[DEFAULT_CHAINID];
BatchContext memory curContext;
for (uint32 i = 0; i < numContexts; i++) {
BatchContext memory nextContext = _getBatchContext(i);
// Now we can update our current context.
curContext = nextContext;
// Process sequencer transactions first.
numSequencerTransactions += uint32(curContext.numSequencedTransactions);
// Now process any subsequent queue transactions.
nextQueueIndex += uint40(curContext.numSubsequentQueueTransactions);
}
require(
nextQueueIndex <= queueElements[DEFAULT_CHAINID].length,
"Attempted to append more elements than are available in the queue."
);
// Generate the required metadata that we need to append this batch
uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions;
uint40 blockTimestamp;
uint40 blockNumber;
if (curContext.numSubsequentQueueTransactions == 0) {
// The last element is a sequencer tx, therefore pull timestamp and block number from
// the last context.
blockTimestamp = uint40(curContext.timestamp);
blockNumber = uint40(curContext.blockNumber);
} else {
// The last element is a queue tx, therefore pull timestamp and block number from the
// queue element.
// curContext.numSubsequentQueueTransactions > 0 which means that we've processed at
// least one queue element. We increment nextQueueIndex after processing each queue
// element, so the index of the last element we processed is nextQueueIndex - 1.
Lib_OVMCodec.QueueElement memory lastElement = queueElements[DEFAULT_CHAINID][nextQueueIndex - 1];
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
}
// Cache the previous blockhash to ensure all transaction data can be retrieved efficiently.
_appendBatch(
blockhash(block.number - 1),
totalElementsToAppend,
numQueuedTransactions,
blockTimestamp,
blockNumber
);
emit SequencerBatchAppended(
nextQueueIndex - numQueuedTransactions,
numQueuedTransactions,
getTotalElements(),
DEFAULT_CHAINID
);
// Update the _nextQueueIndex storage variable.
_nextQueueIndex[DEFAULT_CHAINID] = nextQueueIndex;
}
/**********************
* Internal Functions *
**********************/
/**
* Returns the BatchContext located at a particular index.
* @param _index The index of the BatchContext
* @return The BatchContext at the specified index.
*/
function _getBatchContext(uint256 _index) internal pure returns (BatchContext memory) {
uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 ctxTimestamp;
uint256 ctxBlockNumber;
assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3)))
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
}
return
BatchContext({
numSequencedTransactions: numSequencedTransactions,
numSubsequentQueueTransactions: numSubsequentQueueTransactions,
timestamp: ctxTimestamp,
blockNumber: ctxBlockNumber
});
}
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Index of the next queue element.
*/
function _getBatchExtraData()
internal
view
returns (
uint40,
uint40,
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
uint40 totalElements;
uint40 nextQueueIndex;
uint40 lastTimestamp;
uint40 lastBlockNumber;
// solhint-disable max-line-length
assembly {
extraData := shr(40, extraData)
totalElements := and(
extraData,
0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF
)
nextQueueIndex := shr(
40,
and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000)
)
lastTimestamp := shr(
80,
and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000)
)
lastBlockNumber := shr(
120,
and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000)
)
}
// solhint-enable max-line-length
return (totalElements, nextQueueIndex, lastTimestamp, lastBlockNumber);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _nextQueueIdx Index of the next queue element.
* @param _timestamp Timestamp for the last batch.
* @param _blockNumber Block number of the last batch.
* @return Encoded batch context.
*/
function _makeBatchExtraData(
uint40 _totalElements,
uint40 _nextQueueIdx,
uint40 _timestamp,
uint40 _blockNumber
) internal pure returns (bytes27) {
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _nextQueueIdx))
extraData := or(extraData, shl(80, _timestamp))
extraData := or(extraData, shl(120, _blockNumber))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Inserts a batch into the chain of batches.
* @param _transactionRoot Root of the transaction tree for this batch.
* @param _batchSize Number of elements in the batch.
* @param _numQueuedTransactions Number of queue transactions in the batch.
* @param _timestamp The latest batch timestamp.
* @param _blockNumber The latest batch blockNumber.
*/
function _appendBatch(
bytes32 _transactionRoot,
uint256 _batchSize,
uint256 _numQueuedTransactions,
uint40 _timestamp,
uint40 _blockNumber
) internal {
IChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraData();
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({
batchIndex: batchesRef.length(),
batchRoot: _transactionRoot,
batchSize: _batchSize,
prevTotalElements: totalElements,
extraData: hex""
});
emit TransactionBatchAppended(
DEFAULT_CHAINID,
header.batchIndex,
header.batchRoot,
header.batchSize,
header.prevTotalElements,
header.extraData
);
bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);
bytes27 latestBatchContext = _makeBatchExtraData(
totalElements + uint40(header.batchSize),
nextQueueIndex + uint40(_numQueuedTransactions),
_timestamp,
_blockNumber
);
batchesRef.push(batchHeaderHash, latestBatchContext);
}
//added chain id for public function
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElementsByChainId(uint256 _chainId)
override
public
view
returns (
uint256 _totalElements
)
{
(uint40 totalElements,,,) = _getBatchExtraDataByChainId(_chainId);
return uint256(totalElements);
}
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatchesByChainId(uint256 _chainId)
override
public
view
returns (
uint256 _totalBatches
)
{
return batches().lengthByChainId(_chainId);
}
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndexByChainId(uint256 _chainId)
override
public
view
returns (
uint40
)
{
(,uint40 nextQueueIndex,,) = _getBatchExtraDataByChainId(_chainId);
return nextQueueIndex;
}
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestampByChainId(uint256 _chainId)
override
public
view
returns (
uint40
)
{
(,,uint40 lastTimestamp,) = _getBatchExtraDataByChainId(_chainId);
return lastTimestamp;
}
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumberByChainId(uint256 _chainId)
override
public
view
returns (
uint40
)
{
(,,,uint40 lastBlockNumber) = _getBatchExtraDataByChainId(_chainId);
return lastBlockNumber;
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElementByChainId(
uint256 _chainId,
uint256 _index
)
override
public
view
returns (
Lib_OVMCodec.QueueElement memory _element
)
{
return queueElements[_chainId][_index];
}
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElementsByChainId(
uint256 _chainId
)
override
public
view
returns (
uint40
)
{
return uint40(queueElements[_chainId].length) - _nextQueueIndex[_chainId];
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLengthByChainId(
uint256 _chainId
)
override
public
view
returns (
uint40
)
{
return uint40(queueElements[_chainId].length);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueueByChainId(
uint256 _chainId,
address _target,
uint256 _gasLimit,
bytes memory _data
)
override
public
{
require(msg.sender == resolve("Proxy__OVM_L1CrossDomainMessenger"),
"only the cross domain messenger can enqueue");
require(
_data.length <= MAX_ROLLUP_TX_SIZE,
"Transaction data size exceeds maximum for rollup transaction."
);
require(
_gasLimit <= maxTransactionGasLimit,
"Transaction gas limit exceeds maximum for rollup transaction."
);
require(
_gasLimit >= MIN_ROLLUP_TX_GAS,
"Transaction gas limit too low to enqueue."
);
// Apply an aliasing unless msg.sender == tx.origin. This prevents an attack in which a
// contract on L1 has the same address as a contract on L2 but doesn't have the same code.
// We can safely ignore this for EOAs because they're guaranteed to have the same "code"
// (i.e. no code at all). This also makes it possible for users to interact with contracts
// on L2 even when the Sequencer is down.
address sender;
if (msg.sender == tx.origin) {
sender = msg.sender;
} else {
sender = AddressAliasHelper.applyL1ToL2Alias(msg.sender);
}
bytes32 transactionHash = keccak256(
abi.encode(
sender,
_target,
_gasLimit,
_data
)
);
queueElements[_chainId].push(
Lib_OVMCodec.QueueElement({
transactionHash: transactionHash,
timestamp: uint40(block.timestamp),
blockNumber: uint40(block.number)
})
);
// The underlying queue data structure stores 2 elements
// per insertion, so to get the real queue length we need
// to divide by 2 and subtract 1.
uint256 queueIndex = queueElements[_chainId].length - 1;
emit TransactionEnqueued(
_chainId,
sender,
_target,
_gasLimit,
_data,
queueIndex,
block.timestamp
);
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatchByChainId()
override
public
{
uint256 _chainId;
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
assembly {
_chainId := calldataload(4)
shouldStartAtElement := shr(216, calldataload(36))
totalElementsToAppend := shr(232, calldataload(41))
numContexts := shr(232, calldataload(44))
}
require(
shouldStartAtElement == getTotalElementsByChainId(_chainId),
"Actual batch start index does not match expected start index."
);
require(
msg.sender == resolve(string(abi.encodePacked(uint2str(_chainId),"_MVM_Sequencer"))),
"Function can only be called by the Sequencer."
);
require(
numContexts > 0,
"Must provide at least one batch context."
);
require(
totalElementsToAppend > 0,
"Must append at least one element."
);
uint40 nextTransactionPtr = uint40(
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
);
require(
msg.data.length >= nextTransactionPtr,
"Not enough BatchContexts provided."
);
// Cache the _nextQueueIndex storage variable to a temporary stack variable.
// This is safe as long as nothing reads or writes to the storage variable
// until it is updated by the temp variable.
uint40 nextQueueIndex = _nextQueueIndex[_chainId];
// Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0;
BatchContext memory curContext;
for (uint32 i = 0; i < numContexts; i++) {
BatchContext memory nextContext = _getBatchContextByChainId(0,_chainId,i);
// Now we can update our current context.
curContext = nextContext;
// Process sequencer transactions first.
numSequencerTransactions += uint32(curContext.numSequencedTransactions);
// Now process any subsequent queue transactions.
nextQueueIndex += uint40(curContext.numSubsequentQueueTransactions);
}
require(
nextQueueIndex <= queueElements[_chainId].length,
"Attempted to append more elements than are available in the queue."
);
// Generate the required metadata that we need to append this batch
uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions;
uint40 blockTimestamp;
uint40 blockNumber;
if (curContext.numSubsequentQueueTransactions == 0) {
// The last element is a sequencer tx, therefore pull timestamp and block number from
// the last context.
blockTimestamp = uint40(curContext.timestamp);
blockNumber = uint40(curContext.blockNumber);
} else {
// The last element is a queue tx, therefore pull timestamp and block number from the
// queue element.
// curContext.numSubsequentQueueTransactions > 0 which means that we've processed at
// least one queue element. We increment nextQueueIndex after processing each queue
// element, so the index of the last element we processed is nextQueueIndex - 1.
Lib_OVMCodec.QueueElement memory lastElement = queueElements[_chainId][nextQueueIndex - 1];
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
}
// For efficiency reasons getMerkleRoot modifies the `leaves` argument in place
// while calculating the root hash therefore any arguments passed to it must not
// be used again afterwards
_appendBatchByChainId(
_chainId,
blockhash(block.number - 1),
totalElementsToAppend,
numQueuedTransactions,
blockTimestamp,
blockNumber
);
emit SequencerBatchAppended(
_chainId,
nextQueueIndex - numQueuedTransactions,
numQueuedTransactions,
getTotalElementsByChainId(_chainId)
);
// Update the _nextQueueIndex storage variable.
_nextQueueIndex[_chainId] = nextQueueIndex;
}
/**********************
* Internal Functions *
**********************/
/**
* Returns the BatchContext located at a particular index.
* @param _index The index of the BatchContext
* @return The BatchContext at the specified index.
*/
function _getBatchContextByChainId(
uint256 _ptrStart,
uint256 _chainId,
uint256 _index
)
internal
pure
returns (
BatchContext memory
)
{
uint256 contextPtr = _ptrStart + 32 + 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 ctxTimestamp;
uint256 ctxBlockNumber;
assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3)))
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
}
return BatchContext({
numSequencedTransactions: numSequencedTransactions,
numSubsequentQueueTransactions: numSubsequentQueueTransactions,
timestamp: ctxTimestamp,
blockNumber: ctxBlockNumber
});
}
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Index of the next queue element.
*/
function _getBatchExtraDataByChainId(
uint256 _chainId
)
internal
view
returns (
uint40,
uint40,
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadataByChainId(_chainId);
uint40 totalElements;
uint40 nextQueueIndex;
uint40 lastTimestamp;
uint40 lastBlockNumber;
assembly {
extraData := shr(40, extraData)
totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
nextQueueIndex := shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000))
lastTimestamp := shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000))
lastBlockNumber := shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000))
}
return (
totalElements,
nextQueueIndex,
lastTimestamp,
lastBlockNumber
);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _nextQueueIdx Index of the next queue element.
* @param _timestamp Timestamp for the last batch.
* @param _blockNumber Block number of the last batch.
* @return Encoded batch context.
*/
function _makeBatchExtraDataByChainId(
uint256 _chainId,
uint40 _totalElements,
uint40 _nextQueueIdx,
uint40 _timestamp,
uint40 _blockNumber
)
internal
pure
returns (
bytes27
)
{
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _nextQueueIdx))
extraData := or(extraData, shl(80, _timestamp))
extraData := or(extraData, shl(120, _blockNumber))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Inserts a batch into the chain of batches.
* @param _transactionRoot Root of the transaction tree for this batch.
* @param _batchSize Number of elements in the batch.
* @param _numQueuedTransactions Number of queue transactions in the batch.
* @param _timestamp The latest batch timestamp.
* @param _blockNumber The latest batch blockNumber.
*/
function _appendBatchByChainId(
uint256 _chainId,
bytes32 _transactionRoot,
uint256 _batchSize,
uint256 _numQueuedTransactions,
uint40 _timestamp,
uint40 _blockNumber
)
internal
{
IChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraDataByChainId(_chainId);
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({
batchIndex: batchesRef.lengthByChainId(_chainId),
batchRoot: _transactionRoot,
batchSize: _batchSize,
prevTotalElements: totalElements,
extraData: hex""
});
emit TransactionBatchAppended(
_chainId,
header.batchIndex,
header.batchRoot,
header.batchSize,
header.prevTotalElements,
header.extraData
);
bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);
bytes27 latestBatchContext = _makeBatchExtraDataByChainId(
_chainId,
totalElements + uint40(header.batchSize),
nextQueueIndex + uint40(_numQueuedTransactions),
_timestamp,
_blockNumber
);
batchesRef.pushByChainId(_chainId,batchHeaderHash, latestBatchContext);
}
modifier onlyManager() {
require(
msg.sender == resolve("MVM_SuperManager"),
"ChainStorageContainer: Function can only be called by the owner."
);
_;
}
function pushQueueByChainId(
uint256 _chainId,
Lib_OVMCodec.QueueElement calldata _object
)
override
public
onlyManager
{
queueElements[_chainId].push(_object);
emit QueuePushed(msg.sender,_chainId,_object);
}
function setQueueByChainId(
uint256 _chainId,
uint256 _index,
Lib_OVMCodec.QueueElement calldata _object
)
override
public
onlyManager
{
queueElements[_chainId][_index] = _object;
emit QueueSetted(msg.sender,_chainId,_index,_object);
}
function setBatchGlobalMetadataByChainId(
uint256 _chainId,
bytes27 _globalMetadata
)
override
public
onlyManager
{
batches().setGlobalMetadataByChainId(_chainId,_globalMetadata);
emit BatchesGlobalMetadataSet(msg.sender,_chainId,_globalMetadata);
}
function getBatchGlobalMetadataByChainId(uint256 _chainId)
override
public
view
returns (
bytes27
)
{
return batches().getGlobalMetadataByChainId(_chainId);
}
function lengthBatchByChainId(uint256 _chainId)
override
public
view
returns (
uint256
)
{
return batches().lengthByChainId(_chainId);
}
function pushBatchByChainId(
uint256 _chainId,
bytes32 _object,
bytes27 _globalMetadata
)
override
public
onlyManager
{
batches().pushByChainId(_chainId,_object,_globalMetadata);
emit BatchPushed(msg.sender,_chainId,_object,_globalMetadata);
}
function setBatchByChainId(
uint256 _chainId,
uint256 _index,
bytes32 _object
)
override
public
onlyManager
{
batches().setByChainId(_chainId,_index,_object);
emit BatchSetted(msg.sender,_chainId,_index,_object);
}
function getBatchByChainId(
uint256 _chainId,
uint256 _index
)
override
public
view
returns (
bytes32
)
{
return batches().getByChainId(_chainId,_index);
}
function deleteBatchElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index,
bytes27 _globalMetadata
)
override
public
onlyManager
{
batches().deleteElementsAfterInclusiveByChainId(
_chainId,
_index,
_globalMetadata
);
emit BatchElementDeleted(msg.sender,_chainId,_index,_globalMetadata);
}
}
| Accesses the queue storage container. return Reference to the queue storage container./ | function queue() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve("ChainStorageContainer-CTC-queue"));
}
| 13,125,515 |
pragma solidity ^0.4.25;
/*
* https://12hourauction.github.io
*/
// THT Token Owners 10% (instantly)
// Referral 10% (can withdraw instantly)
// Key holders’ dividend: 30% (instantly? Till the end?)
// Marketing: 5%
// Final pot: 30%
// Next pot: 15%
// Total: 100%
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
interface TwelveHourTokenInterface {
function fallback() external payable;
function buy(address _referredBy) external payable returns (uint256);
function exit() external;
}
contract TwelveHourAuction {
bool init = false;
using SafeMath for uint256;
address owner;
uint256 public round = 0;
uint256 public nextPot = 0;
uint256 public profitTHT = 0;
// setting percent twelve hour auction
uint256 constant private THT_TOKEN_OWNERS = 10;
uint256 constant private KEY_HOLDERS_DIVIDEND = 30;
uint256 constant private REFERRAL = 10;
uint256 constant private FINAL_POT = 30;
// uint256 constant private NEXT_POT = 15;
uint256 constant private MARKETING = 5;
uint256 constant private MAGINITUDE = 2 ** 64;
uint256 constant private HALF_TIME = 12 hours;
uint256 constant private KEY_PRICE_DEFAULT = 0.005 ether;
uint256 constant private VERIFY_REFERRAL_PRICE= 0.01 ether;
// uint256 public stakingRequirement = 2 ether;
address public twelveHourTokenAddress;
TwelveHourTokenInterface public TwelveHourToken;
/**
* @dev game information
*/
mapping(uint256 => Game) public games;
// bonus info
mapping(address => Player) public players;
mapping(address => bool) public referrals;
address[10] public teamMarketing;
struct Game {
uint256 round;
uint256 finalPot;
uint256 profitPerShare;
address keyHolder;
uint256 keyLevel;
uint256 endTime;
bool ended;
}
// distribute gen portion to key holders
struct Player {
uint256 curentRound;
uint256 lastRound;
uint256 bonus;
uint256 keys; // total key in round
uint256 dividends;
uint256 referrals;
int256 payouts;
}
event Buy(uint256 round, address buyer, uint256 amount, uint256 keyLevel);
event EndRound(uint256 round, uint256 finalPot, address keyHolder, uint256 keyLevel, uint256 endTime);
event Withdraw(address player, uint256 amount);
event WithdrawReferral(address player, uint256 amount);
modifier onlyOwner()
{
require(msg.sender == owner);
_;
}
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
constructor() public
{
owner = msg.sender;
// setting default team marketing
for (uint256 idx = 0; idx < 10; idx++) {
teamMarketing[idx] = owner;
}
}
function () public payable
{
if (msg.sender != twelveHourTokenAddress) buy(0x0);
}
/**
* @dev set TwelveHourToken contract
* @param _addr TwelveHourToken address
*/
function setTwelveHourToken(address _addr) public onlyOwner
{
twelveHourTokenAddress = _addr;
TwelveHourToken = TwelveHourTokenInterface(twelveHourTokenAddress);
}
function setTeamMaketing(address _addr, uint256 _idx) public onlyOwner
{
teamMarketing[_idx] = _addr;
}
function verifyReferrals() public payable disableContract
{
require(msg.value >= VERIFY_REFERRAL_PRICE);
referrals[msg.sender] = true;
owner.transfer(msg.value);
}
// --------------------------------------------------------------------------
// SETUP GAME
// --------------------------------------------------------------------------
function startGame() public onlyOwner
{
require(init == false);
init = true;
games[round].ended = true;
startRound();
}
function startRound() private
{
require(games[round].ended == true);
round = round + 1;
uint256 endTime = now + HALF_TIME;
games[round] = Game(round, nextPot, 0, 0x0, 1, endTime, false);
nextPot = 0;
}
function endRound() private disableContract
{
require(games[round].ended == false && games[round].endTime <= now);
Game storage g = games[round];
address keyHolder = g.keyHolder;
g.ended = true;
players[keyHolder].bonus += g.finalPot;
startRound();
// uint256 round, uint256 finalPot, address keyHolder, uint256 keyLevel, uint256 endTime
emit EndRound(g.round, g.finalPot, g.keyHolder, g.keyLevel, g.endTime);
}
// ------------------------------------------------------------------------------
// BUY KEY
// ------------------------------------------------------------------------------
function buy(address _referral) public payable disableContract
{
require(init == true);
require(games[round].ended == false);
require(msg.sender != _referral);
if (games[round].endTime <= now) endRound();
Game storage g = games[round];
uint256 keyPrice = SafeMath.mul(g.keyLevel, KEY_PRICE_DEFAULT);
uint256 repay = SafeMath.sub(msg.value, keyPrice);
//
uint256 _referralBonus = SafeMath.div(SafeMath.mul(keyPrice, REFERRAL), 100);
uint256 _profitTHT = SafeMath.div(SafeMath.mul(keyPrice, THT_TOKEN_OWNERS), 100);
uint256 _dividends = SafeMath.div(SafeMath.mul(keyPrice, KEY_HOLDERS_DIVIDEND), 100);
uint256 _marketingFee = SafeMath.div(SafeMath.mul(keyPrice, MARKETING), 100);
uint256 _finalPot = SafeMath.div(SafeMath.mul(keyPrice, FINAL_POT), 100);
uint256 _nextPot = keyPrice - (_referralBonus + _profitTHT + _dividends + _marketingFee + _finalPot);
if (msg.value < keyPrice) revert();
if (repay > 0) msg.sender.transfer(repay); // repay to player
if (_referral != 0x0 && referrals[_referral] == true) players[_referral].referrals += _referralBonus;
else owner.transfer(_referralBonus);
uint256 _fee = _dividends * MAGINITUDE;
nextPot = SafeMath.add(nextPot, _nextPot);
profitTHT = SafeMath.add(profitTHT, _profitTHT);
if (g.keyLevel > 1) {
g.profitPerShare += (_dividends * MAGINITUDE / g.keyLevel);
_fee = _fee - (_fee - (1 * (_dividends * MAGINITUDE / g.keyLevel)));
}
int256 _updatedPayouts = (int256) (g.profitPerShare * 1 - _fee);
updatePlayer(msg.sender, _updatedPayouts);
// update game
updateGame(_finalPot);
sendToTeamMaketing(_marketingFee);
sendProfitTTH();
emit Buy(round, msg.sender, keyPrice, games[round].keyLevel);
}
function withdraw() public disableContract
{
if (games[round].ended == false && games[round].endTime <= now) endRound();
if (games[players[msg.sender].curentRound].ended == true) updatePlayerEndRound(msg.sender);
Player storage p = players[msg.sender];
uint256 _dividends = calculateDividends(msg.sender, p.curentRound);
uint256 balance = SafeMath.add(p.bonus, _dividends);
balance = SafeMath.add(balance, p.dividends);
require(balance > 0);
if (address(this).balance >= balance) {
p.bonus = 0;
p.dividends = 0;
if (p.curentRound == round) p.payouts += (int256) (_dividends * MAGINITUDE);
msg.sender.transfer(balance);
emit Withdraw(msg.sender, balance);
}
}
function withdrawReferral() public disableContract
{
Player storage p = players[msg.sender];
uint256 balance = p.referrals;
require(balance > 0);
if (address(this).balance >= balance) {
p.referrals = 0;
msg.sender.transfer(balance);
emit WithdrawReferral(msg.sender, balance);
}
}
function myDividends(address _addr)
public
view
returns(
uint256 _dividends // bonus + dividends
) {
Player memory p = players[_addr];
Game memory g = games[p.curentRound];
_dividends = p.bonus + p.dividends;
_dividends+= calculateDividends(_addr, p.curentRound);
if (
g.ended == false &&
g.endTime <= now &&
g.keyHolder == _addr
) {
_dividends += games[p.curentRound].finalPot;
}
}
function getData(address _addr)
public
view
returns(
uint256 _round,
uint256 _finalPot,
uint256 _endTime,
uint256 _keyLevel,
uint256 _keyPrice,
address _keyHolder,
bool _ended,
// player info
uint256 _playerDividends,
uint256 _playerReferrals
) {
_round = round;
Game memory g = games[_round];
_finalPot = g.finalPot;
_endTime = g.endTime;
_keyLevel = g.keyLevel;
_keyPrice = _keyLevel * KEY_PRICE_DEFAULT;
_keyHolder= g.keyHolder;
_ended = g.ended;
// player
_playerReferrals = players[_addr].referrals;
_playerDividends = myDividends(_addr);
}
function calculateDividends(address _addr, uint256 _round) public view returns(uint256 _devidends)
{
Game memory g = games[_round];
Player memory p = players[_addr];
if (p.curentRound == _round && p.lastRound < _round && _round != 0 )
_devidends = (uint256) ((int256) (g.profitPerShare * p.keys) - p.payouts) / MAGINITUDE;
}
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
// ---------------------------------------------------------------------------------------------
// INTERNAL FUNCTION
// ---------------------------------------------------------------------------------------------
function updatePlayer(address _addr, int256 _updatedPayouts) private
{
Player storage p = players[_addr];
if (games[p.curentRound].ended == true) updatePlayerEndRound(_addr);
if (p.curentRound != round) p.curentRound = round;
p.keys += 1;
p.payouts += (int256)(_updatedPayouts);
}
function updatePlayerEndRound(address _addr) private
{
Player storage p = players[_addr];
uint256 dividends = calculateDividends(_addr, p.curentRound);
p.dividends = SafeMath.add(p.dividends, dividends);
p.lastRound = p.curentRound;
p.keys = 0;
p.payouts = 0;
}
function updateGame(uint256 _finalPot) private
{
Game storage g = games[round];
// Final pot: 30%
g.finalPot = SafeMath.add(g.finalPot, _finalPot);
// update key holder
g.keyHolder = msg.sender;
// reset end time game
uint256 endTime = now + HALF_TIME;
endTime = endTime - 10 * g.keyLevel;
if (endTime <= now) endTime = now;
g.endTime = endTime;
// update key level
g.keyLevel += 1;
}
function sendToTeamMaketing(uint256 _marketingFee) private
{
// price * maketing / 100 * 10 /100 = price * maketing * 10 / 10000
uint256 profit = SafeMath.div(SafeMath.mul(_marketingFee, 10), 100);
for (uint256 idx = 0; idx < 10; idx++) {
teamMarketing[idx].transfer(profit);
}
}
function sendProfitTTH() private
{
uint256 balanceContract = totalEthereumBalance();
buyTHT(calEthSendToTHT(profitTHT));
exitTHT();
uint256 currentBalanceContract = totalEthereumBalance();
uint256 ethSendToTHT = SafeMath.sub(balanceContract, currentBalanceContract);
if (ethSendToTHT > profitTHT) {
// reset profit THT
profitTHT = 0;
nextPot = SafeMath.sub(nextPot, SafeMath.sub(ethSendToTHT, profitTHT));
} else {
profitTHT = SafeMath.sub(profitTHT, ethSendToTHT);
}
}
/**
* @dev calculate dividend eth for THT owner
* @param _eth value want share
* value = _eth * 100 / 64
*/
function calEthSendToTHT(uint256 _eth) private pure returns(uint256 _value)
{
_value = SafeMath.div(SafeMath.mul(_eth, 100), 64);
}
// conect to tht contract
function buyTHT(uint256 _value) private
{
TwelveHourToken.fallback.value(_value)();
}
function exitTHT() private
{
TwelveHourToken.exit();
}
} | uint256 round, uint256 finalPot, address keyHolder, uint256 keyLevel, uint256 endTime | function endRound() private disableContract
{
require(games[round].ended == false && games[round].endTime <= now);
Game storage g = games[round];
address keyHolder = g.keyHolder;
g.ended = true;
players[keyHolder].bonus += g.finalPot;
startRound();
emit EndRound(g.round, g.finalPot, g.keyHolder, g.keyLevel, g.endTime);
}
| 12,736,248 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================== MigratableFarmBSC =========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Sam Sun: https://github.com/samczsun
// Modified originally from Synthetixio
// https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol
import "../Math/Math.sol";
import "../Math/SafeMath.sol";
import "../BEP20/BEP20.sol";
import "../BEP20/SafeBEP20.sol";
import '../Uniswap/TransferHelper.sol';
import "../Utils/ReentrancyGuard.sol";
// Inheritance
import "./Owned.sol";
import "./Pausable.sol";
contract MigratableFarmBSC is Owned, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using SafeBEP20 for BEP20;
/* ========== STATE VARIABLES ========== */
BEP20 public rewardsToken0;
BEP20 public rewardsToken1;
BEP20 public stakingToken;
uint256 public periodFinish;
// Constant for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant MULTIPLIER_BASE = 1e6;
// Max reward per second
uint256 public rewardRate0;
uint256 public rewardRate1;
// uint256 public rewardsDuration = 86400 hours;
uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days)
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored0 = 0;
uint256 public rewardPerTokenStored1 = 0;
address public owner_address;
address public timelock_address; // Governance timelock address
uint256 public locked_stake_max_multiplier = 3000000; // 6 decimals of precision. 1x = 1000000
uint256 public locked_stake_time_for_max_multiplier = 3 * 365 * 86400; // 3 years
uint256 public locked_stake_min_time = 604800; // 7 * 86400 (7 days)
string private locked_stake_min_time_str = "604800"; // 7 days on genesis
mapping(address => uint256) public userRewardPerTokenPaid0;
mapping(address => uint256) public userRewardPerTokenPaid1;
mapping(address => uint256) public rewards0;
mapping(address => uint256) public rewards1;
uint256 private _staking_token_supply = 0;
uint256 private _staking_token_boosted_supply = 0;
mapping(address => uint256) private _unlocked_balances;
mapping(address => uint256) private _locked_balances;
mapping(address => uint256) private _boosted_balances;
mapping(address => LockedStake[]) private lockedStakes;
// List of valid migrators (set by governance)
mapping(address => bool) public valid_migrators;
address[] public valid_migrators_array;
// Stakers set which migrator(s) they want to use
mapping(address => mapping(address => bool)) public staker_allowed_migrators;
mapping(address => bool) public greylist;
bool public token1_rewards_on = false;
bool public migrationsOn = false; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals
bool public stakesUnlocked = false; // Release locked stakes in case of system migration or emergency
bool public withdrawalsPaused = false; // For emergencies
bool public rewardsCollectionPaused = false; // For emergencies
struct LockedStake {
bytes32 kek_id;
uint256 start_timestamp;
uint256 amount;
uint256 ending_timestamp;
uint256 multiplier; // 6 decimals of precision. 1x = 1000000
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not the owner or the governance timelock");
_;
}
modifier onlyByOwnerOrGovernanceOrMigrator() {
require(msg.sender == owner_address || msg.sender == timelock_address || valid_migrators[msg.sender] == true, "You are not the owner, governance timelock, or a migrator");
_;
}
modifier isMigrating() {
require(migrationsOn == true, "Contract is not in migration");
_;
}
modifier notWithdrawalsPaused() {
require(withdrawalsPaused == false, "Withdrawals are paused");
_;
}
modifier notRewardsCollectionPaused() {
require(rewardsCollectionPaused == false, "Rewards collection is paused");
_;
}
modifier updateReward(address account) {
// Need to retro-adjust some things if the period hasn't been renewed, then start a new one
sync();
if (account != address(0)) {
(uint256 earned0, uint256 earned1) = earned(account);
rewards0[account] = earned0;
rewards1[account] = earned1;
userRewardPerTokenPaid0[account] = rewardPerTokenStored0;
userRewardPerTokenPaid1[account] = rewardPerTokenStored1;
}
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
address _owner,
address _rewardsToken0,
address _rewardsToken1,
address _stakingToken,
address _timelock_address
) Owned(_owner){
owner_address = _owner;
rewardsToken0 = BEP20(_rewardsToken0);
rewardsToken1 = BEP20(_rewardsToken1);
stakingToken = BEP20(_stakingToken);
lastUpdateTime = block.timestamp;
timelock_address = _timelock_address;
// 1000 FXS a day
rewardRate0 = (uint256(365000e18)).div(365 * 86400);
// 0 CAKE a day
rewardRate1 = 0;
migrationsOn = false;
stakesUnlocked = false;
}
/* ========== VIEWS ========== */
function totalSupply() external view returns (uint256) {
return _staking_token_supply;
}
function totalBoostedSupply() external view returns (uint256) {
return _staking_token_boosted_supply;
}
function stakingMultiplier(uint256 secs) public view returns (uint256) {
uint256 multiplier = uint(MULTIPLIER_BASE).add(secs.mul(locked_stake_max_multiplier.sub(MULTIPLIER_BASE)).div(locked_stake_time_for_max_multiplier));
if (multiplier > locked_stake_max_multiplier) multiplier = locked_stake_max_multiplier;
return multiplier;
}
// Total unlocked and locked liquidity tokens
function balanceOf(address account) external view returns (uint256) {
return (_unlocked_balances[account]).add(_locked_balances[account]);
}
// Total unlocked liquidity tokens
function unlockedBalanceOf(address account) external view returns (uint256) {
return _unlocked_balances[account];
}
// Total locked liquidity tokens
function lockedBalanceOf(address account) public view returns (uint256) {
return _locked_balances[account];
}
// Total 'balance' used for calculating the percent of the pool the account owns
// Takes into account the locked stake time multiplier
function boostedBalanceOf(address account) external view returns (uint256) {
return _boosted_balances[account];
}
function lockedStakesOf(address account) external view returns (LockedStake[] memory) {
return lockedStakes[account];
}
function stakingDecimals() external view returns (uint256) {
return stakingToken.decimals();
}
function rewardsFor(address account) external view returns (uint256, uint256) {
// You may have use earned() instead, because of the order in which the contract executes
return (rewards0[account], rewards1[account]);
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256, uint256) {
if (_staking_token_supply == 0) {
return (rewardPerTokenStored0, rewardPerTokenStored1);
}
else {
return (
// Boosted emission
rewardPerTokenStored0.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate0).mul(1e18).div(_staking_token_boosted_supply)
),
// Flat emission
// Locked stakes will still get more weight with token1 rewards, but the CR boost will be canceled out for everyone
rewardPerTokenStored1.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate1).mul(1e18).div(_staking_token_boosted_supply)
)
);
}
}
function earned(address account) public view returns (uint256, uint256) {
(uint256 reward0, uint256 reward1) = rewardPerToken();
return (
_boosted_balances[account].mul(reward0.sub(userRewardPerTokenPaid0[account])).div(1e18).add(rewards0[account]),
_boosted_balances[account].mul(reward1.sub(userRewardPerTokenPaid1[account])).div(1e18).add(rewards1[account])
);
}
function getRewardForDuration() external view returns (uint256, uint256) {
return (
rewardRate0.mul(rewardsDuration),
rewardRate1.mul(rewardsDuration)
);
}
function migratorApprovedForStaker(address staker_address, address migrator_address) public view returns (bool) {
// Migrator is not a valid one
if (valid_migrators[migrator_address] == false) return false;
// Staker has to have approved this particular migrator
if (staker_allowed_migrators[staker_address][migrator_address] == true) return true;
// Otherwise, return false
return false;
}
/* ========== MUTATIVE FUNCTIONS ========== */
// Staker can allow a migrator
function stakerAllowMigrator(address migrator_address) public {
require(staker_allowed_migrators[msg.sender][migrator_address] == false, "Address already exists");
require(valid_migrators[migrator_address], "Invalid migrator address");
staker_allowed_migrators[msg.sender][migrator_address] = true;
}
// Staker can disallow a previously-allowed migrator
function stakerDisallowMigrator(address migrator_address) public {
require(staker_allowed_migrators[msg.sender][migrator_address] == true, "Address doesn't exist already");
// Redundant
// require(valid_migrators[migrator_address], "Invalid migrator address");
// Delete from the mapping
delete staker_allowed_migrators[msg.sender][migrator_address];
}
// Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration)
function stake(uint256 amount) public {
_stake(msg.sender, msg.sender, amount);
}
// If this were not internal, and source_address had an infinite approve, this could be exploitable
// (pull funds from source_address and stake for an arbitrary staker_address)
function _stake(address staker_address, address source_address, uint256 amount) internal nonReentrant updateReward(staker_address) {
require((paused == false && migrationsOn == false) || valid_migrators[msg.sender] == true, "Staking is paused, or migration is happening");
require(amount > 0, "Cannot stake 0");
require(greylist[staker_address] == false, "address has been greylisted");
// Pull the tokens from the source_address
TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), amount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.add(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.add(amount);
// Staking token balance and boosted balance
_unlocked_balances[staker_address] = _unlocked_balances[staker_address].add(amount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].add(amount);
emit Staked(staker_address, amount, source_address);
}
// Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration)
function stakeLocked(uint256 amount, uint256 secs) public {
_stakeLocked(msg.sender, msg.sender, amount, secs);
}
// If this were not internal, and source_address had an infinite approve, this could be exploitable
// (pull funds from source_address and stake for an arbitrary staker_address)
function _stakeLocked(address staker_address, address source_address, uint256 amount, uint256 secs) internal nonReentrant updateReward(staker_address) {
require((paused == false && migrationsOn == false) || valid_migrators[msg.sender] == true, "Staking is paused, or migration is happening");
require(amount > 0, "Cannot stake 0");
require(secs > 0, "Cannot wait for a negative number");
require(greylist[staker_address] == false, "address has been greylisted");
require(secs >= locked_stake_min_time, "Minimum stake time not met");
require(secs <= locked_stake_time_for_max_multiplier, "You are trying to stake for too long");
uint256 multiplier = stakingMultiplier(secs);
uint256 boostedAmount = amount.mul(multiplier).div(PRICE_PRECISION);
lockedStakes[staker_address].push(LockedStake(
keccak256(abi.encodePacked(staker_address, block.timestamp, amount)),
block.timestamp,
amount,
block.timestamp.add(secs),
multiplier
));
// Pull the tokens from the source_address
TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), amount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.add(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.add(boostedAmount);
// Staking token balance and boosted balance
_locked_balances[staker_address] = _locked_balances[staker_address].add(amount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].add(boostedAmount);
emit StakeLocked(staker_address, amount, secs, source_address);
}
// Two different withdrawer functions are needed because of delegateCall and msg.sender issues (important for migration)
function withdraw(uint256 amount) public {
_withdraw(msg.sender, msg.sender, amount);
}
// No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper
// functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked()
function _withdraw(address staker_address, address destination_address, uint256 amount) internal nonReentrant notWithdrawalsPaused updateReward(staker_address) {
require(amount > 0, "Cannot withdraw 0");
// Staking token balance and boosted balance
_unlocked_balances[staker_address] = _unlocked_balances[staker_address].sub(amount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].sub(amount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.sub(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.sub(amount);
// Give the tokens to the destination_address
stakingToken.safeTransfer(destination_address, amount);
emit Withdrawn(staker_address, amount, destination_address);
}
// Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration)
function withdrawLocked(bytes32 kek_id) public {
_withdrawLocked(msg.sender, msg.sender, kek_id);
}
// No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper
// functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked()
function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal nonReentrant notWithdrawalsPaused updateReward(staker_address) {
LockedStake memory thisStake;
thisStake.amount = 0;
uint theIndex;
for (uint i = 0; i < lockedStakes[staker_address].length; i++){
if (kek_id == lockedStakes[staker_address][i].kek_id){
thisStake = lockedStakes[staker_address][i];
theIndex = i;
break;
}
}
require(thisStake.kek_id == kek_id, "Stake not found");
require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!");
uint256 theAmount = thisStake.amount;
uint256 boostedAmount = theAmount.mul(thisStake.multiplier).div(PRICE_PRECISION);
if (theAmount > 0){
// Staking token balance and boosted balance
_locked_balances[staker_address] = _locked_balances[staker_address].sub(theAmount);
_boosted_balances[staker_address] = _boosted_balances[staker_address].sub(boostedAmount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.sub(theAmount);
_staking_token_boosted_supply = _staking_token_boosted_supply.sub(boostedAmount);
// Remove the stake from the array
delete lockedStakes[staker_address][theIndex];
// Give the tokens to the destination_address
stakingToken.safeTransfer(destination_address, theAmount);
emit WithdrawnLocked(staker_address, theAmount, kek_id, destination_address);
}
}
// Two different getReward functions are needed because of delegateCall and msg.sender issues (important for migration)
function getReward() public {
_getReward(msg.sender, msg.sender);
}
// No withdrawer == msg.sender check needed since this is only internally callable
// This distinction is important for the migrator
function _getReward(address rewardee, address destination_address) internal nonReentrant notRewardsCollectionPaused updateReward(rewardee) {
uint256 reward0 = rewards0[rewardee];
uint256 reward1 = rewards1[rewardee];
if (reward0 > 0) {
rewards0[rewardee] = 0;
rewardsToken0.transfer(destination_address, reward0);
emit RewardPaid(rewardee, reward0, address(rewardsToken0), destination_address);
}
// if (token1_rewards_on){
if (reward1 > 0) {
rewards1[rewardee] = 0;
rewardsToken1.transfer(destination_address, reward1);
emit RewardPaid(rewardee, reward1, address(rewardsToken1), destination_address);
}
// }
}
function renewIfApplicable() external {
if (block.timestamp > periodFinish) {
retroCatchUp();
}
}
// If the period expired, renew it
function retroCatchUp() internal {
// Failsafe check
require(block.timestamp > periodFinish, "Period has not expired yet!");
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 num_periods_elapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period
uint balance0 = rewardsToken0.balanceOf(address(this));
uint balance1 = rewardsToken1.balanceOf(address(this));
require(rewardRate0.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance0, "Not enough FXS available for rewards!");
if (token1_rewards_on){
require(rewardRate1.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance1, "Not enough token1 available for rewards!");
}
// uint256 old_lastUpdateTime = lastUpdateTime;
// uint256 new_lastUpdateTime = block.timestamp;
// lastUpdateTime = periodFinish;
periodFinish = periodFinish.add((num_periods_elapsed.add(1)).mul(rewardsDuration));
(uint256 reward0, uint256 reward1) = rewardPerToken();
rewardPerTokenStored0 = reward0;
rewardPerTokenStored1 = reward1;
lastUpdateTime = lastTimeRewardApplicable();
emit RewardsPeriodRenewed(address(stakingToken));
}
function sync() public {
if (block.timestamp > periodFinish) {
retroCatchUp();
}
else {
(uint256 reward0, uint256 reward1) = rewardPerToken();
rewardPerTokenStored0 = reward0;
rewardPerTokenStored1 = reward1;
lastUpdateTime = lastTimeRewardApplicable();
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can)
function migrator_stake_for(address staker_address, uint256 amount) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_stake(staker_address, msg.sender, amount);
}
// Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can).
function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_stakeLocked(staker_address, msg.sender, amount, secs);
}
// Used for migrations
function migrator_withdraw_unlocked(address staker_address) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_withdraw(staker_address, msg.sender, _unlocked_balances[staker_address]);
}
// Used for migrations
function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating {
require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them");
_withdrawLocked(staker_address, msg.sender, kek_id);
}
// Adds supported migrator address
function addMigrator(address migrator_address) public onlyByOwnerOrGovernance {
require(valid_migrators[migrator_address] == false, "address already exists");
valid_migrators[migrator_address] = true;
valid_migrators_array.push(migrator_address);
}
// Remove a migrator address
function removeMigrator(address migrator_address) public onlyByOwnerOrGovernance {
require(valid_migrators[migrator_address] == true, "address doesn't exist already");
// Delete from the mapping
delete valid_migrators[migrator_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < valid_migrators_array.length; i++){
if (valid_migrators_array[i] == migrator_address) {
valid_migrators_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
}
// Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders
function recoverBEP20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
// Admin cannot withdraw the staking token from the contract unless currently migrating
if(!migrationsOn){
require(tokenAddress != address(stakingToken), "Cannot withdraw staking tokens unless migration is on"); // Only Governance / Timelock can trigger a migration
}
// Only the owner address can ever receive the recovery withdrawal
BEP20(tokenAddress).transfer(owner_address, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwnerOrGovernance {
require(
periodFinish == 0 || block.timestamp > periodFinish,
"Previous rewards period must be complete before changing the duration for the new period"
);
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
function setMultipliers(uint256 _locked_stake_max_multiplier) external onlyByOwnerOrGovernance {
require(_locked_stake_max_multiplier >= 1, "Multiplier must be greater than or equal to 1");
locked_stake_max_multiplier = _locked_stake_max_multiplier;
emit LockedStakeMaxMultiplierUpdated(locked_stake_max_multiplier);
}
function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _locked_stake_time_for_max_multiplier, uint256 _locked_stake_min_time) external onlyByOwnerOrGovernance {
require(_locked_stake_time_for_max_multiplier >= 1, "Multiplier Max Time must be greater than or equal to 1");
require(_locked_stake_min_time >= 1, "Multiplier Min Time must be greater than or equal to 1");
locked_stake_time_for_max_multiplier = _locked_stake_time_for_max_multiplier;
locked_stake_min_time = _locked_stake_min_time;
emit LockedStakeTimeForMaxMultiplier(locked_stake_time_for_max_multiplier);
emit LockedStakeMinTime(_locked_stake_min_time);
}
function initializeDefault() external onlyByOwnerOrGovernance {
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit DefaultInitialization();
}
function greylistAddress(address _address) external onlyByOwnerOrGovernance {
greylist[_address] = !(greylist[_address]);
}
function unlockStakes() external onlyByOwnerOrGovernance {
stakesUnlocked = !stakesUnlocked;
}
function toggleMigrations() external onlyByOwnerOrGovernance {
migrationsOn = !migrationsOn;
}
function toggleWithdrawals() external onlyByOwnerOrGovernance {
withdrawalsPaused = !withdrawalsPaused;
}
function toggleRewardsCollection() external onlyByOwnerOrGovernance {
rewardsCollectionPaused = !rewardsCollectionPaused;
}
function setRewardRates(uint256 _new_rate0, uint256 _new_rate1, bool sync_too) external onlyByOwnerOrGovernance {
rewardRate0 = _new_rate0;
rewardRate1 = _new_rate1;
if (sync_too){
sync();
}
}
function toggleToken1Rewards() external onlyByOwnerOrGovernance {
if (token1_rewards_on) {
rewardRate1 = 0;
}
token1_rewards_on = !token1_rewards_on;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setTimelock(address _new_timelock) external onlyByOwnerOrGovernance {
timelock_address = _new_timelock;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount, address source_address );
event StakeLocked(address indexed user, uint256 amount, uint256 secs, address source_address);
event Withdrawn(address indexed user, uint256 amount, address destination_address);
event WithdrawnLocked(address indexed user, uint256 amount, bytes32 kek_id, address destination_address);
event RewardPaid(address indexed user, uint256 reward, address token_address, address destination_address);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
event RewardsPeriodRenewed(address token);
event DefaultInitialization();
event LockedStakeMaxMultiplierUpdated(uint256 multiplier);
event LockedStakeTimeForMaxMultiplier(uint256 secs);
event LockedStakeMinTime(uint256 secs);
}
| Staker can disallow a previously-allowed migrator Redundant require(valid_migrators[migrator_address], "Invalid migrator address"); Delete from the mapping | function stakerDisallowMigrator(address migrator_address) public {
require(staker_allowed_migrators[msg.sender][migrator_address] == true, "Address doesn't exist already");
delete staker_allowed_migrators[msg.sender][migrator_address];
}
| 7,271,199 |
pragma solidity ^0.6.2;
// SPDX-License-Identifier: MIT
abstract contract Context {
function _MSGSENDER583() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA879() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
interface IERC20 {
function TOTALSUPPLY430() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF616(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER244(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE387(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE425(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM381(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER617(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL460(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// SPDX-License-Identifier: MIT
library SafeMath {
function ADD135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB321(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB321(a, b, "SafeMath: subtraction overflow");
}
function SUB321(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL733(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV136(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV136(a, b, "SafeMath: division by zero");
}
function DIV136(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD593(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD593(a, b, "SafeMath: modulo by zero");
}
function MOD593(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
library Address {
function ISCONTRACT469(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE193(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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 FUNCTIONCALL340(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL340(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL340(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE922(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE944(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE922(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE922(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT469(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
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;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME100() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL131() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS904() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY430() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF616(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER244(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER73(_MSGSENDER583(), recipient, amount);
return true;
}
function ALLOWANCE387(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE425(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, amount);
return true;
}
function TRANSFERFROM381(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER73(sender, recipient, amount);
_APPROVE319(sender, _MSGSENDER583(), _allowances[sender][_MSGSENDER583()].SUB321(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE808(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].ADD135(addedValue));
return true;
}
function DECREASEALLOWANCE515(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].SUB321(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER73(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER129(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB321(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD135(amount);
emit TRANSFER617(sender, recipient, amount);
}
function _MINT517(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER129(address(0), account, amount);
_totalSupply = _totalSupply.ADD135(amount);
_balances[account] = _balances[account].ADD135(amount);
emit TRANSFER617(address(0), account, amount);
}
function _BURN171(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER129(account, address(0), amount);
_balances[account] = _balances[account].SUB321(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB321(amount);
emit TRANSFER617(account, address(0), amount);
}
function _APPROVE319(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL460(owner, spender, amount);
}
function _SETUPDECIMALS874(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
// SPDX-License-Identifier: MIT
abstract contract ERC20Capped is ERC20 {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
function CAP360() public view returns (uint256) { //inject NONSTANDARD NAMING
return _cap;
}
function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING
super._BEFORETOKENTRANSFER129(from, to, amount);
if (from == address(0)) { // When minting tokens
require(TOTALSUPPLY430().ADD135(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
}
// SPDX-License-Identifier: MIT
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED797(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER583();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED797(address(0), msgSender);
}
function OWNER971() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER607() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER583(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP525() public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED797(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP777(address newOwner) public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED797(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Router01 {
function FACTORY439() external pure returns (address); //inject NONSTANDARD NAMING
function WETH181() external pure returns (address); //inject NONSTANDARD NAMING
function ADDLIQUIDITY85( //inject NONSTANDARD NAMING
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 ADDLIQUIDITYETH216( //inject NONSTANDARD NAMING
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function REMOVELIQUIDITY344( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function REMOVELIQUIDITYETH742( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function REMOVELIQUIDITYWITHPERMIT491( //inject NONSTANDARD NAMING
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 REMOVELIQUIDITYETHWITHPERMIT317( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENS917( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTTOKENS879( //inject NONSTANDARD NAMING
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPEXACTETHFORTOKENS817(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTETH856(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPEXACTTOKENSFORETH218(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPETHFOREXACTTOKENS998(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function QUOTE315(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING
function GETAMOUNTOUT816(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING
function GETAMOUNTIN684(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING
function GETAMOUNTSOUT241(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
function GETAMOUNTSIN775(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS846( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS1( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS219( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS501( //inject NONSTANDARD NAMING
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS54( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Pair {
event APPROVAL460(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER617(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME100() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL131() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS904() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY430() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF616(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE387(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE425(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM381(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR749() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH945() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES546(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT654(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT786(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN405(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP722( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC303(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY735() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY439() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0934() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1318() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES691() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST150() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST277() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST634() external view returns (uint); //inject NONSTANDARD NAMING
function MINT615(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN664(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP816(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM21(address to) external; //inject NONSTANDARD NAMING
function SYNC269() external; //inject NONSTANDARD NAMING
function INITIALIZE267(address, address) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED762(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO789() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER578() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR592(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS410(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH90() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR614(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO894(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER1(address) external; //inject NONSTANDARD NAMING
}
interface IWETH {
function DEPOSIT145() external payable; //inject NONSTANDARD NAMING
function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW78(uint) external; //inject NONSTANDARD NAMING
}
contract CGLB is ERC20Capped, Ownable {
using SafeMath for uint;
address public UNIPAIR;
address public DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IUniswapV2Router02 public UNIROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Factory public UNIFACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
bool public isRunning = false;
bool private liquidityFlag;
uint public constant supplycap690 = (10**4)*(10**18); //inject NONSTANDARD NAMING
uint public constant tokensforinitialliquidity143 = 3*(10**3)*(10**18); //inject NONSTANDARD NAMING
bytes32 public airdropRoot;
mapping (address => bool) public claimedAirdrop;
string public website = "www.cglb.fi";
constructor() public ERC20Capped(supplycap690) ERC20("Cant go lower boys", "CGLB") {
airdropRoot = 0x185065ab3d54b516ee3ed54dc30e04758300a4b41e207cf3ba91715f378d7728;
}
function TRANSFER244(address recipient, uint256 amount) //inject NONSTANDARD NAMING
public override
returns (bool) {
require(msg.sender == UNIPAIR || msg.sender == address(UNIROUTER));
super.TRANSFER244(recipient, amount);
return true;
}
function TRANSFERFROM381(address sender, address recipient, uint256 amount) //inject NONSTANDARD NAMING
public override
returns (bool) {
require(liquidityFlag);
_TRANSFER73(sender, recipient, amount);
return true;
}
function ADDLIQUIDITYTOUNISWAPPAIR951( //inject NONSTANDARD NAMING
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountDAIDesired,
uint256 amountDAImin
) public payable {
require(isRunning);
require(IERC20(DAI).TRANSFERFROM381(msg.sender, address(this), amountDAIDesired));
require(IERC20(DAI).APPROVE425(address(UNIROUTER), amountDAIDesired));
_TRANSFER73(msg.sender, address(this), amountTokenDesired);
liquidityFlag = true;
(uint amountToken, uint amountDAI, uint liquidity) = UNIROUTER.ADDLIQUIDITY85(
address(this),
DAI,
amountTokenDesired,
amountDAIDesired,
amountTokenMin,
amountDAImin,
msg.sender,
now + 10 minutes
);
liquidityFlag = false;
//sends dust back
if (amountTokenDesired - amountToken > 0 ) _TRANSFER73(address(this), msg.sender, amountTokenDesired-amountToken);
if (amountDAIDesired - amountDAI > 0) require(IERC20(DAI).TRANSFER244(msg.sender, amountDAIDesired - amountDAI));
}
function ADDINITIALLIQUIDITYWITHPAIR729() public ONLYOWNER607 { //inject NONSTANDARD NAMING
CREATEUNISWAPPAIR64();
uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this));
require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI));
_MINT517(UNIPAIR, tokensforinitialliquidity143);
IUniswapV2Pair(UNIPAIR).MINT615(msg.sender);
isRunning = true;
}
function ADDINITIALLIQUIDITY209() public ONLYOWNER607 { //inject NONSTANDARD NAMING
uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this));
require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI));
_MINT517(UNIPAIR, tokensforinitialliquidity143);
IUniswapV2Pair(UNIPAIR).MINT615(msg.sender);
isRunning = true;
}
function SETAIRDROPROOT894(bytes32 _root) public ONLYOWNER607 { //inject NONSTANDARD NAMING
airdropRoot = _root;
}
function SETPAIR246(address _pair) public ONLYOWNER607 { //inject NONSTANDARD NAMING
UNIPAIR = _pair;
}
function CREATEUNISWAPPAIR64() internal { //inject NONSTANDARD NAMING
require(UNIPAIR == address(0), "Token: pool already created");
UNIPAIR = UNIFACTORY.CREATEPAIR614(
DAI,
address(this)
);
}
function CHECKPROOF499(bytes memory proof, bytes32 root, bytes32 hash) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 el;
bytes32 h = hash;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
el := mload(add(proof, i))
}
if (h < el) {
h = keccak256(abi.encodePacked(h, el));
} else {
h = keccak256(abi.encodePacked(el, h));
}
}
return h == root;
}
function CLAIMAIRDROP701(bytes memory proof, uint amount) public { //inject NONSTANDARD NAMING
require(!claimedAirdrop[msg.sender]);
bytes32 hash = keccak256(abi.encodePacked(msg.sender, amount));
require(CHECKPROOF499(proof, airdropRoot, hash), "Invalid proof");
claimedAirdrop[msg.sender] = true;
_MINT517(msg.sender, amount);
}
function WITHDRAWERC20742(address token) ONLYOWNER607 public { //inject NONSTANDARD NAMING
uint balance = IERC20(token).BALANCEOF616(address(this));
require(IERC20(token).TRANSFER244(msg.sender, balance));
}
} | inject NONSTANDARD NAMING | function TOKEN0934() external view returns (address); | 1,820,591 |
./full_match/1/0x394D2cbD357156b45D02881fc176F7053144639A/sources/contracts/GenPadNFTV4.sol | Set new limit per wallet | function changeMaxMintPerWallet(
uint256 _max_mint_amount
) external onlyOwner {
uint256 oldAmount = MAX_MINTS;
MAX_MINTS = _max_mint_amount;
emit MintsPerWalletUpdated(
_max_mint_amount,
oldAmount,
block.timestamp
);
}
| 8,447,531 |
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./IReserve.sol";
import "./whitelist.sol";
import "./safari-erc20.sol";
import "./isafari-erc721.sol";
import "./token-metadata.sol";
import "./safari-token-meta.sol";
uint256 constant GEN0 = 0;
uint256 constant GEN1 = 1;
contract SafariMint is Ownable, Pausable {
using SafariToken for SafariToken.Metadata;
struct WhitelistInfo {
uint8 origAmount;
uint8 amountRemaining;
uint240 cost;
}
// mint price
uint256 public constant MINT_PRICE = .07 ether;
uint256 public constant WHITELIST_MINT_PRICE = .04 ether;
uint256 public MAX_GEN0_TOKENS = 7777;
uint256 public MAX_GEN1_TOKENS = 6667;
uint256 public constant GEN1_MINT_PRICE = 40000 ether;
mapping(uint256 => SafariToken.Metadata[]) internal special;
uint256 public MAX_MINTS_PER_TX = 10;
// For Whitelist winners
mapping(address => WhitelistInfo) public whiteList;
// For lions/zebras holders
SafariOGWhitelist ogWhitelist;
// reference to the Reserve for staking and choosing random Poachers
IReserve public reserve;
// reference to $RUBY for burning on mint
SafariErc20 public ruby;
// reference to the rhino metadata generator
SafariTokenMeta public rhinoMeta;
// reference to the poacher metadata generator
SafariTokenMeta public poacherMeta;
// reference to the main NFT contract
ISafariErc721 public safari_erc721;
// is public mint enabled
bool public publicMint;
// is gen1 mint enabled
bool public gen1MintEnabled;
constructor(address _ruby, address _ogWhitelist) {
ogWhitelist = SafariOGWhitelist(_ogWhitelist);
ruby = SafariErc20(_ruby);
}
function setReserve(address _reserve) external onlyOwner {
reserve = IReserve(_reserve);
}
function setRhinoMeta(address _rhino) external onlyOwner {
rhinoMeta = SafariTokenMeta(_rhino);
}
function setPoacherMeta(address _poacher) external onlyOwner {
poacherMeta = SafariTokenMeta(_poacher);
}
function setErc721(address _safariErc721) external onlyOwner {
safari_erc721 = ISafariErc721(_safariErc721);
}
function addSpecial(bytes32[] calldata value) external onlyOwner {
for (uint256 i=0; i<value.length; i++) {
SafariToken.Metadata memory v = SafariToken.create(value[i]);
v.setSpecial(true);
uint8 kind = v.getCharacterType();
special[kind].push(v);
}
}
/**
* allows owner to withdraw funds from minting
*/
function withdraw() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
/**
* public mint tokens
* @param amount the number of tokens that are being paid for
* @param boostPercent increase the odds of minting poachers to this percent
* @param stake stake the tokens if true
*/
function mintGen0(uint256 amount, uint256 boostPercent, bool stake) external payable whenNotPaused whenPublicMint {
require(amount * MINT_PRICE == msg.value, "Invalid payment amount");
_mintGen0(amount, boostPercent, stake);
}
/**
* public mint tokens
* @param amount the number of tokens that are being paid for
* @param boostPercent increase the odds of minting poachers to this percent
* @param stake stake the tokens if true
*/
function mintGen1(uint256 amount, uint256 boostPercent, bool stake) external payable whenNotPaused whenGen1Mint {
_mintGen1(amount, boostPercent, stake);
}
/**
* mint tokens using the whitelist
* @param amount the number of tokens that are being paid for or claimed
* @param boostPercent increase the odds of minting poachers to this percent
* @param stake stake the tokens if true
*/
function mintWhitelist(uint8 amount, uint256 boostPercent, bool stake) external payable whenNotPaused whenWhitelistMint {
WhitelistInfo memory wlInfo = whiteList[_msgSender()];
require(wlInfo.origAmount > 0, "you are not on the whitelist");
uint256 amountAtCustomPrice = min(amount, wlInfo.amountRemaining);
uint256 amountAtWhitelistPrice = amount - amountAtCustomPrice;
uint256 totalPrice = amountAtCustomPrice * wlInfo.cost + amountAtWhitelistPrice * WHITELIST_MINT_PRICE;
require(totalPrice == msg.value, "wrong payment amount");
wlInfo.amountRemaining -= uint8(amountAtCustomPrice);
whiteList[_msgSender()] = wlInfo;
_mintGen0(amount, boostPercent, stake);
}
/**
* mint tokens using the OG Whitelist
* @param amountPaid the number of tokens that are being paid for
* @param amountFree the number of free tokens being claimed
* @param boostPercent increase the odds of minting poachers to this percent
* @param stake stake the tokens if true
*/
function mintOGWhitelist(uint256 amountPaid, uint256 amountFree, uint256 boostPercent, bool stake) external payable whenNotPaused whenWhitelistMint {
require(amountPaid * WHITELIST_MINT_PRICE == msg.value, "wrong payment amount");
uint16 offset;
uint8 bought;
uint8 claimed;
uint8 lions;
uint8 zebras;
uint256 packedInfo = ogWhitelist.getInfoPacked(_msgSender());
offset = uint16(packedInfo >> 32);
bought = uint8(packedInfo >> 24);
claimed = uint8(packedInfo >> 16);
lions = uint8(packedInfo >> 8);
zebras = uint8(packedInfo);
uint256 totalBought = amountPaid + bought;
uint256 totalClaimed = amountFree + claimed;
uint256 totalCredits = freeCredits(totalBought, lions, zebras);
require(totalClaimed <= totalCredits, 'not enough free credits');
if (totalBought > 255) {
totalBought = 255;
}
uint16 boughtAndClaimed = uint16((totalBought << 8) + totalClaimed);
ogWhitelist.setBoughtAndClaimed(offset, boughtAndClaimed);
uint256 amount = amountPaid + amountFree;
_mintGen0(amount, boostPercent, stake);
}
/**
* calculate how many RUBIES are needed to increase the
* odds of minting a Poacher or APR
* @param boostPercent the number of zebras owned by the user
* @return the amount of RUBY that is needed
*/
function boostPercentToCost(uint256 boostPercent, uint256 gen) internal pure returns(uint256) {
if (boostPercent == 0) {
return 0;
}
uint256 boostCost;
if (gen == GEN0) {
assembly {
switch boostPercent
case 20 {
boostCost := 50000
}
case 25 {
boostCost := 60000
}
case 30 {
boostCost := 100000
}
case 100 {
boostCost := 500000
}
}
} else {
assembly {
switch boostPercent
case 20 {
boostCost := 50000
}
case 25 {
boostCost := 60000
}
case 30 {
boostCost := 100000
}
case 100 {
boostCost := 1000000
}
}
}
require(boostCost > 0, 'Invalid boost amount');
return boostCost * 1 ether;
}
function getStakedPoacherBoost() internal view returns(uint256) {
uint256 numStakedPoachers = reserve.numDepositedPoachersOf(tx.origin);
if (numStakedPoachers >= 5) {
return 15;
} else if (numStakedPoachers >= 4) {
return 10;
} else if (numStakedPoachers >= 2) {
return 5;
}
return 0;
}
function _mintGen0(uint256 amount, uint256 boostPercent, bool stake) internal {
require(tx.origin == _msgSender(), "Only EOA");
require(amount > 0 && amount <= MAX_MINTS_PER_TX, "Invalid mint amount");
uint256 m = safari_erc721.totalSupply();
require(m < MAX_GEN0_TOKENS, "All Gen 0 tokens minted");
uint256 totalRubyCost = boostPercentToCost(boostPercent, GEN0) * amount;
require(ruby.balanceOf(_msgSender()) >= totalRubyCost, 'not enough RUBY for boost');
uint256 poacherChance = boostPercent == 0 ? 10 : boostPercent;
SafariToken.Metadata[] memory tokenMetadata = new SafariToken.Metadata[](amount);
uint16[] memory tokenIds = new uint16[](amount);
uint256 randomVal;
address recipient = stake ? address(reserve) : _msgSender();
for (uint i = 0; i < amount; i++) {
m++;
randomVal = random(m);
tokenMetadata[i] = generate0(randomVal, poacherChance, m);
tokenIds[i] = uint16(m);
}
if (totalRubyCost > 0) {
ruby.burn(_msgSender(), totalRubyCost);
}
safari_erc721.batchMint(recipient, tokenMetadata, tokenIds);
if (stake) {
reserve.stakeMany(_msgSender(), tokenIds);
}
}
function selectRecipient(uint256 seed, address origRecipient) internal view returns (address) {
if (((seed >> 245) % 10) != 0) return origRecipient;
address thief = reserve.randomPoacherOwner(seed >> 144);
if (thief == address(0x0)) return origRecipient;
return thief;
}
function _mintGen1(uint256 amount, uint256 boostPercent, bool stake) internal {
require(tx.origin == _msgSender(), "Only EOA");
require(amount > 0 && amount <= MAX_MINTS_PER_TX, "Invalid mint amount");
uint256 m = safari_erc721.totalSupply();
require(m < MAX_GEN0_TOKENS + MAX_GEN1_TOKENS, "All Gen 1 tokens minted");
uint256 totalRubyCost = boostPercentToCost(boostPercent, GEN1) * amount;
totalRubyCost += amount * GEN1_MINT_PRICE;
require(ruby.balanceOf(_msgSender()) >= totalRubyCost, 'not enough RUBY owned');
uint256 aprChance = boostPercent == 0 ? 10 : boostPercent;
if (aprChance != 100) {
aprChance += getStakedPoacherBoost();
}
SafariToken.Metadata[] memory tokenMetadata = new SafariToken.Metadata[](amount);
SafariToken.Metadata[] memory singleTokenMetadata = new SafariToken.Metadata[](1);
uint16[] memory tokenIds = new uint16[](amount);
uint16[] memory singleTokenId = new uint16[](1);
uint256 randomVal;
address recipient = stake ? address(reserve) : _msgSender();
address thief;
for (uint i = 0; i < amount; i++) {
m++;
randomVal = random(m);
singleTokenMetadata[0] = generate1(randomVal, aprChance, m);
if (!singleTokenMetadata[0].isAPR() && (thief = selectRecipient(randomVal, recipient)) != recipient) {
singleTokenId[0] = uint16(m);
safari_erc721.batchMint(thief, singleTokenMetadata, singleTokenId);
} else {
tokenMetadata[i] = singleTokenMetadata[0];
tokenIds[i] = uint16(m);
}
}
if (totalRubyCost > 0) {
ruby.burn(_msgSender(), totalRubyCost);
}
safari_erc721.batchMint(recipient, tokenMetadata, tokenIds);
if (stake) {
reserve.stakeMany(_msgSender(), tokenIds);
}
}
/**
* generates traits for a specific token, checking to make sure it's unique
* @param randomVal a pseudorandom 256 bit number to derive traits from
* @return t - a struct of traits for the given token ID
*/
function generate0(uint256 randomVal, uint256 poacherChance, uint256 tokenId) internal returns(SafariToken.Metadata memory) {
SafariToken.Metadata memory newData;
uint8 characterType = (randomVal % 100 < poacherChance) ? POACHER : ANIMAL;
if (characterType == POACHER) {
SafariToken.Metadata[] storage specials = special[POACHER];
if (randomVal % (MAX_GEN0_TOKENS/10 - min(tokenId, MAX_GEN0_TOKENS/10) + 1) < specials.length) {
newData.setSpecial(specials);
} else {
newData = poacherMeta.generateProperties(randomVal, tokenId);
newData.setAlpha(uint8(((randomVal >> 7) % (MAX_ALPHA - MIN_ALPHA + 1)) + MIN_ALPHA));
newData.setCharacterType(characterType);
}
} else {
SafariToken.Metadata[] storage specials = special[ANIMAL];
if (randomVal % (MAX_GEN0_TOKENS - min(tokenId, MAX_GEN0_TOKENS) + 1) < specials.length) {
newData.setSpecial(specials);
} else {
newData = rhinoMeta.generateProperties(randomVal, tokenId);
newData.setCharacterType(characterType);
}
}
return newData;
}
/**
* generates traits for a specific token, checking to make sure it's unique
* @param randomVal a pseudorandom 256 bit number to derive traits from
* @return t - a struct of traits for the given token ID
*/
function generate1(uint256 randomVal, uint256 aprChance, uint256 tokenId) internal returns(SafariToken.Metadata memory) {
SafariToken.Metadata memory newData;
newData.setCharacterType((randomVal % 100 < aprChance) ? APR : ANIMAL);
if (newData.isAPR()) {
SafariToken.Metadata[] storage specials = special[APR];
if (randomVal % (MAX_GEN0_TOKENS + MAX_GEN1_TOKENS - min(tokenId, MAX_GEN0_TOKENS + MAX_GEN1_TOKENS) + 1) < specials.length) {
newData.setSpecial(specials);
} else {
newData.setAlpha(uint8(((randomVal >> 7) % (MAX_ALPHA - MIN_ALPHA + 1)) + MIN_ALPHA));
}
} else {
SafariToken.Metadata[] storage specials = special[CHEETAH];
if (randomVal % (MAX_GEN0_TOKENS + MAX_GEN1_TOKENS - min(tokenId, MAX_GEN0_TOKENS + MAX_GEN1_TOKENS) + 1) < specials.length) {
newData.setSpecial(specials);
} else {
newData.setCharacterSubtype(CHEETAH);
}
}
return newData;
}
/**
* updates the number of tokens for primary mint
*/
function setGen0Max(uint256 _gen0Tokens) external onlyOwner {
MAX_GEN0_TOKENS = _gen0Tokens;
}
/**
* generates a pseudorandom number
* @param seed a value ensure different outcomes for different sources in the same block
* @return a pseudorandom value
*/
function random(uint256 seed) internal view returns (uint256) {
return uint256(
keccak256(
abi.encodePacked(
blockhash(block.number - 1),
seed
)
)
);
}
/** ADMIN */
function setPublicMint(bool allowPublicMint) external onlyOwner {
publicMint = allowPublicMint;
}
function setGen1Mint(bool allowGen1Mint) external onlyOwner {
gen1MintEnabled = allowGen1Mint;
}
function addToWhitelist(address[] calldata toWhitelist, uint8[] calldata amount, uint240[] calldata cost) external onlyOwner {
require(toWhitelist.length == amount.length && toWhitelist.length == cost.length, 'all arguments were not the same length');
WhitelistInfo storage wlInfo;
for(uint256 i = 0; i < toWhitelist.length; i++){
address idToWhitelist = toWhitelist[i];
wlInfo = whiteList[idToWhitelist];
wlInfo.origAmount += amount[i];
wlInfo.amountRemaining += amount[i];
wlInfo.cost = cost[i];
}
}
/**
* calculate how many free tokens can be redeemed by a user
* based on how many tokens the user has bought
* @param bought the number of tokens bought
* @param lions the number of lions owned by the user
* @param zebras the number of zebras owned by the user
* @return the number of free tokens that the user can claim
*/
function freeCredits(uint256 bought, uint256 lions, uint256 zebras) internal pure returns(uint256) {
uint256 used_lions = min(bought, lions);
lions -= used_lions;
bought -= used_lions;
uint256 used_zebras = min(bought, zebras);
return used_lions * 2 + used_zebras;
}
function min(uint256 a, uint256 b) internal pure returns(uint256) {
return a <= b ? a : b;
}
modifier whenPublicMint() {
require(publicMint == true, 'public mint is not activated');
_;
}
modifier whenWhitelistMint() {
require(publicMint == false, 'whitelist mint is over');
_;
}
modifier whenGen1Mint() {
require(gen1MintEnabled == true, 'gen1 mint is not activated');
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IReserve {
function stakeMany(address account, uint16[] calldata tokenIds) external;
function randomPoacherOwner(uint256 seed) external view returns (address);
function numDepositedPoachersOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
contract SafariOGWhitelist {
bytes internal offsets = hex"0000001800300048005a006600780084009600ae00f001080108010e01500168019201b001c801ec01f8020402100228025e027c0294029a02b202d002e202e803000306030c032a034203540366037e039003b403de04140432044a047a049204b004ce04f205280546056a058e05ac05ca05f4061e0630067206a206ba06cc06de06fc0714072c073e0756075c076e0780079e07c807ec080a08160828085208700882088e08a008b808e208e808fa090c09240942095a0978098a09ae09ea09f00a080a1a0a260a380a3e0a560a680a7a0a9e0abc0ae00aec0b040b220b4c0b640b8e0bac0bc40bdc0bf40c120c360c420c540c600c720c900ca20cb40ccc0cde0cf60d200d2c0d3e0d5c0d620d9e0daa0dce0df20dfe0e1c0e280e400e580e6a0e7c0ea60ec40edc0efa0f060f1e0f3c0f600f900fc00fde1002101a1038104a10621080109810a410c210d410e010ec10fe111611461164118e11b211d611f4121212301254128412ae12cc12f0132c133e135c136e1386139813aa13bc13da1404141c143a14521464147c148814a614b814d014f414fa1506151815361560158a15ba15cc15e416021632164a166e1680169e16b616c216ce16ec170a17161740174017461764178e17ac17ca17fa18181824183c1860189018a818ba18e4190e192c193e19501974198c19b019da19fe1a281a461a641a761a9a1aac1abe";
bytes internal items = hex"0000000000041b26000000018ca400000003fcdd00000007337300000002353c000001009e5c00000104caaf00000100045b0000000128850000050f35ba00000001736d00000102004900000001893300000005d0f900000001cd3800000001ebe800000001005000000001235500000001379b00000001737000000109cd18000000023f0d00000005538a00000628d7d70000000215910000010535bf000000063ff900000001b071000000030deb000000012700000002082dfe000000015647000000075f330000000460ca0000000373c2000000068f5c00000100bde20000020be3b50000000ce4800000000107bd00000001465700000003848400000003fb20000006190ac7000000014640000000025eeb0000000273aa0000010b77c6000000017c7100000005804e000001038b3a00000001cf5700000006d18200000004da9900000200df260000010968ec00000002815c00000102916100000001b50c000000015e9900000100600500000001817600000003932500000014e82600000202e8590000060eeb6e000000040825000000010f5b00000002a78700000101c89f00000001d353000000012b3200000001a54d00000001e46500000002ef200000010843d00000000454f4000000015e5100000001adc000000003b11500000002c782000000025d02000001026db700000002246f00000004a74800000002093000000001e8750000010927990000010539490000000549e200000002f2ba0000000221e40000000350ca0000000267350000000370c6000000017a6800000007b64c00000004c6e900000001c73800000205d41100000003494f0000010454fe00000001996200000005bd7c00000003e25a0000000422dd00000002391d00000004b0cc00000201b446000000057bd900000001293700000d85a90d0000073aabe300000003f3a7000001081f6b000000012943000000032b72000000053c3600000100c3190000000aa5b800000001c30100000b32cc7e000000042316000000051041000000018c3d000000018cef0000010392c00000010ae4b2000000048d560000010f62b7000000027b68000000038f9f00000001d82900000001fc3100000101851700000001a17f00000001b2db00000007c1e1000000079a49000000029f9300000003e5ed00000002044000000001b90700000001cd0c00000001631e00000103b02000000002deb000000004f640000001019ea000000003b75500000007c5930000000505dc0000020208f000000101a69f00000001b4d600000009dcf600000001e76a000000010ded0000000232b300000001480300000105c9e000000001e76a00000307e9b200000003fdb00000000400f6000000050e4e00000001140600000001193c000000034040000000025ba60000000c849a00000003c93e00000009ebaa0000010411300000000136100000010367200000010277fb0000000a83ae0000000519bc0000000196e400000002c41100000103f00e0000020332f0000000014eb9000000026cea000000017e60000002048e6c00000003a65e00000100bacd00000001f65f000000052673000000023c4100000003c20600000003ea47000000010e040000000216040000000350f500000001c06600000101f0260000000155b4000002307e7900000005904600000002a21e00000002fcc80000000106f400000102171d000003066a8e000000019e9200000001c4eb00000111ddf4000000010562000000020beb0000010913f50000000114550000000138bf000000016696000000016c500000010a707400000001e37a0000000100ce0000000239c20000000662c90000000ca10700000205e2a8000000044e2a000000015f2d00000005996600000003a08200000002b5f300000003f3600000010a34b200000004721500000102bd1700000003bd320000020bbe2700000104e94d000001047fc700000001852d00000104961500000106b73f00000003be2b000000011b4b00000208294500000001a8f800000001c9eb00000200e22900000001439f0000020344d4000000074ca5000000035ce10000000283550000000286c500000109abad00000100168900000204206000000002486100000002542e000000016b8e00000002970c000000019b6700000001136400000003693500000306f7f80000000221d700000005639b0000000269be0000010090c900000003977a000000029f2f00000100af3400000412b62700000002bd8d00000001c44100000002eff80000000105e60000010013c2000000012b07000000062c57000001004cad0000050b5c9700000002702500000105dd9b0000000177f9000001017fa0000000029f18000000019f92000000018f0b00000007e98d00000002fa38000000032ca7000000026e0800000003aaa60000000331490000000146d3000000014c5e00000001711b0000072fee01000000011c4b000000062be8000000013c0a00000001bba8000000011ab90000010521e200000102bdb500000002f34400000212547b00000002691300000001db5d000000031029000000012dcc00000109c5db00000003cabd00000108ce930000010405d80000000289a800000004f41d00000004326e0000010143e50000000167d4000000012f9b000000023b610000000b920e000000029a0f00000228e148000001123b360000000349d40000010c7dfb00000001819300000002918d000000049b9100000001cfba00000003124c000001027e8d00000109915e00000208b6c000000206eb5000000102feff0000010032f80000000539cd0000000169be000000029a1600000002aa9200000002618d00000101888e0000010442d600000003c67500000311ce05000002001e7f000001012cb200000205613500000002743600000003a01d00000001a11100000009e83c000000032404000000016b8200000006aff700000109b8b700000001f33d000000040e4300000313368600000107f92a00000100c2bc00000004ef2b000000041a19000000035a52000000056f78000000032ff6000000018d4d00000003cfa100000002da6f00000100349c0000000138f00000000855760000000159f0000000016a110000000192ac00000001f2eb00000102e1740000000710f1000000021b5500000100543700000002021800000005145000000001e259000000011a9c000000011bd400000207a49d00000001d70b0000000305e9000000021f8a0000020f8e1600000002b27200000002e0d00000000117fb000000039b6400000002cba600000001f75200000002049c0000031b17d1000000044f870000010374c300000203b054000000043311000000024dda000000017a9f0000010f17c2000000012c6e0000001e7a4b00000001b60200000001e37d00000001ec6e00000004067900000001070c000000010c3d000001115c8100000004ae8500000002b27c00000001b2b000000003b5dc00000006e2c700000002e83200000104d8dc0000000430a0000000044cb80000000150270000000173b70000020175cc000000017ea900000002933d00000001222900000103a15000000004035f0000000938e800000001c8e10000010444ff000000053bcd000000025d5200000001dcf700000003ea52000000028e960000000e9035000000039e2500000001159a000001019be800000101c30900000002372a000001123cb40000000c419f000000018ad500000001ae4400000102b53a000000023285000000013969000001013a0f000001026f11000002098ce70000000103fd000000010d47000001003bf1000003123c1c00000001c5d10000000dcb80000000020dd3000000012b43000000010811000000013da3000000015cbf00000100712f0000000384ab00000102877a000000038e51000001029b0000000207a248000000014dcb000001035349000000018a5b0000040898af00000102d11800000001db820000010aef09000001004f7a00000005b9a800000104e19a00000205e97d0000000407d3000001070a4d000000031ab500000002a5e000000002a85100000004cdc500000001e4d7000000085766000000056031000001027bb9000000029aec00000001ab7a000000015062000000027f2500000006c33100000001d6930000090a3f4d000000034cab00000104854c0000000b91970000000635a000000001a26800000104e6ce00000002f0e6000000011aac00000002594b00000002915e0000020693f900000002eb44000002012f37000002034abe000000019beb00000001c69400000117daf100000002f2bf0000000129a500000002e276000000020fa60000011559c700000003eae40000000101cc0000000214cf000001031ded00000004a76500000629eaf4000000015b24000000016be90000020c8e5000000001adca00000001ea5800000205689e00000005982c000001059a70000000023fbf00000001737400000003a8dd00000001b20800000001c68a00000100f0f100000001f61c000004151c1e00000001648e0000000a915c000000036b0e000000037d370000000295d700000001eb13000001062763000000032efa000000013d9a00000104665900000200729700000001c48700000005cd1b000003000da40000020be8e9000001051dcd000000024b4700000001c1ba00000002314400000001451d00000002571400000200e0f900000002ecbe00000001ccac0000000300b4000000012007000000015d1f0000010260fc00000004649d00000001688000000101781d000002107d2f000000017ec3000000028c8100000001483200000003d96700000002004a0000010418d0000000028d740000000292c8000000019bfc00000001b9520000000102820000000118f0000001004c43000000025a37000000039caf00000008aa0d00000005362700000003fb3a0000010231ce00000001732c00000002d98300000001ea6700000002ec84000000018d2c00000002aa11000000032b7900000001d98800000202e16b00000001fe9c00000003182f00000101a3dc00000001aaf800000002e76e000001006da000000002913600000001c622000000021df200000003477d00000002c400000000011ff20000000340e3000000038e940000000193f300000002b08500000004cda40000010cf34a000002021c0b0000020620ae00000001756200000004b1bd00000002e9b9000000011318000000022dc50000000384f200000002e11c000001013a4800000101446f00000003979700000001c1cd00000001f04100000001012c00000003896d000000010aea00000002233400000002a3420000040bf91e0000000160f40000000174bf00000001916e00000216b10f00000001bf8d000000012e09000004114b18000000019ed400000103b9cf00000102fdf300000002ff0800000001010a000000046e1d0000023e834100000108881c0000000a9e5800000001aa2f00000001c46100000002ec060000000127b8000000012d3e000000074dbc0000000175a600000001796000000201a98500000002d3c000000001e94700000001330c0000000a5932000000015aec000000016a4000000007e550000001024ca7000000054f9b00000103530500000003621000000001cfae0000000ee7a9000000014f7d000000016f7900000002c73c00000009e120000002028d7a00000001b3350000000fbb0500000001d81900000001d915000000012909000000012f310000020971b100000001196b00000205593d00000001ee1d00000104efdc00000b0006130000000153dc000000019ecd00000101cff300000007ee0b00000100449b00000004cc9f00000001d06f00000103ea5500000005285600000102e567000000011e460000000132b0000001019b0700000100adc800000002b4910000010e622200000102887100000100890f0000000a45b4000000038e15000000039e1000000009f034000000010935000001090d78000000041feb000000034db100000001525900000002c86c00000002f9c00000000106e20000010051300000000454fa000006076ea50000000196a5000005009d3900000003a3a500000003e3090000000101110000000525750000000730340000000134d60000000187090000040c159c000000014b880000000167720000010282170000000194e000000108a57300000001ca38000000013904000000014cc90000000177d500000001b04000000003c35400000006c3c100000101926000000005c29d00000001da870000000ade7500000001ef6700000001f605000000021cc50000000551720000030c84b600000001c4cb00000002fc8b0000010300dd000000012ac8000000019dc800000001a2cf00000001acf00000020410c300000100bd9400000307c75400000103e0f700000001f9640000010105be0000020440220000000254d500000001b8fb00000008c7ff00000106f40e00000200557b000000025bba0000000161b500000001918000000003ab080000000ac95400000005d6db00000002e0240000000372d5000000017678000000018ef900000001b12400000005cf3c00000001e8bb00000104f5d800000005243a0000000134f600000003800700000006915000000005bc660000000104f30000000143c9000000048a8e000000029e3800000103cae000000001d5af0000000303110000010107c600000004132300000006358f000000028f0f00000204a41700000101af430000020bbc1400000002dc1c00000007ff76000000014580000000107ac300000112e6a30000000143670000020555ee000000057d1300000003bc870000020df43e00000002264100000001b64500000009c708000000014c5800000106a39e00000005aac900000009d171000000022f380000010095d600000002be9b00000005743000000104c10200000001d37e000000022e3d000000065bea000001039bc3000004011dac0000000175f300000002c7e300000004f7c200000002fc3d000001032bdb0000000136c0000000015c2500000001a97700000001add300000002e8cd00000001fac60000000444800000001a65960000000869ef000000018d5000000105390800000002889700000003978400000008d10900000009e7c3000004110840000002082f1200000109342400000103fd9500000001cac600000105dcdc00000200e85a0000000181c0000001019c0300000203a97700000003b43a000009120b17000000017cfd000000010f53000000015d32000000037c5800000003c50100000002d1b40000000acb1800000101cec700000001e69d000000012eff000000036f3d000000018a850000010d8b1f0000040938d00000000340d8000005029d8100000002a7e600000100c47a00000003cb7200000001eb3c0000021220a600000108b4bd00000001134f00000015bf8300000001f46e0000000320ae0000010951aa00000005a4e300000103cb7200000002f7aa000000013b55000000033b89000000015e8200000305988200000105baf000000006c75900000001e5cb0000020226eb0000041939e200000001ceca00000008d99300000001e1f300000003fb2a0000000efcc8000000015600000000025cf0000001018f0100000205a2d300000200a56f00000001b39700000001be4300000003d9160000010168b5000001007b140000000185f1000000026b92000000036f800000000aeb6400000001f5ff000001081a54000001042c2d0000030933fb00000001932200000208d14a0000000108ab000000011e9700000003258c000000014a310000020ea7710000000bbb8d00000005ce0e00000001f07f0000000312ed00000001a35a00000100ced700000004df88000001081920000000093ef80000000143490000000167700000000197aa000000019b6c0000000206c4000000059b8300000002abba0000000123d100000002602d00000104d72700000002e0f500000004f685000000011de1000000012a6200000005bc0f00000210fac2000000013506000000016b63000000022dc600000001a9c90000000108d0000000011e160000040c797c00000001b47b00000007dd690000000209ba0000010622410000000358c700000003798d0000000dd94d000000044bbf00000005e7b30000000106c300000001191700000005513500000004754500000001d4c600000003f93f00000003ff740000000213f80000010311e00000000155170000000157160000010ab42e00000008cf56000000010f0c0000000128bf000000023300000001107db000000001a5a900000002ac2d00000001b52e000002064c9800000106906d00000101a81700000001c3a30000000ec8ca0000010216a8000002193bd90000031a40fc00000001714900000001750c000000010101000003090d1600000006125f00000002551e00000101bb8300000001c76500000001e0fa00000300fa960000000107f600000001417f000000025041000001075dbd00000002b28c000000013ed900000103a5f4000000010b0500000107b13200000103cf6c00000001fe5500000002077b000001010c4e00000001950200000003c8a600000001e7e200000001f43800000021393f000010794a27000000039ea300000001a03300000001b28500000005d68c00000001e47600000001feb90000020c1dbb00000001223b00000001cf5d00000003d27c00000001589900000002d28900000002e96300000001109800000105263b000000052d22000000014da10000010475290000000490dd00000005c19d0000000439c3000001033d32000000019d2e00000001aa9e00000116f17800000001f23800000001fa530000000158e90000000f88ea00000003943100000004a9f500000103c9b00000000107b3000000010e7c00000003aec60000010a1fc100000001307d00000002fbb2000000014eab0000000550870000000266bf00000002676e000000016e530000020fbdc10000000100c900000001102500000105e19f00000317fd65000001031f90000000014386000000017e7900000002aee100000002cc0500000001edbb000000010a18000000012601000001002b15000000014ac000000001c79600000001ce6b00000107d4810000000124ae000000043def0000010545e6000000044cf600000002d0a400000119fc5b0000000116710000021542f30000000a5d7b000001068c2c00000002b0b300000004cdd300000001f3280000000124480000000173950000000189ec000000029f2000000004a6140000000a112600000001273a000000017c4c000000018c6500000001c393000000037bc9000000019e0d00000100d51c0000010522670000000270330000010271500000000395c4000000059bf800000001cd5000000002aa5c00000001dbe300000003dca5000000045ec300000001e14600000005fd3200000001";
address public owner;
address public minting_contract;
constructor() {
owner = msg.sender;
}
function setOwner(address addr) external {
require(msg.sender == owner, 'you are not the owner');
owner = addr;
}
function setMintingContract(address addr) external {
require(msg.sender == owner, 'you are not the owner');
minting_contract = addr;
}
function balanceOf(address holder) external view returns(uint256) {
uint8 bought;
uint8 claimed;
uint8 lions;
uint8 zebras;
(bought, claimed, lions, zebras) = this.getInfo(holder);
return uint256(lions) + uint256(zebras);
}
function getInfo(address holder) external view returns(uint8 number_bought, uint8 number_free_claimed, uint8 lions_owned, uint8 zebras_owned) {
uint16 first = uint16(uint160(holder) >> 152 & 0xff) * 2;
uint16 addr_part = uint16(uint160(holder) >> 136);
uint256 slot0 = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
uint16 offset;
uint16 end;
assembly {
offset := and(shr(mul(sub(30,mod( first,32)),8),sload(add(slot0,div( first,32)))),0xffff)
end := and(shr(mul(sub(30,mod(add(first,2),32)),8),sload(add(slot0,div(add(first,2),32)))),0xffff)
}
for (; offset < end; offset += 6) {
if (uint16(uint8(items[offset]) *256 + uint8(items[offset+1])) == addr_part) {
return (uint8(items[offset+2]),uint8(items[offset+3]),uint8(items[offset+4]),uint8(items[offset+5]));
}
}
return (uint8(0),uint8(0),uint8(0),uint8(0));
}
function getInfoPacked(address holder) external view returns(uint256) {
uint256 first = uint16(uint160(holder) >> 152 & 0xff) * 2;
uint256 addr_part = uint16(uint160(holder) >> 136);
uint256 slot0 = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
uint256 slot1 = 0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6;
uint256 offset;
uint256 end;
assembly {
offset := and(shr(mul(sub(30,mod( first,32)),8),sload(add(slot0,div( first,32)))),0xffff)
end := and(shr(mul(sub(30,mod(add(first,2),32)),8),sload(add(slot0,div(add(first,2),32)))),0xffff)
}
uint256 result;
assembly {
let i := and(offset, 0xffff)
let e := and(end, 0xffff)
let slot_index := add(slot1, div(i, 32))
let slot_val := sload(slot_index)
let shift_amount := mul(sub(30, mod(i, 32)), 8)
let this_addr_part
for { } lt(i, e) { } {
this_addr_part := and(shr(shift_amount, slot_val), 0xffff)
switch eq(this_addr_part, addr_part)
case true { // found the address
result := shl(32, i)
switch shift_amount
case 0 {
slot_val := sload(add(slot_index, 1))
result := add(result, shr(224, slot_val))
}
case 16 {
result := add(result, shl(16, and(slot_val, 0xffff)))
slot_val := sload(add(slot_index, 1))
result := add(result, shr(240, slot_val))
}
default {
result := add(result, and(shr(sub(shift_amount, 32), slot_val), 0xffffffff))
}
let p := mload(0x40)
mstore(0x40, add(mload(0x40), 0x20))
mstore(p, result)
return(p, 32)
}
case false { // this_addr_part != addr_part
i := add(i, 6)
switch gt(shift_amount, 32)
case true {
shift_amount := sub(shift_amount, 48)
}
case false {
slot_index := add(slot_index, 1)
slot_val := sload(slot_index)
shift_amount := add(208, shift_amount)
}
}
}
}
revert('you are not in the whitelist');
}
function setBoughtAndClaimed(uint16 offset, uint16 bought_and_claimed) external {
require(msg.sender == minting_contract, 'you are not the minting contract');
items[offset+2] = bytes1(uint8(bought_and_claimed >> 8));
items[offset+3] = bytes1(uint8(bought_and_claimed));
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract SafariErc20 is UUPSUpgradeable, ERC20Upgradeable, OwnableUpgradeable {
// a mapping from an address to whether or not it can mint / burn
mapping(address => bool) controllers;
address public stripesAddress;
bool public stripesBurning;
function initialize(string memory name, string memory symbol, address stripes) public initializer {
__ERC20_init(name, symbol);
__Ownable_init();
stripesAddress = stripes;
stripesBurning = false;
}
function upgrade(address stripes) public onlyOwner {
stripesAddress = stripes;
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
function mint(address to, uint256 amount) external {
require(controllers[msg.sender], "Only controllers can mint");
_mint(to, amount);
}
function burn(address from, uint256 amount) external {
require(controllers[msg.sender], "Only controllers can burn");
_burn(from, amount);
}
function burnStripes(uint256 amount) external {
require(stripesBurning, 'burning stripes is not currently allowed');
IERC20(stripesAddress).transferFrom(_msgSender(), address(this), amount);
_mint(_msgSender(), amount);
}
function setStripesBurning(bool val) external onlyOwner {
stripesBurning = val;
}
/**
* enables an address to mint / burn
* @param controller the address to enable
*/
function addController(address controller) external onlyOwner {
controllers[controller] = true;
}
/**
* disables an address from minting / burning
* @param controller the address to disbale
*/
function removeController(address controller) external onlyOwner {
controllers[controller] = false;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "./token-metadata.sol";
interface ISafariErc721 {
function totalSupply() external view returns(uint256);
function batchMint(address recipient, SafariToken.Metadata[] memory _tokenMetadata, uint16[] memory tokenIds) external;
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
uint8 constant MIN_ALPHA = 5;
uint8 constant MAX_ALPHA = 8;
uint8 constant POACHER = 1;
uint8 constant ANIMAL = 2;
uint8 constant APR = 3;
uint8 constant RHINO = 0;
uint8 constant CHEETAH = 1;
uint8 constant propertiesStart = 128;
uint8 constant propertiesSize = 128;
library SafariToken {
// struct to store each token's traits
struct Metadata {
bytes32 _value;
}
function create(bytes32 raw) internal pure returns(Metadata memory) {
Metadata memory meta = Metadata(raw);
return meta;
}
function getCharacterType(Metadata memory meta) internal pure returns(uint8) {
return uint8(bytes1(meta._value));
}
function setCharacterType(Metadata memory meta, uint8 characterType) internal pure {
meta._value = (meta._value & 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) | (bytes32(bytes1(characterType)));
}
function getAlpha(Metadata memory meta) internal pure returns(uint8) {
return uint8(bytes1(meta._value << (8*1)));
}
function setAlpha(Metadata memory meta, uint8 alpha) internal pure {
meta._value = (meta._value & 0xff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) | (bytes32(bytes1(alpha)) >> (8*1));
}
function getCharacterSubtype(Metadata memory meta) internal pure returns(uint8) {
return uint8(bytes1(meta._value << (8*2)));
}
function setCharacterSubtype(Metadata memory meta, uint8 subType) internal pure {
meta._value = (meta._value & 0xffff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) | (bytes32(bytes1(subType)) >> (8*2));
}
function isSpecial(Metadata memory meta) internal pure returns(bool) {
return bool(uint8(bytes1(meta._value << (8*3) & bytes1(0x01))) == 0x01);
}
function setSpecial(Metadata memory meta, bool _isSpecial) internal pure {
bytes1 specialVal = bytes1(_isSpecial ? 0x01 : 0x00);
meta._value = (meta._value & 0xfffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff) | (bytes32(specialVal) >> (8*3));
}
function getReserved(Metadata memory meta) internal pure returns(bytes29) {
return bytes29(meta._value << (8*3));
}
function isPoacher(Metadata memory meta) internal pure returns(bool) {
return getCharacterType(meta) == POACHER;
}
function isAnimal(Metadata memory meta) internal pure returns(bool) {
return getCharacterType(meta) == ANIMAL;
}
function isRhino(Metadata memory meta) internal pure returns(bool) {
return getCharacterType(meta) == ANIMAL && getCharacterSubtype(meta) == RHINO;
}
function isAPR(Metadata memory meta) internal pure returns(bool) {
return getCharacterType(meta) == APR;
}
function setSpecial(Metadata memory meta, Metadata[] storage specials) internal {
Metadata memory special = specials[specials.length-1];
meta._value = special._value;
specials.pop();
}
function setProperty(Metadata memory meta, uint256 fieldStart, uint256 fieldSize, uint256 value) internal view {
setField(meta, fieldStart + propertiesStart, fieldSize, value);
}
function getProperty(Metadata memory meta, uint256 fieldStart, uint256 fieldSize) internal pure returns(uint256) {
return getField(meta, fieldStart + propertiesStart, fieldSize);
}
function setField(Metadata memory meta, uint256 fieldStart, uint256 fieldSize, uint256 value) internal view {
require(value < (1 << fieldSize), 'attempted to set a field to a value that exceeds the field size');
uint256 shiftAmount = 256 - (fieldStart + fieldSize);
bytes32 mask = ~bytes32(((1 << fieldSize) - 1) << shiftAmount);
bytes32 fieldVal = bytes32(value << shiftAmount);
meta._value = (meta._value & mask) | fieldVal;
}
function getField(Metadata memory meta, uint256 fieldStart, uint256 fieldSize) internal pure returns(uint256) {
uint256 shiftAmount = 256 - (fieldStart + fieldSize);
bytes32 mask = bytes32(((1 << fieldSize) - 1) << shiftAmount);
bytes32 fieldVal = meta._value & mask;
return uint256(fieldVal >> shiftAmount);
}
function getRaw(Metadata memory meta) internal pure returns(bytes32) {
return meta._value;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.5;
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "./token-metadata.sol";
contract SafariTokenMeta is UUPSUpgradeable, OwnableUpgradeable {
using SafariToken for SafariToken.Metadata;
using Strings for uint256;
struct TraitInfo {
uint16 weight;
uint16 end;
bytes28 name;
}
struct PartInfo {
uint8 fieldSize;
uint8 fieldOffset;
bytes28 name;
}
PartInfo[] public partInfo;
mapping(uint256 => TraitInfo[]) public partTraitInfo;
struct PartCombo {
uint8 part1;
uint8 trait1;
uint8 part2;
uint8 traits2Len;
uint8[28] traits2;
}
PartCombo[] public mandatoryCombos;
PartCombo[] public forbiddenCombos;
function initialize() public initializer {
__Ownable_init_unchained();
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
function buildSpecial(uint256[] calldata traits) external view returns(bytes32) {
require(traits.length == partInfo.length, string(abi.encodePacked('need ', partInfo.length.toString(), ' elements')));
SafariToken.Metadata memory newData;
PartInfo storage _partInfo;
uint256 i;
for (i=0; i<partInfo.length; i++) {
_partInfo = partInfo[i];
newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, traits[i]);
}
return newData._value;
}
function setMandatoryCombos(uint256[] calldata parts1, uint256[] calldata traits1, uint256[] calldata parts2, uint256[][] calldata traits2) external onlyOwner {
require(parts1.length == traits1.length && parts1.length == parts2.length && parts1.length == traits2.length, 'all arguments must be arrays of the same length');
delete mandatoryCombos;
uint256 i;
for (i=0; i<parts1.length; i++) {
addMandatoryCombo(parts1[i], traits1[i], parts2[i], traits2[i][0]);
}
}
function addMandatoryCombo(uint256 part1, uint256 trait1, uint256 part2, uint256 trait2) internal {
mandatoryCombos.push();
PartCombo storage combo = mandatoryCombos[mandatoryCombos.length-1];
combo.part1 = uint8(part1);
combo.trait1 = uint8(trait1);
combo.part2 = uint8(part2);
combo.traits2Len = uint8(1);
combo.traits2[0] = uint8(trait2);
}
// this should only be used to correct errors in trait names
function setPartTraitNames(uint256[] calldata parts, uint256[] calldata traits, string[] memory names) external onlyOwner {
require(parts.length == traits.length && parts.length == names.length, 'all arguments must be arrays of the same length');
uint256 i;
for (i=0; i<parts.length; i++) {
require(partTraitInfo[parts[i]].length > traits[i], 'you tried to set the name of a property that does not exist');
partTraitInfo[parts[i]][traits[i]].name = stringToBytes28(names[i]);
}
}
// set the odds of getting a trait. dividing the weight of a trait by the sum of all trait weights yields the odds of minting that trait
function setPartTraitWeights(uint256[] calldata parts, uint256[] calldata traits, uint256[] calldata weights) external onlyOwner {
require(parts.length == traits.length && parts.length == weights.length, 'all arguments must be arrays of the same length');
uint256 i;
for (i=0; i<parts.length; i++) {
require(partTraitInfo[parts[i]].length < traits[i], 'you tried to set the odds of a property that does not exist');
partTraitInfo[parts[i]][traits[i]].weight = uint16(weights[i]);
}
_updatePartTraitWeightRanges();
}
// after trait weights are changed this runs to update the ranges
function _updatePartTraitWeightRanges() internal {
uint256 offset;
TraitInfo storage traitInfo;
uint256 i;
uint256 j;
for (i=0; i<partInfo.length; i++) {
offset = 0;
for (j=0; j<partTraitInfo[i].length; j++) {
traitInfo = partTraitInfo[i][j];
offset += traitInfo.weight;
traitInfo.end = uint16(offset);
}
}
}
function addPartTraits(uint256[] calldata parts, uint256[] calldata weights, string[] calldata names) external onlyOwner {
require(parts.length == weights.length && parts.length == names.length, 'all arguments must be arrays of the same length');
uint256 i;
for (i=0; i<parts.length; i++) {
_addPartTrait(parts[i], weights[i], names[i]);
}
_updatePartTraitWeightRanges();
}
function _addPartTrait(uint256 part, uint256 weight, string calldata name) internal {
TraitInfo memory traitInfo;
traitInfo.weight = uint16(weight);
traitInfo.name = stringToBytes28(name);
partTraitInfo[part].push(traitInfo);
}
function addParts(uint256[] calldata fieldSizes, string[] calldata names) external onlyOwner {
require(fieldSizes.length == names.length, 'all arguments must be arrays of the same length');
PartInfo memory _partInfo;
uint256 fieldOffset;
if (partInfo.length > 0) {
_partInfo = partInfo[partInfo.length-1];
fieldOffset = _partInfo.fieldOffset + _partInfo.fieldSize;
}
uint256 i;
for (i=0; i<fieldSizes.length; i++) {
_partInfo.name = stringToBytes28(names[i]);
_partInfo.fieldOffset = uint8(fieldOffset);
_partInfo.fieldSize = uint8(fieldSizes[i]);
partInfo.push(_partInfo);
fieldOffset += fieldSizes[i];
}
}
function getMeta(SafariToken.Metadata memory tokenMeta, uint256 tokenId, string memory baseURL) external view returns(string memory) {
bytes memory metaStr = abi.encodePacked(
'{',
'"name":"SafariBattle #', tokenId.toString(), '",',
'"image":"', baseURL, _getSpecificURLPart(tokenMeta), '",',
'"attributes":[', _getAttributes(tokenMeta), ']'
'}'
);
return string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(metaStr)
)
);
}
function _getSpecificURLPart(SafariToken.Metadata memory tokenMeta) internal view returns(string memory) {
bytes memory result = abi.encodePacked('?');
PartInfo storage _partInfo;
bool isFirst = true;
uint256 i;
for (i=0; i<partInfo.length; i++) {
if (!isFirst) {
result = abi.encodePacked(result, '&');
}
isFirst = false;
_partInfo = partInfo[i];
result = abi.encodePacked(
result, bytes28ToString(_partInfo.name),
'=',
bytes28ToString(partTraitInfo[i][tokenMeta.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize)].name)
);
}
return string(result);
}
function _getAttributes(SafariToken.Metadata memory tokenMeta) internal view returns(string memory) {
bytes memory result;
PartInfo storage _partInfo;
bool isFirst = true;
string memory traitValue;
uint256 i;
for (i=0; i<partInfo.length; i++) {
_partInfo = partInfo[i];
traitValue = bytes28ToString(partTraitInfo[i][tokenMeta.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize)].name);
if (bytes(traitValue).length == 0) {
continue;
}
if (!isFirst) {
result = abi.encodePacked(result, ',');
}
isFirst = false;
result = abi.encodePacked(
result,
'{',
'"trait_type":"', bytes28ToString(_partInfo.name), '",',
'"value":"', traitValue, '"',
'}'
);
}
return string(result);
}
function generateProperties(uint256 randomVal, uint256 tokenId) external view returns(SafariToken.Metadata memory) {
SafariToken.Metadata memory newData;
PartInfo storage _partInfo;
uint256 trait;
uint256 i;
for (i=0; i<partInfo.length; i++) {
_partInfo = partInfo[i];
trait = genPart(i, randomVal);
newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, trait);
randomVal >>= 8;
}
PartCombo storage combo;
for (i=0; i<mandatoryCombos.length; i++) {
combo = mandatoryCombos[i];
_partInfo = partInfo[combo.part1];
if (newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize) != combo.trait1) {
continue;
}
_partInfo = partInfo[combo.part2];
if (newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize) != combo.traits2[0]) {
newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, combo.traits2[0]);
}
}
uint256 j;
bool bad;
for (i=0; i<forbiddenCombos.length; i++) {
combo = forbiddenCombos[i];
_partInfo = partInfo[combo.part1];
if (newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize) != combo.trait1) {
continue;
}
_partInfo = partInfo[combo.part2];
trait = newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize);
// generate a new trait until one is found that doesn't conflict
while (true) {
bad = false;
for (j=0; j<combo.traits2.length; j++) {
if (trait == combo.traits2[i]) {
bad = true;
break;
}
}
if (!bad) {
break;
}
trait = genPart(combo.part2, randomVal);
newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, trait);
randomVal >>= 8;
}
}
return newData;
}
function genPart(uint256 part, uint256 randomVal) internal view returns(uint256) {
TraitInfo storage traitInfo;
traitInfo = partTraitInfo[part][partTraitInfo[part].length-1];
uint256 partTotalWeight = traitInfo.end;
uint256 selected = randomVal % partTotalWeight;
uint256 start = 0;
uint256 i;
for (i=0; i<partTraitInfo[part].length; i++) {
traitInfo = partTraitInfo[part][i];
if (selected >= start && selected < traitInfo.end) {
return i;
}
start = traitInfo.end;
}
require(false, string(abi.encodePacked('did not find a trait: part: ', part.toString(), ', total weight: ', partTotalWeight.toString(), ', selected: ', selected.toString())));
}
function min(uint256 a, uint256 b) internal pure returns(uint256) {
return a <= b ? a : b;
}
function bytes28ToString(bytes28 _bytes28) public pure returns (string memory) {
uint256 i = 0;
// find the end of the string
while(i < 28 && _bytes28[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 28 && _bytes28[i] != 0; i++) {
bytesArray[i] = _bytes28[i];
}
return string(bytesArray);
}
function stringToBytes28(string memory _string) public pure returns (bytes28) {
bytes28 _bytes28;
bytes memory bytesArray = bytes(_string);
require(bytesArray.length <= 28, 'string is longer than 28 bytes');
uint256 i = 0;
for (i = 0; i<bytesArray.length; i++) {
_bytes28 |= bytes28(bytesArray[i]) >> (i*8);
}
return _bytes28;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate that the this implementation remains valid after an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// 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 AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// 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 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// 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 (last updated v4.5.0) (utils/Base64.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*
* _Available since v4.5._
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// Loads the table into memory
string memory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
// and split into 4 numbers of 6 bits.
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
// - `data.length + 2` -> Round up
// - `/ 3` -> Number of 3-bytes chunks
// - `4 *` -> 4 characters for each chunk
string memory result = new string(4 * ((data.length + 2) / 3));
assembly {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 32)
// Run over the input, 3 bytes at a time
for {
let dataPtr := data
let endPtr := add(data, mload(data))
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 bytes (18 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F which is the number of
// the previous character in the ASCII table prior to the Base64 Table
// The result is then added to the table to get the character to write,
// and finally write it in the result pointer but with a left shift
// of 256 (1 byte) - 8 (1 ASCII char) = 248 bits
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
} | calculate how many free tokens can be redeemed by a user based on how many tokens the user has bought bought the number of tokens bought lions the number of lions owned by the user zebras the number of zebras owned by the user return the number of free tokens that the user can claim/ | function freeCredits(uint256 bought, uint256 lions, uint256 zebras) internal pure returns(uint256) {
uint256 used_lions = min(bought, lions);
lions -= used_lions;
bought -= used_lions;
uint256 used_zebras = min(bought, zebras);
return used_lions * 2 + used_zebras;
}
| 1,304,076 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ResellingCredit.sol";
import "./RegenerationCredit.sol";
import "./ReclothesShopRoleManager.sol";
import "./ReclothesShopDataTypes.sol";
/**
* @title Public core ReClothes on-chain business logic smart contract. This contract enables Customers to send boxes of second-hand clothes,
* buy new clothes, and enable the Dealer to evaluate the boxes and sell saleable (second-hand/upcycled) clothes.
* This contract guarantees data consistency across private interaction between Recyclers and Dealer, storing those interactions'
* available public output.
* @author LINKS Foundation.
*/
contract ReclothesShop is ReclothesShopRoleManager {
/** Events */
event SecondHandBoxSent(uint boxId, string description, CLOTH_TYPE[] clothesTypes, uint[] quantities);
event SecondHandBoxEvaluated(uint boxId, uint rscAmount);
event SecondHandClothesStored(CLOTH_TYPE clothType, uint quantity);
event SaleableClothAdded(uint clothId, uint rscPrice, CLOTH_TYPE clothType, CLOTH_SIZE clothSize, CLOTH_STATUS clothStatus, string description, bytes extClothDataHash);
event SaleableClothSold(uint clothId, uint rscPrice);
event ConfidentialUpcycledClothOnSale(uint clothId, string confidentialTxHash);
event ConfidentialBoxSent(CLOTH_TYPE[] clothesTypes, uint[] quantities, string confidentialTxHash);
event ConfidentialTokenTransfer(address sender, address receiver, uint amount, string confidentialTxHash);
/** Storage */
ResellingCredit public resellingCreditInstance;
RegenerationCredit public regenerationCreditInstance;
address public reclothesDealer;
/// @dev Associate a price (expressed in RSC tokens) for every possible cloth type.
mapping(CLOTH_TYPE => uint) public clothTypeToEvaluationPrice;
/// @dev Return the Box associated to its unique numeric identifier; otherwise an empty Box.
mapping(uint => Box) public idToBox;
/// @dev Return the list of SecondHandClothes associated to a Box; otherwise an empty array.
mapping(uint => SecondHandClothes[]) public boxToSecondHandClothes;
/// @dev Return the SaleableCloth associated to its unique numeric identifier; otherwise an empty SaleableCloth.
mapping(uint => SaleableCloth) public idToSaleableCloth;
/// @dev Associate a quantity for every possible cloth type (i.e., the clothes are aggregated by cloth type inside the Dealer inventory).
mapping(CLOTH_TYPE => uint) public inventory;
/// @dev Return the list of unique identifiers for each Box sent by a Customer; otherwise an empty array.
mapping(address => uint[]) public customerToBoxesIds;
/// @dev Return the list of unique identifiers for each SaleableClothes purchased by a Customer; otherwise an empty array.
mapping(address => uint[]) public customerToPurchasedClothesIds;
/// @dev Store every SaleableClothes unique identifier.
uint[] private _saleableClothesIds;
/** Modifiers */
/// @dev Evaluate true when the provided identifier is greater than zero and it is not used for another Box.
modifier isValidBoxId(uint _id) {
require(_id > 0, "ZERO-ID");
require(idToBox[_id].id == 0, "ALREADY-USED-ID");
_;
}
/// @dev Evaluate true when the provided identifier is greater than zero and it is not used for another SaleableCloth.
modifier isValidClothId(uint _id) {
require(_id > 0, "ZERO-ID");
require(idToSaleableCloth[_id].id == 0, "ALREADY-SALEABLE-CLOTH");
_;
}
/// @dev Evaluate true when the provided identifier is used for a Box.
modifier isBox(uint _boxId) {
require(idToBox[_boxId].id == _boxId, "NOT-BOX");
_;
}
/// @dev Avoid inconsistency between clothes types and quantities arrays.
modifier areTypesAndQuantitiesArrayInvalid(CLOTH_TYPE[] calldata _clothesTypes, uint[] calldata _quantities) {
require(_clothesTypes.length == _quantities.length && _clothesTypes.length <= 6, "INVALID-ARRAYS");
_;
}
/** Methods */
/**
* @notice Deploy a new instance of ReclothesShop smart contract.
* @param _resellingCreditAddress The address of the ResellingCredit smart contract.
* @param _regenerationCreditAddress The address of the RegenerationCredit smart contract.
*/
constructor(
address _resellingCreditAddress,
address _regenerationCreditAddress
) {
// Setup the role for the Reclothes Dealer.
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
reclothesDealer = msg.sender;
// Setup ResellingCredit Token smart contract instance.
resellingCreditInstance = ResellingCredit(_resellingCreditAddress);
// Setup RegenerationCredit Token smart contract instance.
regenerationCreditInstance = RegenerationCredit(_regenerationCreditAddress);
// Standard pricing list for second-hand clothes evaluation in RSC tokens.
clothTypeToEvaluationPrice[CLOTH_TYPE.OTHER] = 2;
clothTypeToEvaluationPrice[CLOTH_TYPE.TSHIRT] = 4;
clothTypeToEvaluationPrice[CLOTH_TYPE.PANT] = 7;
clothTypeToEvaluationPrice[CLOTH_TYPE.JACKET] = 15;
clothTypeToEvaluationPrice[CLOTH_TYPE.DRESS] = 8;
clothTypeToEvaluationPrice[CLOTH_TYPE.SHIRT] = 10;
}
/**
* @notice Send second-hand clothes Box from a Customer account.
* @param _boxId The unique numeric id used for identifying the box.
* @param _description A short description of the box content.
* @param _clothesTypes The clothes types which are contained in the box.
* @param _quantities A quantity for each cloth type contained in the box.
*/
function sendBoxForEvaluation(
uint _boxId,
string calldata _description,
CLOTH_TYPE[] calldata _clothesTypes,
uint[] calldata _quantities
)
external
onlyCustomer isValidBoxId(_boxId) areTypesAndQuantitiesArrayInvalid(_clothesTypes, _quantities) {
Box memory secondHandClothesBox = Box(
_boxId,
block.timestamp, /// @dev Using "block.timestamp" here is safe because it is not involved in critical time constraints operations.
_clothesTypes.length,
0,
_description,
msg.sender
);
// Create the SecondHandClothes array for the box clothes.
for (uint i = 0; i < _clothesTypes.length; i++) {
require(_quantities[i] > 0, "ZERO-QUANTITY");
boxToSecondHandClothes[_boxId].push(
SecondHandClothes(CLOTH_TYPE(_clothesTypes[i]), _quantities[i])
);
}
// Storage update.
idToBox[_boxId] = secondHandClothesBox;
customerToBoxesIds[msg.sender].push(_boxId);
// Event emit.
emit SecondHandBoxSent(_boxId, _description, _clothesTypes, _quantities);
}
/**
* @notice Evaluate a box of second-hand clothes and remunerate the sender with RSC tokens.
* @dev RSC tokens' allowance from Dealer to ReclothesShop must satisfy the evaluation made with the pricing list plus the extra amount.
* @param _boxId The unique numeric id used for identifying the box.
* @param _extraAmountRSC An additional remuneration in RSC tokens for the box sender.
*/
function evaluateBox(uint _boxId, uint _extraAmountRSC)
external
isBox(_boxId)
onlyReclothesDealer {
require(idToBox[_boxId].evaluationInToken == 0, "ALREADY-EVALUATED");
// Estimation of the amount of RSC tokens to be transferred from the Dealer to the sender of the box.
uint rscAmount = _extraAmountRSC;
SecondHandClothes[] memory secondHandClothes = boxToSecondHandClothes[_boxId];
for (uint i = 0; i < secondHandClothes.length; i++) {
rscAmount += clothTypeToEvaluationPrice[secondHandClothes[i].clothType] * secondHandClothes[i].quantity;
}
// Dealer inventory update.
for (uint i = 0; i < secondHandClothes.length; i++) {
inventory[CLOTH_TYPE(secondHandClothes[i].clothType)] += secondHandClothes[i].quantity;
emit SecondHandClothesStored(secondHandClothes[i].clothType, secondHandClothes[i].quantity);
}
// Storage update.
idToBox[_boxId].evaluationInToken = rscAmount;
// Event emit.
emit SecondHandBoxEvaluated(_boxId, rscAmount);
// Token transfer from Dealer to box sender (Customer).
resellingCreditInstance.transferFrom(reclothesDealer, idToBox[_boxId].sender, rscAmount);
}
/**
* @notice Sell a second-hand cloth in the shop.
* @dev Decrease by one the quantity of the chosen cloth type from the Dealer inventory.
* @param _clothId The unique numeric id used for identifying the SaleableCloth.
* @param _rscPrice The price of the SaleableCloth expressed in RSC tokens.
* @param _clothType The type of cloth to sell.
* @param _clothSize The size of cloth to sell.
* @param _description A short description of the cloth.
* @param _extClothDataHash A hash of external information related to the dress to sell (e.g., link to the cloth photo).
*/
function sellSecondHandCloth(
uint _clothId,
uint _rscPrice,
CLOTH_TYPE _clothType,
CLOTH_SIZE _clothSize,
string calldata _description,
bytes calldata _extClothDataHash
) external {
require(inventory[_clothType] > 0, "INVENTORY-ZERO-QUANTITY");
_sellCloth(
_clothId,
_rscPrice,
_clothType,
_clothSize,
CLOTH_STATUS.SECOND_HAND,
_description,
_extClothDataHash
);
// Storage update.
inventory[_clothType] -= 1;
}
/**
* @notice Sell an upcycled cloth in the shop.
* @dev Requires the confidential transaction hash relating to the confidential transaction sent by the Dealer for buying the cloth from a Recycler.
* @param _clothId The unique numeric id used for identifying the SaleableCloth.
* @param _rscPrice The price of the SaleableCloth expressed in RSC tokens.
* @param _clothType The type of cloth to sell.
* @param _clothSize The size of cloth to sell.
* @param _description A short description of the cloth.
* @param _extClothDataHash A hash of external information related to the dress to sell (e.g., link to the cloth photo).
* @param _confidentialTxHash The hash of the confidential transaction sent by the Dealer for buying the cloth from a Recycler.
*/
function sellUpcycledCloth(
uint _clothId,
uint _rscPrice,
CLOTH_TYPE _clothType,
CLOTH_SIZE _clothSize,
string calldata _description,
bytes calldata _extClothDataHash,
string calldata _confidentialTxHash
) external {
_sellCloth(
_clothId,
_rscPrice,
_clothType,
_clothSize,
CLOTH_STATUS.UPCYCLED,
_description,
_extClothDataHash
);
// Event emit.
emit ConfidentialUpcycledClothOnSale(_clothId, _confidentialTxHash);
}
/**
* @notice Buy a cloth from the shop.
* @param _clothId The unique numeric id used for identifying the SaleableCloth available in the shop.
*/
function buyCloth(uint _clothId)
external
onlyCustomer {
require(idToSaleableCloth[_clothId].id == _clothId, "INVALID-CLOTH");
require(idToSaleableCloth[_clothId].buyer == address(0x0), "ALREADY-SOLD");
// Storage update.
idToSaleableCloth[_clothId].buyer = msg.sender;
customerToPurchasedClothesIds[msg.sender].push(_clothId);
// Event emit.
emit SaleableClothSold(_clothId, idToSaleableCloth[_clothId].price);
// Token transfer from sender (Customer) to Dealer.
resellingCreditInstance.transferFrom(msg.sender, reclothesDealer, idToSaleableCloth[_clothId].price);
}
/**
* @notice Decrease the Dealer inventory clothes types quantities for the provided amounts.
* @dev Requires the confidential transaction hash relating to the confidential transaction sent by the Dealer to send a box of second-hand clothes to a Recycler.
* @param _clothesTypes The types of clothes to sell.
* @param _quantities The quantities for each cloth type.
* @param _confidentialTxHash The hash of the confidential transaction sent by the Dealer to send a box of second-hand clothes to a Recycler.
*/
function decreaseStockForConfidentialBox(
CLOTH_TYPE[] calldata _clothesTypes,
uint[] calldata _quantities,
string calldata _confidentialTxHash
)
external
onlyReclothesDealer areTypesAndQuantitiesArrayInvalid(_clothesTypes, _quantities) {
// Dealer inventory update.
for (uint i = 0; i < _clothesTypes.length; i++) {
require(_quantities[i] > 0, "ZERO-QUANTITY");
inventory[_clothesTypes[i]] -= _quantities[i];
}
// Event emit.
emit ConfidentialBoxSent(_clothesTypes, _quantities, _confidentialTxHash);
}
/**
* @notice Transfer a RSC token amount from Dealer to Recycler.
* @dev Requires the confidential transaction hash relating to the confidential transaction sent by the Dealer for buying the cloth from a Recycler.
* @param _recycler The Recycler EOA.
* @param _rscAmount The RSC token amount to transfer.
* @param _confidentialTxHash The hash of the confidential transaction sent by the Dealer for buying the cloth from a Recycler.
*/
function transferRSCForConfidentialTx(
address _recycler,
uint _rscAmount,
string calldata _confidentialTxHash
)
external
isRecycler(_recycler)
onlyReclothesDealer {
require(_rscAmount > 0, "ZERO-AMOUNT");
// Event emit.
emit ConfidentialTokenTransfer(msg.sender, _recycler, _rscAmount, _confidentialTxHash);
// Token transfer from Dealer to Recycler.
resellingCreditInstance.transferFrom(msg.sender, _recycler, _rscAmount);
}
/**
* @notice Transfer a RSC token amount from Recycler to Dealer.
* @dev Requires the confidential transaction hash relating to the confidential transaction sent by the Recycler for evaluating a second-hand clothes box sent by the Dealer.
* @param _rgcAmount The RGC token amount to transfer.
* @param _confidentialTxHash The hash of the confidential transaction sent by the Recycler for evaluating a second-hand clothes box sent by the Dealer.
*/
function transferRGCForConfidentialTx(
uint _rgcAmount,
string calldata _confidentialTxHash
)
external
onlyRecycler {
require(_rgcAmount > 0, "ZERO-AMOUNT");
// Event emit.
emit ConfidentialTokenTransfer(msg.sender, reclothesDealer, _rgcAmount, _confidentialTxHash);
// Token transfer from Recycler to Dealer.
regenerationCreditInstance.transferFrom(msg.sender, reclothesDealer, _rgcAmount);
}
/**
* @notice Sell a cloth in the shop.
* @param _clothId The unique numeric id used for identifying the SaleableCloth.
* @param _rscPrice The price of the SaleableCloth expressed in RSC tokens.
* @param _clothType The type of cloth to sell.
* @param _clothSize The size of cloth to sell.
* @param _clothStatus The status of cloth to sell.
* @param _description A short description of the cloth.
* @param _extClothDataHash A hash of external information related to the dress to sell (e.g., link to the cloth photo).
*/
function _sellCloth(
uint _clothId,
uint _rscPrice,
CLOTH_TYPE _clothType,
CLOTH_SIZE _clothSize,
CLOTH_STATUS _clothStatus,
string calldata _description,
bytes calldata _extClothDataHash
)
internal
isValidClothId(_clothId)
onlyReclothesDealer {
require(_rscPrice > 0, "INVALID-PRICE");
SaleableCloth memory saleableCloth = SaleableCloth(
_clothId,
_rscPrice,
CLOTH_TYPE(_clothType),
_clothSize,
_clothStatus,
_description,
address(0x0),
block.timestamp, /// @dev Using "block.timestamp" here is safe because it is not involved in critical time constraints operations.
_extClothDataHash
);
// Storage update.
_saleableClothesIds.push(_clothId);
idToSaleableCloth[_clothId] = saleableCloth;
// Event emit.
emit SaleableClothAdded(_clothId, _rscPrice, _clothType, _clothSize, CLOTH_STATUS.UPCYCLED, _description, _extClothDataHash);
}
/**
* @notice Return the unique identifiers of every SaleableCloth.
* @return The list of unique identifiers.
*/
function getAllSaleableClothesIds() external view returns(uint[] memory){
return _saleableClothesIds;
}
/**
* @notice Return the unique identifiers of every Box sent by the provided Customer.
* @return The list of unique identifiers.
*/
function getAllCustomerBoxesIds(address _customer) external view returns(uint[] memory){
return customerToBoxesIds[_customer];
}
/**
* @notice Return the unique identifiers of every SaleableCloth purchased by the provided Customer.
* @return The list of unique identifiers.
*/
function getAllPurchasedClothesIds(address _customer) external view returns(uint[] memory){
return customerToPurchasedClothesIds[_customer];
}
}
| Sell an upcycled cloth in the shop. Requires the confidential transaction hash relating to the confidential transaction sent by the Dealer for buying the cloth from a Recycler. _clothId The unique numeric id used for identifying the SaleableCloth. _rscPrice The price of the SaleableCloth expressed in RSC tokens. _clothType The type of cloth to sell. _clothSize The size of cloth to sell. _description A short description of the cloth. _extClothDataHash A hash of external information related to the dress to sell (e.g., link to the cloth photo). _confidentialTxHash The hash of the confidential transaction sent by the Dealer for buying the cloth from a Recycler./ Event emit. | function sellUpcycledCloth(
uint _clothId,
uint _rscPrice,
CLOTH_TYPE _clothType,
CLOTH_SIZE _clothSize,
string calldata _description,
bytes calldata _extClothDataHash,
string calldata _confidentialTxHash
) external {
_sellCloth(
_clothId,
_rscPrice,
_clothType,
_clothSize,
CLOTH_STATUS.UPCYCLED,
_description,
_extClothDataHash
);
emit ConfidentialUpcycledClothOnSale(_clothId, _confidentialTxHash);
}
| 12,669,084 |
./full_match/1/0x6098e8B4E04eB643E4f93b0Cd4f454B9aCE884B2/sources/lib/solady/src/utils/MerkleProofLib.sol | @solidity memory-safe-assembly Cache the lengths of the arrays. Advance the pointers of the arrays to point to the data. If the number of flags is correct. For the case where `proof.length + leafs.length == 1`. `isValid = (proof.length == 1 ? proof[0] : leafs[0]) == root`. | function verifyMultiProof(
bytes32[] memory proof,
bytes32 root,
bytes32[] memory leafs,
bool[] memory flags
assembly {
let leafsLength := mload(leafs)
let proofLength := mload(proof)
let flagsLength := mload(flags)
leafs := add(0x20, leafs)
proof := add(0x20, proof)
flags := add(0x20, flags)
if iszero(flagsLength) {
isValid := eq(mload(xor(leafs, mul(xor(proof, leafs), proofLength))), root)
break
}
mstore(add(hashesFront, i), mload(add(leafs, i)))
}
hashesFront := add(hashesFront, 0x40)
| 17,135,101 |
./full_match/1/0xB6937eeeEECC8f2a9FAc89dBDdfF00c98420c996/sources/contracts/HegicOptionsNFT.sol | Exercises underlying option _tokenId ID of the token that holds the option to be exercised/ | function exerciseOption(uint _tokenId) external onlyTokenOwnerOrApproved(_tokenId) returns (uint profit){
uint optionId = underlyingOptionId[_tokenId];
optionsProvider.exercise(optionId);
profit = _transferBalance(msg.sender);
emit Exercised(ownerOf(_tokenId), _tokenId, optionId, profit);
}
| 16,533,711 |
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
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;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "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;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract Lunar is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 10000000000 * 10**6 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Lunar Finance';
string private _symbol = 'LUNAR';
uint8 private _decimals = 9;
constructor () public {
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflect(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
}
function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) {
uint256 tFee = tAmount.div(100).mul(2);
uint256 tTransferAmount = tAmount.sub(tFee);
return (tTransferAmount, tFee);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} | 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 | 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;
}
| 1,092,171 |
/**
*Submitted for verification at Etherscan.io on 2021-11-30
*/
// File: contracts/components/Proxy.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma experimental ABIEncoderV2;
pragma solidity ^0.4.24;
/**
* Math operations with safety checks
*/
contract Proxy {
event Upgraded(address indexed implementation);
address internal _implementation;
function implementation() public view returns (address) {
return _implementation;
}
function () external payable {
address _impl = _implementation;
require(_impl != address(0), "implementation contract not set");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
// File: contracts/components/Owned.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.24;
/// @dev `Owned` is a base level contract that assigns an `owner` that can be
/// later changed
contract Owned {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev `owner` is the only address that can call a function with this
/// modifier
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
address public owner;
/// @notice The Constructor assigns the message sender to be `owner`
constructor() public {
owner = msg.sender;
}
address public newOwner;
function transferOwner(address _newOwner) public onlyOwner {
require(_newOwner != address(0), "New owner is the zero address");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
/// @notice `owner` can step down and assign some other address to this role
/// @param _newOwner The address of the new owner. 0x0 can be used to create
/// an unowned neutral vault, however that cannot be undone
function changeOwner(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
function renounceOwnership() public onlyOwner {
owner = address(0);
}
}
// File: contracts/components/Halt.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.24;
contract Halt is Owned {
bool public halted = false;
modifier notHalted() {
require(!halted, "Smart contract is halted");
_;
}
modifier isHalted() {
require(halted, "Smart contract is not halted");
_;
}
/// @notice function Emergency situation that requires
/// @notice contribution period to stop or not.
function setHalt(bool halt)
public
onlyOwner
{
halted = halt;
}
}
// File: contracts/components/ReentrancyGuard.sol
pragma solidity 0.4.26;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// File: contracts/lib/BasicStorageLib.sol
pragma solidity ^0.4.24;
library BasicStorageLib {
struct UintData {
mapping(bytes => mapping(bytes => uint)) _storage;
}
struct BoolData {
mapping(bytes => mapping(bytes => bool)) _storage;
}
struct AddressData {
mapping(bytes => mapping(bytes => address)) _storage;
}
struct BytesData {
mapping(bytes => mapping(bytes => bytes)) _storage;
}
struct StringData {
mapping(bytes => mapping(bytes => string)) _storage;
}
/* uintStorage */
function setStorage(UintData storage self, bytes memory key, bytes memory innerKey, uint value) internal {
self._storage[key][innerKey] = value;
}
function getStorage(UintData storage self, bytes memory key, bytes memory innerKey) internal view returns (uint) {
return self._storage[key][innerKey];
}
function delStorage(UintData storage self, bytes memory key, bytes memory innerKey) internal {
delete self._storage[key][innerKey];
}
/* boolStorage */
function setStorage(BoolData storage self, bytes memory key, bytes memory innerKey, bool value) internal {
self._storage[key][innerKey] = value;
}
function getStorage(BoolData storage self, bytes memory key, bytes memory innerKey) internal view returns (bool) {
return self._storage[key][innerKey];
}
function delStorage(BoolData storage self, bytes memory key, bytes memory innerKey) internal {
delete self._storage[key][innerKey];
}
/* addressStorage */
function setStorage(AddressData storage self, bytes memory key, bytes memory innerKey, address value) internal {
self._storage[key][innerKey] = value;
}
function getStorage(AddressData storage self, bytes memory key, bytes memory innerKey) internal view returns (address) {
return self._storage[key][innerKey];
}
function delStorage(AddressData storage self, bytes memory key, bytes memory innerKey) internal {
delete self._storage[key][innerKey];
}
/* bytesStorage */
function setStorage(BytesData storage self, bytes memory key, bytes memory innerKey, bytes memory value) internal {
self._storage[key][innerKey] = value;
}
function getStorage(BytesData storage self, bytes memory key, bytes memory innerKey) internal view returns (bytes memory) {
return self._storage[key][innerKey];
}
function delStorage(BytesData storage self, bytes memory key, bytes memory innerKey) internal {
delete self._storage[key][innerKey];
}
/* stringStorage */
function setStorage(StringData storage self, bytes memory key, bytes memory innerKey, string memory value) internal {
self._storage[key][innerKey] = value;
}
function getStorage(StringData storage self, bytes memory key, bytes memory innerKey) internal view returns (string memory) {
return self._storage[key][innerKey];
}
function delStorage(StringData storage self, bytes memory key, bytes memory innerKey) internal {
delete self._storage[key][innerKey];
}
}
// File: contracts/components/BasicStorage.sol
pragma solidity ^0.4.24;
contract BasicStorage {
/************************************************************
**
** VARIABLES
**
************************************************************/
//// basic variables
using BasicStorageLib for BasicStorageLib.UintData;
using BasicStorageLib for BasicStorageLib.BoolData;
using BasicStorageLib for BasicStorageLib.AddressData;
using BasicStorageLib for BasicStorageLib.BytesData;
using BasicStorageLib for BasicStorageLib.StringData;
BasicStorageLib.UintData internal uintData;
BasicStorageLib.BoolData internal boolData;
BasicStorageLib.AddressData internal addressData;
BasicStorageLib.BytesData internal bytesData;
BasicStorageLib.StringData internal stringData;
}
// File: contracts/interfaces/IRC20Protocol.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.26;
interface IRC20Protocol {
function transfer(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
function balanceOf(address _owner) external view returns (uint);
}
// File: contracts/interfaces/IQuota.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity 0.4.26;
interface IQuota {
function userLock(uint tokenId, bytes32 storemanGroupId, uint value) external;
function userBurn(uint tokenId, bytes32 storemanGroupId, uint value) external;
function smgRelease(uint tokenId, bytes32 storemanGroupId, uint value) external;
function smgMint(uint tokenId, bytes32 storemanGroupId, uint value) external;
function upgrade(bytes32 storemanGroupId) external;
function transferAsset(bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId) external;
function receiveDebt(bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId) external;
function getUserMintQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint);
function getSmgMintQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint);
function getUserBurnQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint);
function getSmgBurnQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint);
function getAsset(uint tokenId, bytes32 storemanGroupId) external view returns (uint asset, uint asset_receivable, uint asset_payable);
function getDebt(uint tokenId, bytes32 storemanGroupId) external view returns (uint debt, uint debt_receivable, uint debt_payable);
function isDebtClean(bytes32 storemanGroupId) external view returns (bool);
}
// File: contracts/interfaces/IStoremanGroup.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.24;
interface IStoremanGroup {
function getSelectedSmNumber(bytes32 groupId) external view returns(uint number);
function getStoremanGroupConfig(bytes32 id) external view returns(bytes32 groupId, uint8 status, uint deposit, uint chain1, uint chain2, uint curve1, uint curve2, bytes gpk1, bytes gpk2, uint startTime, uint endTime);
function getDeposit(bytes32 id) external view returns(uint);
function getStoremanGroupStatus(bytes32 id) external view returns(uint8 status, uint startTime, uint endTime);
function setGpk(bytes32 groupId, bytes gpk1, bytes gpk2) external;
function setInvalidSm(bytes32 groupId, uint[] indexs, uint8[] slashTypes) external returns(bool isContinue);
function getThresholdByGrpId(bytes32 groupId) external view returns (uint);
function getSelectedSmInfo(bytes32 groupId, uint index) external view returns(address wkAddr, bytes PK, bytes enodeId);
function recordSmSlash(address wk) public;
}
// File: contracts/interfaces/ITokenManager.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity 0.4.26;
interface ITokenManager {
function getTokenPairInfo(uint id) external view
returns (uint origChainID, bytes tokenOrigAccount, uint shadowChainID, bytes tokenShadowAccount);
function getTokenPairInfoSlim(uint id) external view
returns (uint origChainID, bytes tokenOrigAccount, uint shadowChainID);
function getAncestorInfo(uint id) external view
returns (bytes account, string name, string symbol, uint8 decimals, uint chainId);
function mintToken(address tokenAddress, address to, uint value) external;
function burnToken(address tokenAddress, address from, uint value) external;
}
// File: contracts/interfaces/ISignatureVerifier.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity 0.4.26;
interface ISignatureVerifier {
function verify(
uint curveId,
bytes32 signature,
bytes32 groupKeyX,
bytes32 groupKeyY,
bytes32 randomPointX,
bytes32 randomPointY,
bytes32 message
) external returns (bool);
}
// File: contracts/lib/SafeMath.sol
pragma solidity ^0.4.24;
/**
* Math operations with safety checks
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath mul overflow");
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath div 0"); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath sub b > a");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath add overflow");
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath mod 0");
return a % b;
}
}
// File: contracts/crossApproach/lib/HTLCTxLib.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.26;
library HTLCTxLib {
using SafeMath for uint;
/**
*
* ENUMS
*
*/
/// @notice tx info status
/// @notice uninitialized,locked,redeemed,revoked
enum TxStatus {None, Locked, Redeemed, Revoked, AssetLocked, DebtLocked}
/**
*
* STRUCTURES
*
*/
/// @notice struct of HTLC user mint lock parameters
struct HTLCUserParams {
bytes32 xHash; /// hash of HTLC random number
bytes32 smgID; /// ID of storeman group which user has selected
uint tokenPairID; /// token pair id on cross chain
uint value; /// exchange token value
uint lockFee; /// exchange token value
uint lockedTime; /// HTLC lock time
}
/// @notice HTLC(Hashed TimeLock Contract) tx info
struct BaseTx {
bytes32 smgID; /// HTLC transaction storeman ID
uint lockedTime; /// HTLC transaction locked time
uint beginLockedTime; /// HTLC transaction begin locked time
TxStatus status; /// HTLC transaction status
}
/// @notice user tx info
struct UserTx {
BaseTx baseTx;
uint tokenPairID;
uint value;
uint fee;
address userAccount; /// HTLC transaction sender address for the security check while user's revoke
}
/// @notice storeman tx info
struct SmgTx {
BaseTx baseTx;
uint tokenPairID;
uint value;
address userAccount; /// HTLC transaction user address for the security check while user's redeem
}
/// @notice storeman debt tx info
struct DebtTx {
BaseTx baseTx;
bytes32 srcSmgID; /// HTLC transaction sender(source storeman) ID
}
struct Data {
/// @notice mapping of hash(x) to UserTx -- xHash->htlcUserTxData
mapping(bytes32 => UserTx) mapHashXUserTxs;
/// @notice mapping of hash(x) to SmgTx -- xHash->htlcSmgTxData
mapping(bytes32 => SmgTx) mapHashXSmgTxs;
/// @notice mapping of hash(x) to DebtTx -- xHash->htlcDebtTxData
mapping(bytes32 => DebtTx) mapHashXDebtTxs;
}
/**
*
* MANIPULATIONS
*
*/
/// @notice add user transaction info
/// @param params parameters for user tx
function addUserTx(Data storage self, HTLCUserParams memory params)
public
{
UserTx memory userTx = self.mapHashXUserTxs[params.xHash];
// UserTx storage userTx = self.mapHashXUserTxs[params.xHash];
// require(params.value != 0, "Value is invalid");
require(userTx.baseTx.status == TxStatus.None, "User tx exists");
userTx.baseTx.smgID = params.smgID;
userTx.baseTx.lockedTime = params.lockedTime;
userTx.baseTx.beginLockedTime = now;
userTx.baseTx.status = TxStatus.Locked;
userTx.tokenPairID = params.tokenPairID;
userTx.value = params.value;
userTx.fee = params.lockFee;
userTx.userAccount = msg.sender;
self.mapHashXUserTxs[params.xHash] = userTx;
}
/// @notice refund coins from HTLC transaction, which is used for storeman redeem(outbound)
/// @param x HTLC random number
function redeemUserTx(Data storage self, bytes32 x)
external
returns(bytes32 xHash)
{
xHash = sha256(abi.encodePacked(x));
UserTx storage userTx = self.mapHashXUserTxs[xHash];
require(userTx.baseTx.status == TxStatus.Locked, "Status is not locked");
require(now < userTx.baseTx.beginLockedTime.add(userTx.baseTx.lockedTime), "Redeem timeout");
userTx.baseTx.status = TxStatus.Redeemed;
return xHash;
}
/// @notice revoke user transaction
/// @param xHash hash of HTLC random number
function revokeUserTx(Data storage self, bytes32 xHash)
external
{
UserTx storage userTx = self.mapHashXUserTxs[xHash];
require(userTx.baseTx.status == TxStatus.Locked, "Status is not locked");
require(now >= userTx.baseTx.beginLockedTime.add(userTx.baseTx.lockedTime), "Revoke is not permitted");
userTx.baseTx.status = TxStatus.Revoked;
}
/// @notice function for get user info
/// @param xHash hash of HTLC random number
/// @return smgID ID of storeman which user has selected
/// @return tokenPairID token pair ID of cross chain
/// @return value exchange value
/// @return fee exchange fee
/// @return userAccount HTLC transaction sender address for the security check while user's revoke
function getUserTx(Data storage self, bytes32 xHash)
external
view
returns (bytes32, uint, uint, uint, address)
{
UserTx storage userTx = self.mapHashXUserTxs[xHash];
return (userTx.baseTx.smgID, userTx.tokenPairID, userTx.value, userTx.fee, userTx.userAccount);
}
/// @notice add storeman transaction info
/// @param xHash hash of HTLC random number
/// @param smgID ID of the storeman which user has selected
/// @param tokenPairID token pair ID of cross chain
/// @param value HTLC transfer value of token
/// @param userAccount user account address on the destination chain, which is used to redeem token
function addSmgTx(Data storage self, bytes32 xHash, bytes32 smgID, uint tokenPairID, uint value, address userAccount, uint lockedTime)
external
{
SmgTx memory smgTx = self.mapHashXSmgTxs[xHash];
// SmgTx storage smgTx = self.mapHashXSmgTxs[xHash];
require(value != 0, "Value is invalid");
require(smgTx.baseTx.status == TxStatus.None, "Smg tx exists");
smgTx.baseTx.smgID = smgID;
smgTx.baseTx.status = TxStatus.Locked;
smgTx.baseTx.lockedTime = lockedTime;
smgTx.baseTx.beginLockedTime = now;
smgTx.tokenPairID = tokenPairID;
smgTx.value = value;
smgTx.userAccount = userAccount;
self.mapHashXSmgTxs[xHash] = smgTx;
}
/// @notice refund coins from HTLC transaction, which is used for users redeem(inbound)
/// @param x HTLC random number
function redeemSmgTx(Data storage self, bytes32 x)
external
returns(bytes32 xHash)
{
xHash = sha256(abi.encodePacked(x));
SmgTx storage smgTx = self.mapHashXSmgTxs[xHash];
require(smgTx.baseTx.status == TxStatus.Locked, "Status is not locked");
require(now < smgTx.baseTx.beginLockedTime.add(smgTx.baseTx.lockedTime), "Redeem timeout");
smgTx.baseTx.status = TxStatus.Redeemed;
return xHash;
}
/// @notice revoke storeman transaction
/// @param xHash hash of HTLC random number
function revokeSmgTx(Data storage self, bytes32 xHash)
external
{
SmgTx storage smgTx = self.mapHashXSmgTxs[xHash];
require(smgTx.baseTx.status == TxStatus.Locked, "Status is not locked");
require(now >= smgTx.baseTx.beginLockedTime.add(smgTx.baseTx.lockedTime), "Revoke is not permitted");
smgTx.baseTx.status = TxStatus.Revoked;
}
/// @notice function for get smg info
/// @param xHash hash of HTLC random number
/// @return smgID ID of storeman which user has selected
/// @return tokenPairID token pair ID of cross chain
/// @return value exchange value
/// @return userAccount user account address for redeem
function getSmgTx(Data storage self, bytes32 xHash)
external
view
returns (bytes32, uint, uint, address)
{
SmgTx storage smgTx = self.mapHashXSmgTxs[xHash];
return (smgTx.baseTx.smgID, smgTx.tokenPairID, smgTx.value, smgTx.userAccount);
}
/// @notice add storeman transaction info
/// @param xHash hash of HTLC random number
/// @param srcSmgID ID of source storeman group
/// @param destSmgID ID of the storeman which will take over of the debt of source storeman group
/// @param lockedTime HTLC lock time
/// @param status Status, should be 'Locked' for asset or 'DebtLocked' for debt
function addDebtTx(Data storage self, bytes32 xHash, bytes32 srcSmgID, bytes32 destSmgID, uint lockedTime, TxStatus status)
external
{
DebtTx memory debtTx = self.mapHashXDebtTxs[xHash];
// DebtTx storage debtTx = self.mapHashXDebtTxs[xHash];
require(debtTx.baseTx.status == TxStatus.None, "Debt tx exists");
debtTx.baseTx.smgID = destSmgID;
debtTx.baseTx.status = status;//TxStatus.Locked;
debtTx.baseTx.lockedTime = lockedTime;
debtTx.baseTx.beginLockedTime = now;
debtTx.srcSmgID = srcSmgID;
self.mapHashXDebtTxs[xHash] = debtTx;
}
/// @notice refund coins from HTLC transaction
/// @param x HTLC random number
/// @param status Status, should be 'Locked' for asset or 'DebtLocked' for debt
function redeemDebtTx(Data storage self, bytes32 x, TxStatus status)
external
returns(bytes32 xHash)
{
xHash = sha256(abi.encodePacked(x));
DebtTx storage debtTx = self.mapHashXDebtTxs[xHash];
// require(debtTx.baseTx.status == TxStatus.Locked, "Status is not locked");
require(debtTx.baseTx.status == status, "Status is not locked");
require(now < debtTx.baseTx.beginLockedTime.add(debtTx.baseTx.lockedTime), "Redeem timeout");
debtTx.baseTx.status = TxStatus.Redeemed;
return xHash;
}
/// @notice revoke debt transaction, which is used for source storeman group
/// @param xHash hash of HTLC random number
/// @param status Status, should be 'Locked' for asset or 'DebtLocked' for debt
function revokeDebtTx(Data storage self, bytes32 xHash, TxStatus status)
external
{
DebtTx storage debtTx = self.mapHashXDebtTxs[xHash];
// require(debtTx.baseTx.status == TxStatus.Locked, "Status is not locked");
require(debtTx.baseTx.status == status, "Status is not locked");
require(now >= debtTx.baseTx.beginLockedTime.add(debtTx.baseTx.lockedTime), "Revoke is not permitted");
debtTx.baseTx.status = TxStatus.Revoked;
}
/// @notice function for get debt info
/// @param xHash hash of HTLC random number
/// @return srcSmgID ID of source storeman
/// @return destSmgID ID of destination storeman
function getDebtTx(Data storage self, bytes32 xHash)
external
view
returns (bytes32, bytes32)
{
DebtTx storage debtTx = self.mapHashXDebtTxs[xHash];
return (debtTx.srcSmgID, debtTx.baseTx.smgID);
}
function getLeftTime(uint endTime) private view returns (uint) {
if (now < endTime) {
return endTime.sub(now);
}
return 0;
}
/// @notice function for get debt info
/// @param xHash hash of HTLC random number
/// @return leftTime the left lock time
function getLeftLockedTime(Data storage self, bytes32 xHash)
external
view
returns (uint)
{
UserTx storage userTx = self.mapHashXUserTxs[xHash];
if (userTx.baseTx.status != TxStatus.None) {
return getLeftTime(userTx.baseTx.beginLockedTime.add(userTx.baseTx.lockedTime));
}
SmgTx storage smgTx = self.mapHashXSmgTxs[xHash];
if (smgTx.baseTx.status != TxStatus.None) {
return getLeftTime(smgTx.baseTx.beginLockedTime.add(smgTx.baseTx.lockedTime));
}
DebtTx storage debtTx = self.mapHashXDebtTxs[xHash];
if (debtTx.baseTx.status != TxStatus.None) {
return getLeftTime(debtTx.baseTx.beginLockedTime.add(debtTx.baseTx.lockedTime));
}
require(false, 'invalid xHash');
}
}
// File: contracts/crossApproach/lib/RapidityTxLib.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.26;
library RapidityTxLib {
/**
*
* ENUMS
*
*/
/// @notice tx info status
/// @notice uninitialized,Redeemed
enum TxStatus {None, Redeemed}
/**
*
* STRUCTURES
*
*/
struct Data {
/// @notice mapping of uniqueID to TxStatus -- uniqueID->TxStatus
mapping(bytes32 => TxStatus) mapTxStatus;
}
/**
*
* MANIPULATIONS
*
*/
/// @notice add user transaction info
/// @param uniqueID Rapidity random number
function addRapidityTx(Data storage self, bytes32 uniqueID)
internal
{
TxStatus status = self.mapTxStatus[uniqueID];
require(status == TxStatus.None, "Rapidity tx exists");
self.mapTxStatus[uniqueID] = TxStatus.Redeemed;
}
}
// File: contracts/crossApproach/lib/CrossTypesV1.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.26;
library CrossTypesV1 {
using SafeMath for uint;
/**
*
* STRUCTURES
*
*/
struct Data {
/// map of the htlc transaction info
HTLCTxLib.Data htlcTxData;
/// map of the rapidity transaction info
RapidityTxLib.Data rapidityTxData;
/// quota data of storeman group
IQuota quota;
/// token manager instance interface
ITokenManager tokenManager;
/// storemanGroup admin instance interface
IStoremanGroup smgAdminProxy;
/// storemanGroup fee admin instance address
address smgFeeProxy;
ISignatureVerifier sigVerifier;
/// @notice transaction fee, smgID => fee
mapping(bytes32 => uint) mapStoremanFee;
/// @notice transaction fee, origChainID => shadowChainID => fee
mapping(uint => mapping(uint =>uint)) mapContractFee;
/// @notice transaction fee, origChainID => shadowChainID => fee
mapping(uint => mapping(uint =>uint)) mapAgentFee;
}
/**
*
* MANIPULATIONS
*
*/
// /// @notice convert bytes32 to address
// /// @param b bytes32
// function bytes32ToAddress(bytes32 b) internal pure returns (address) {
// return address(uint160(bytes20(b))); // high
// // return address(uint160(uint256(b))); // low
// }
/// @notice convert bytes to address
/// @param b bytes
function bytesToAddress(bytes b) internal pure returns (address addr) {
assembly {
addr := mload(add(b,20))
}
}
function transfer(address tokenScAddr, address to, uint value)
internal
returns(bool)
{
uint beforeBalance;
uint afterBalance;
beforeBalance = IRC20Protocol(tokenScAddr).balanceOf(to);
// IRC20Protocol(tokenScAddr).transfer(to, value);
tokenScAddr.call(bytes4(keccak256("transfer(address,uint256)")), to, value);
afterBalance = IRC20Protocol(tokenScAddr).balanceOf(to);
return afterBalance == beforeBalance.add(value);
}
function transferFrom(address tokenScAddr, address from, address to, uint value)
internal
returns(bool)
{
uint beforeBalance;
uint afterBalance;
beforeBalance = IRC20Protocol(tokenScAddr).balanceOf(to);
// IRC20Protocol(tokenScAddr).transferFrom(from, to, value);
tokenScAddr.call(bytes4(keccak256("transferFrom(address,address,uint256)")), from, to, value);
afterBalance = IRC20Protocol(tokenScAddr).balanceOf(to);
return afterBalance == beforeBalance.add(value);
}
}
// File: contracts/crossApproach/CrossStorageV1.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.26;
contract CrossStorageV1 is BasicStorage {
using HTLCTxLib for HTLCTxLib.Data;
using RapidityTxLib for RapidityTxLib.Data;
/************************************************************
**
** VARIABLES
**
************************************************************/
CrossTypesV1.Data internal storageData;
/// @notice locked time(in seconds)
uint public lockedTime = uint(3600*36);
/// @notice Since storeman group admin receiver address may be changed, system should make sure the new address
/// @notice can be used, and the old address can not be used. The solution is add timestamp.
/// @notice unit: second
uint public smgFeeReceiverTimeout = uint(10*60);
enum GroupStatus { none, initial, curveSeted, failed, selected, ready, unregistered, dismissed }
}
// File: contracts/crossApproach/CrossStorageV2.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.26;
contract CrossStorageV2 is CrossStorageV1, ReentrancyGuard, Halt, Proxy {
/************************************************************
**
** VARIABLES
**
************************************************************/
/** STATE VARIABLES **/
uint256 public currentChainID;
address public admin;
/** STRUCTURES **/
struct SetFeesParam {
uint256 srcChainID;
uint256 destChainID;
uint256 contractFee;
uint256 agentFee;
}
struct GetFeesParam {
uint256 srcChainID;
uint256 destChainID;
}
struct GetFeesReturn {
uint256 contractFee;
uint256 agentFee;
}
}
// File: contracts/crossApproach/lib/HTLCDebtLibV2.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.26;
library HTLCDebtLibV2 {
/**
*
* STRUCTURES
*
*/
/// @notice struct of debt and asset parameters
struct DebtAssetParams {
bytes32 uniqueID; /// hash of HTLC random number
bytes32 srcSmgID; /// ID of source storeman group
bytes32 destSmgID; /// ID of destination storeman group
}
/**
*
* EVENTS
*
**/
/// @notice event of storeman asset transfer
/// @param uniqueID random number
/// @param srcSmgID ID of source storeman group
/// @param destSmgID ID of destination storeman group
event TransferAssetLogger(bytes32 indexed uniqueID, bytes32 indexed srcSmgID, bytes32 indexed destSmgID);
/// @notice event of storeman debt receive
/// @param uniqueID random number
/// @param srcSmgID ID of source storeman group
/// @param destSmgID ID of destination storeman group
event ReceiveDebtLogger(bytes32 indexed uniqueID, bytes32 indexed srcSmgID, bytes32 indexed destSmgID);
/**
*
* MANIPULATIONS
*
*/
/// @notice transfer asset
/// @param storageData Cross storage data
/// @param params parameters of storeman debt lock
function transferAsset(CrossTypesV1.Data storage storageData, DebtAssetParams memory params)
public
{
if (address(storageData.quota) != address(0)) {
storageData.quota.transferAsset(params.srcSmgID, params.destSmgID);
}
emit TransferAssetLogger(params.uniqueID, params.srcSmgID, params.destSmgID);
}
/// @notice receive debt
/// @param storageData Cross storage data
/// @param params parameters of storeman debt lock
function receiveDebt(CrossTypesV1.Data storage storageData, DebtAssetParams memory params)
public
{
if (address(storageData.quota) != address(0)) {
storageData.quota.receiveDebt(params.srcSmgID, params.destSmgID);
}
emit ReceiveDebtLogger(params.uniqueID, params.srcSmgID, params.destSmgID);
}
}
// File: contracts/interfaces/ISmgFeeProxy.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity 0.4.26;
interface ISmgFeeProxy {
function smgTransfer(bytes32 smgID) external payable;
}
// File: contracts/crossApproach/lib/RapidityLibV2.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.26;
library RapidityLibV2 {
using SafeMath for uint;
using RapidityTxLib for RapidityTxLib.Data;
/**
*
* STRUCTURES
*
*/
/// @notice struct of Rapidity storeman mint lock parameters
struct CrossFeeParams {
uint contractFee; /// token pair id on cross chain
uint agentFee; /// exchange token value
}
/// @notice struct of Rapidity storeman mint lock parameters
struct RapidityUserLockParams {
bytes32 smgID; /// ID of storeman group which user has selected
uint tokenPairID; /// token pair id on cross chain
uint value; /// exchange token value
uint currentChainID; /// current chain ID
bytes destUserAccount; /// account of shadow chain, used to receive token
}
/// @notice struct of Rapidity storeman mint lock parameters
struct RapiditySmgMintParams {
bytes32 uniqueID; /// Rapidity random number
bytes32 smgID; /// ID of storeman group which user has selected
uint tokenPairID; /// token pair id on cross chain
uint value; /// exchange token value
address destTokenAccount; /// shadow token account
address destUserAccount; /// account of shadow chain, used to receive token
}
/// @notice struct of Rapidity user burn lock parameters
struct RapidityUserBurnParams {
bytes32 smgID; /// ID of storeman group which user has selected
uint tokenPairID; /// token pair id on cross chain
uint value; /// exchange token value
uint currentChainID; /// current chain ID
uint fee; /// exchange token fee
address srcTokenAccount; /// shadow token account
bytes destUserAccount; /// account of token destination chain, used to receive token
}
/// @notice struct of Rapidity user burn lock parameters
struct RapiditySmgReleaseParams {
bytes32 uniqueID; /// Rapidity random number
bytes32 smgID; /// ID of storeman group which user has selected
uint tokenPairID; /// token pair id on cross chain
uint value; /// exchange token value
address destTokenAccount; /// original token/coin account
address destUserAccount; /// account of token original chain, used to receive token
}
/**
*
* EVENTS
*
**/
/// @notice event of exchange WRC-20 token with original chain token request
/// @notice event invoked by storeman group
/// @param smgID ID of storemanGroup
/// @param tokenPairID token pair ID of cross chain token
/// @param tokenAccount Rapidity original token account
/// @param value Rapidity value
/// @param userAccount account of shadow chain, used to receive token
event UserLockLogger(bytes32 indexed smgID, uint indexed tokenPairID, address indexed tokenAccount, uint value, uint contractFee, bytes userAccount);
/// @notice event of exchange WRC-20 token with original chain token request
/// @notice event invoked by storeman group
/// @param smgID ID of storemanGroup
/// @param tokenPairID token pair ID of cross chain token
/// @param tokenAccount Rapidity shadow token account
/// @param value Rapidity value
/// @param userAccount account of shadow chain, used to receive token
event UserBurnLogger(bytes32 indexed smgID, uint indexed tokenPairID, address indexed tokenAccount, uint value, uint contractFee, uint fee, bytes userAccount);
/// @notice event of exchange WRC-20 token with original chain token request
/// @notice event invoked by storeman group
/// @param uniqueID unique random number
/// @param smgID ID of storemanGroup
/// @param tokenPairID token pair ID of cross chain token
/// @param value Rapidity value
/// @param tokenAccount Rapidity shadow token account
/// @param userAccount account of original chain, used to receive token
event SmgMintLogger(bytes32 indexed uniqueID, bytes32 indexed smgID, uint indexed tokenPairID, uint value, address tokenAccount, address userAccount);
/// @notice event of exchange WRC-20 token with original chain token request
/// @notice event invoked by storeman group
/// @param uniqueID unique random number
/// @param smgID ID of storemanGroup
/// @param tokenPairID token pair ID of cross chain token
/// @param value Rapidity value
/// @param tokenAccount Rapidity original token account
/// @param userAccount account of original chain, used to receive token
event SmgReleaseLogger(bytes32 indexed uniqueID, bytes32 indexed smgID, uint indexed tokenPairID, uint value, address tokenAccount, address userAccount);
/**
*
* MANIPULATIONS
*
*/
/// @notice mintBridge, user lock token on token original chain
/// @notice event invoked by user mint lock
/// @param storageData Cross storage data
/// @param params parameters for user mint lock token on token original chain
function userLock(CrossTypesV1.Data storage storageData, RapidityUserLockParams memory params)
public
{
uint fromChainID;
uint toChainID;
bytes memory fromTokenAccount;
(fromChainID,fromTokenAccount,toChainID) = storageData.tokenManager.getTokenPairInfoSlim(params.tokenPairID);
require(fromChainID != 0, "Token does not exist");
if (address(storageData.quota) != address(0)) {
storageData.quota.userLock(params.tokenPairID, params.smgID, params.value);
}
uint contractFee = storageData.mapContractFee[fromChainID][toChainID];
if (contractFee > 0) {
if (storageData.smgFeeProxy == address(0)) {
storageData.mapStoremanFee[bytes32(0)] = storageData.mapStoremanFee[bytes32(0)].add(contractFee);
} else {
(storageData.smgFeeProxy).transfer(contractFee);
}
}
address tokenScAddr = CrossTypesV1.bytesToAddress(fromTokenAccount);
uint left;
if (tokenScAddr == address(0)) {
left = (msg.value).sub(params.value).sub(contractFee);
} else {
left = (msg.value).sub(contractFee);
require(CrossTypesV1.transferFrom(tokenScAddr, msg.sender, this, params.value), "Lock token failed");
}
if (left != 0) {
(msg.sender).transfer(left);
}
emit UserLockLogger(params.smgID, params.tokenPairID, tokenScAddr, params.value, contractFee, params.destUserAccount);
}
/// @notice burnBridge, user lock token on token original chain
/// @notice event invoked by user burn lock
/// @param storageData Cross storage data
/// @param params parameters for user burn lock token on token original chain
function userBurn(CrossTypesV1.Data storage storageData, RapidityUserBurnParams memory params)
public
{
ITokenManager tokenManager = storageData.tokenManager;
uint fromChainID;
uint toChainID;
bytes memory fromTokenAccount;
bytes memory toTokenAccount;
(fromChainID,fromTokenAccount,toChainID,toTokenAccount) = tokenManager.getTokenPairInfo(params.tokenPairID);
require(fromChainID != 0, "Token does not exist");
uint256 contractFee;
address tokenScAddr;
if (params.currentChainID == toChainID) {
contractFee = storageData.mapContractFee[toChainID][fromChainID];
tokenScAddr = CrossTypesV1.bytesToAddress(toTokenAccount);
} else if (params.currentChainID == fromChainID) {
contractFee = storageData.mapContractFee[fromChainID][toChainID];
tokenScAddr = CrossTypesV1.bytesToAddress(fromTokenAccount);
} else {
require(false, "Invalid token pair");
}
require(params.srcTokenAccount == tokenScAddr, "invalid token account");
if (address(storageData.quota) != address(0)) {
storageData.quota.userBurn(params.tokenPairID, params.smgID, params.value);
}
require(burnShadowToken(tokenManager, tokenScAddr, msg.sender, params.value), "burn failed");
if (contractFee > 0) {
if (storageData.smgFeeProxy == address(0)) {
storageData.mapStoremanFee[bytes32(0)] = storageData.mapStoremanFee[bytes32(0)].add(contractFee);
} else {
(storageData.smgFeeProxy).transfer(contractFee);
}
}
uint left = (msg.value).sub(contractFee);
// uint left = (msg.value).sub(contractFee);
if (left != 0) {
(msg.sender).transfer(left);
}
emit UserBurnLogger(params.smgID, params.tokenPairID, tokenScAddr, params.value, contractFee, params.fee, params.destUserAccount);
}
/// @notice mintBridge, storeman mint lock token on token shadow chain
/// @notice event invoked by user mint lock
/// @param storageData Cross storage data
/// @param params parameters for storeman mint lock token on token shadow chain
function smgMint(CrossTypesV1.Data storage storageData, RapiditySmgMintParams memory params)
public
{
storageData.rapidityTxData.addRapidityTx(params.uniqueID);
if (address(storageData.quota) != address(0)) {
storageData.quota.smgMint(params.tokenPairID, params.smgID, params.value);
}
require(mintShadowToken(storageData.tokenManager, params.destTokenAccount, params.destUserAccount, params.value), "mint failed");
emit SmgMintLogger(params.uniqueID, params.smgID, params.tokenPairID, params.value, params.destTokenAccount, params.destUserAccount);
}
/// @notice burnBridge, storeman burn lock token on token shadow chain
/// @notice event invoked by user burn lock
/// @param storageData Cross storage data
/// @param params parameters for storeman burn lock token on token shadow chain
function smgRelease(CrossTypesV1.Data storage storageData, RapiditySmgReleaseParams memory params)
public
{
storageData.rapidityTxData.addRapidityTx(params.uniqueID);
if (address(storageData.quota) != address(0)) {
storageData.quota.smgRelease(params.tokenPairID, params.smgID, params.value);
}
if (params.destTokenAccount == address(0)) {
(params.destUserAccount).transfer(params.value);
} else {
require(CrossTypesV1.transfer(params.destTokenAccount, params.destUserAccount, params.value), "Transfer token failed");
}
emit SmgReleaseLogger(params.uniqueID, params.smgID, params.tokenPairID, params.value, params.destTokenAccount, params.destUserAccount);
}
function burnShadowToken(address tokenManager, address tokenAddress, address userAccount, uint value) private returns (bool) {
uint beforeBalance;
uint afterBalance;
beforeBalance = IRC20Protocol(tokenAddress).balanceOf(userAccount);
ITokenManager(tokenManager).burnToken(tokenAddress, userAccount, value);
afterBalance = IRC20Protocol(tokenAddress).balanceOf(userAccount);
return afterBalance == beforeBalance.sub(value);
}
function mintShadowToken(address tokenManager, address tokenAddress, address userAccount, uint value) private returns (bool) {
uint beforeBalance;
uint afterBalance;
beforeBalance = IRC20Protocol(tokenAddress).balanceOf(userAccount);
ITokenManager(tokenManager).mintToken(tokenAddress, userAccount, value);
afterBalance = IRC20Protocol(tokenAddress).balanceOf(userAccount);
return afterBalance == beforeBalance.add(value);
}
}
// File: contracts/crossApproach/CrossDelegateV2.sol
/*
Copyright 2019 Wanchain 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.
*/
// _ _ _
// __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __
// \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / /
// \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V /
// \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/
//
//
pragma solidity ^0.4.26;
contract CrossDelegateV2 is CrossStorageV2 {
using SafeMath for uint;
/**
*
* EVENTS
*
**/
/// @notice event of admin config
/// @param adminAccount account of admin
event SetAdmin(address adminAccount);
/// @notice event of setFee or setFees
/// @param srcChainID source of cross chain
/// @param destChainID destination of cross chain
/// @param contractFee contract fee
/// @param agentFee agent fee
event SetFee(uint srcChainID, uint destChainID, uint contractFee, uint agentFee);
/// @notice event of storeman group ID withdraw the original coin to receiver
/// @param smgID ID of storemanGroup
/// @param timeStamp timestamp of the withdraw
/// @param receiver receiver address
/// @param fee shadow coin of the fee which the storeman group pk got it
event SmgWithdrawFeeLogger(bytes32 indexed smgID, uint indexed timeStamp, address indexed receiver, uint fee);
event WithdrawContractFeeLogger(uint indexed block, uint indexed timeStamp, address indexed receiver, uint fee);
/**
*
* MODIFIERS
*
*/
/// @notice check the admin or not
modifier onlyAdmin() {
require(msg.sender == admin, "not admin");
_;
}
/// @notice check the storeman group is ready
/// @param smgID ID of storeman group
modifier onlyReadySmg(bytes32 smgID) {
uint8 status;
uint startTime;
uint endTime;
(status,startTime,endTime) = storageData.smgAdminProxy.getStoremanGroupStatus(smgID);
require(status == uint8(GroupStatus.ready) && now >= startTime && now <= endTime, "PK is not ready");
_;
}
/**
*
* MANIPULATIONS
*
*/
/// @notice request exchange orignal coin or token with WRC20 on wanchain
/// @param smgID ID of storeman
/// @param tokenPairID token pair ID of cross chain coin/token
/// @param value exchange value
/// @param userAccount account of user, used to receive shadow chain token
function userLock(bytes32 smgID, uint tokenPairID, uint value, bytes userAccount)
external
payable
notHalted
onlyReadySmg(smgID)
{
RapidityLibV2.RapidityUserLockParams memory params = RapidityLibV2.RapidityUserLockParams({
smgID: smgID,
tokenPairID: tokenPairID,
value: value,
currentChainID: currentChainID,
destUserAccount: userAccount
});
RapidityLibV2.userLock(storageData, params);
}
/// @notice request exchange RC20 token with WRC20 on wanchain
/// @param smgID ID of storeman
/// @param tokenPairID token pair ID of cross chain token
/// @param value exchange value
/// @param userAccount account of user, used to receive original chain token
function userBurn(bytes32 smgID, uint tokenPairID, uint value, uint fee, address tokenAccount, bytes userAccount)
external
payable
notHalted
onlyReadySmg(smgID)
{
RapidityLibV2.RapidityUserBurnParams memory params = RapidityLibV2.RapidityUserBurnParams({
smgID: smgID,
tokenPairID: tokenPairID,
value: value,
fee: fee,
currentChainID: currentChainID,
srcTokenAccount: tokenAccount,
destUserAccount: userAccount
});
RapidityLibV2.userBurn(storageData, params);
}
/// @notice request exchange RC20 token with WRC20 on wanchain
/// @param uniqueID fast cross chain random number
/// @param smgID ID of storeman
/// @param tokenPairID token pair ID of cross chain token
/// @param value exchange value
/// @param userAccount address of user, used to receive WRC20 token
/// @param r signature
/// @param s signature
function smgMint(bytes32 uniqueID, bytes32 smgID, uint tokenPairID, uint value, address tokenAccount, address userAccount, bytes r, bytes32 s)
external
notHalted
{
uint curveID;
bytes memory PK;
(curveID, PK) = acquireReadySmgInfo(smgID);
RapidityLibV2.RapiditySmgMintParams memory params = RapidityLibV2.RapiditySmgMintParams({
uniqueID: uniqueID,
smgID: smgID,
tokenPairID: tokenPairID,
value: value,
destTokenAccount: tokenAccount,
destUserAccount: userAccount
});
RapidityLibV2.smgMint(storageData, params);
bytes32 mHash = sha256(abi.encode(currentChainID, uniqueID, tokenPairID, value, tokenAccount, userAccount));
verifySignature(curveID, mHash, PK, r, s);
}
/// @notice request exchange RC20 token with WRC20 on wanchain
/// @param uniqueID fast cross chain random number
/// @param smgID ID of storeman
/// @param tokenPairID token pair ID of cross chain token
/// @param value exchange value
/// @param userAccount address of user, used to receive original token/coin
/// @param r signature
/// @param s signature
function smgRelease(bytes32 uniqueID, bytes32 smgID, uint tokenPairID, uint value, address tokenAccount, address userAccount, bytes r, bytes32 s)
external
notHalted
{
uint curveID;
bytes memory PK;
(curveID, PK) = acquireReadySmgInfo(smgID);
RapidityLibV2.RapiditySmgReleaseParams memory params = RapidityLibV2.RapiditySmgReleaseParams({
uniqueID: uniqueID,
smgID: smgID,
tokenPairID: tokenPairID,
value: value,
destTokenAccount: tokenAccount,
destUserAccount: userAccount
});
RapidityLibV2.smgRelease(storageData, params);
bytes32 mHash = sha256(abi.encode(currentChainID, uniqueID, tokenPairID, value, tokenAccount, userAccount));
verifySignature(curveID, mHash, PK, r, s);
}
/// @notice transfer storeman asset
/// @param uniqueID random number (likes old xHash)
/// @param srcSmgID ID of src storeman
/// @param destSmgID ID of dst storeman
/// @param r signature
/// @param s signature
function transferAsset(bytes32 uniqueID, bytes32 srcSmgID, bytes32 destSmgID, bytes r, bytes32 s)
external
notHalted
onlyReadySmg(destSmgID)
{
uint curveID;
bytes memory PK;
(curveID, PK) = acquireUnregisteredSmgInfo(srcSmgID);
HTLCDebtLibV2.DebtAssetParams memory params = HTLCDebtLibV2.DebtAssetParams({
uniqueID: uniqueID,
srcSmgID: srcSmgID,
destSmgID: destSmgID
});
HTLCDebtLibV2.transferAsset(storageData, params);
bytes32 mHash = sha256(abi.encode(currentChainID, uniqueID, destSmgID));
verifySignature(curveID, mHash, PK, r, s);
}
/// @notice receive storeman debt
/// @param uniqueID random number (likes old xHash)
/// @param srcSmgID ID of src storeman
/// @param destSmgID ID of dst storeman
/// @param r signature
/// @param s signature
function receiveDebt(bytes32 uniqueID, bytes32 srcSmgID, bytes32 destSmgID, bytes r, bytes32 s)
external
notHalted
{
uint curveID;
bytes memory PK;
(curveID, PK) = acquireReadySmgInfo(destSmgID);
HTLCDebtLibV2.DebtAssetParams memory params = HTLCDebtLibV2.DebtAssetParams({
uniqueID: uniqueID,
srcSmgID: srcSmgID,
destSmgID: destSmgID
});
HTLCDebtLibV2.receiveDebt(storageData, params);
bytes32 mHash = sha256(abi.encode(currentChainID, uniqueID, srcSmgID));
verifySignature(curveID, mHash, PK, r, s);
}
/// @notice get the fee of the storeman group should get
/// @param param struct of setFee parameter
function setFee(SetFeesParam param)
public
onlyAdmin
{
storageData.mapContractFee[param.srcChainID][param.destChainID] = param.contractFee;
storageData.mapAgentFee[param.srcChainID][param.destChainID] = param.agentFee;
emit SetFee(param.srcChainID, param.destChainID, param.contractFee, param.agentFee);
}
/// @notice get the fee of the storeman group should get
/// @param params struct of setFees parameter
function setFees(SetFeesParam [] params) public onlyAdmin {
for (uint i = 0; i < params.length; ++i) {
storageData.mapContractFee[params[i].srcChainID][params[i].destChainID] = params[i].contractFee;
storageData.mapAgentFee[params[i].srcChainID][params[i].destChainID] = params[i].agentFee;
emit SetFee(params[i].srcChainID, params[i].destChainID, params[i].contractFee, params[i].agentFee);
}
}
function setChainID(uint256 chainID) external onlyAdmin {
if (currentChainID == 0) {
currentChainID = chainID;
}
}
function setAdmin(address adminAccount) external onlyOwner {
admin = adminAccount;
emit SetAdmin(adminAccount);
}
function setUintValue(bytes key, bytes innerKey, uint value) external onlyAdmin {
return uintData.setStorage(key, innerKey, value);
}
function delUintValue(bytes key, bytes innerKey) external onlyAdmin {
return uintData.delStorage(key, innerKey);
}
/// @notice update the initialized state value of this contract
/// @param tokenManager address of the token manager
/// @param smgAdminProxy address of the storeman group admin
/// @param smgFeeProxy address of the proxy to store fee for storeman group
/// @param quota address of the quota
/// @param sigVerifier address of the signature verifier
function setPartners(address tokenManager, address smgAdminProxy, address smgFeeProxy, address quota, address sigVerifier)
external
onlyOwner
{
// require(tokenManager != address(0) && smgAdminProxy != address(0) && quota != address(0) && sigVerifier != address(0),
// "Parameter is invalid");
require(tokenManager != address(0) && smgAdminProxy != address(0) && sigVerifier != address(0),
"Parameter is invalid");
storageData.smgAdminProxy = IStoremanGroup(smgAdminProxy);
storageData.tokenManager = ITokenManager(tokenManager);
storageData.quota = IQuota(quota);
storageData.smgFeeProxy = smgFeeProxy;
storageData.sigVerifier = ISignatureVerifier(sigVerifier);
}
/// @notice withdraw the history fee to foundation account
/// @param smgIDs array of storemanGroup ID
function smgWithdrawFee(bytes32 [] smgIDs) external {
uint fee;
uint currentFee;
address smgFeeProxy = storageData.smgFeeProxy;
if (smgFeeProxy == address(0)) {
smgFeeProxy = owner;
}
require(smgFeeProxy != address(0), "invalid smgFeeProxy");
for (uint i = 0; i < smgIDs.length; ++i) {
currentFee = storageData.mapStoremanFee[smgIDs[i]];
delete storageData.mapStoremanFee[smgIDs[i]];
fee = fee.add(currentFee);
emit SmgWithdrawFeeLogger(smgIDs[i], block.timestamp, smgFeeProxy, currentFee);
}
currentFee = storageData.mapStoremanFee[bytes32(0)];
if (currentFee > 0) {
delete storageData.mapStoremanFee[bytes32(0)];
fee = fee.add(currentFee);
}
require(fee > 0, "Fee is null");
smgFeeProxy.transfer(fee);
emit WithdrawContractFeeLogger(block.number, block.timestamp, smgFeeProxy, fee);
}
/** Get Functions */
function getUintValue(bytes key, bytes innerKey) public view returns (uint) {
return uintData.getStorage(key, innerKey);
}
/// @notice get the fee of the storeman group should get
/// @param smgID ID of storemanGroup
/// @return fee original coin the storeman group should get
function getStoremanFee(bytes32 smgID) external view returns(uint fee) {
fee = storageData.mapStoremanFee[smgID];
}
/// @notice get the fee of the storeman group should get
/// @param param struct of getFee parameter
/// @return fees struct of getFee return
function getFee(GetFeesParam param) public view returns(GetFeesReturn fee) {
fee.contractFee = storageData.mapContractFee[param.srcChainID][param.destChainID];
fee.agentFee = storageData.mapAgentFee[param.srcChainID][param.destChainID];
}
/// @notice get the fee of the storeman group should get
/// @param params struct of getFees parameter
/// @return fees struct of getFees return
function getFees(GetFeesParam [] params) public view returns(GetFeesReturn [] fees) {
fees = new GetFeesReturn[](params.length);
for (uint i = 0; i < params.length; ++i) {
fees[i].contractFee = storageData.mapContractFee[params[i].srcChainID][params[i].destChainID];
fees[i].agentFee = storageData.mapAgentFee[params[i].srcChainID][params[i].destChainID];
}
}
/// @notice get the initialized state value of this contract
/// @return tokenManager address of the token manager
/// @return smgAdminProxy address of the storeman group admin
/// @return smgFeeProxy address of the proxy to store fee for storeman group
/// @return quota address of the quota
/// @return sigVerifier address of the signature verifier
function getPartners()
external
view
returns(address tokenManager, address smgAdminProxy, address smgFeeProxy, address quota, address sigVerifier)
{
tokenManager = address(storageData.tokenManager);
smgAdminProxy = address(storageData.smgAdminProxy);
smgFeeProxy = storageData.smgFeeProxy;
quota = address(storageData.quota);
sigVerifier = address(storageData.sigVerifier);
}
/** Private and Internal Functions */
/// @notice check the storeman group is ready or not
/// @param smgID ID of storeman group
/// @return curveID ID of elliptic curve
/// @return PK PK of storeman group
function acquireReadySmgInfo(bytes32 smgID)
internal
view
returns (uint curveID, bytes memory PK)
{
uint8 status;
uint startTime;
uint endTime;
(,status,,,,curveID,,PK,,startTime,endTime) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID);
require(status == uint8(GroupStatus.ready) && now >= startTime && now <= endTime, "PK is not ready");
return (curveID, PK);
}
/// @notice get the unregistered storeman group info
/// @param smgID ID of storeman group
/// @return curveID ID of elliptic curve
/// @return PK PK of storeman group
function acquireUnregisteredSmgInfo(bytes32 smgID)
internal
view
returns (uint curveID, bytes memory PK)
{
uint8 status;
(,status,,,,curveID,,PK,,,) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID);
require(status == uint8(GroupStatus.unregistered), "PK is not unregistered");
}
/// @notice convert bytes to bytes32
/// @param b bytes array
/// @param offset offset of array to begin convert
function bytesToBytes32(bytes memory b, uint offset) internal pure returns (bytes32 result) {
assembly {
result := mload(add(add(b, offset), 32))
}
}
/// @notice verify signature
/// @param curveID ID of elliptic curve
/// @param message message to be verified
/// @param r Signature info r
/// @param s Signature info s
function verifySignature(uint curveID, bytes32 message, bytes PK, bytes r, bytes32 s) internal {
bytes32 PKx = bytesToBytes32(PK, 0);
bytes32 PKy = bytesToBytes32(PK, 32);
bytes32 Rx = bytesToBytes32(r, 0);
bytes32 Ry = bytesToBytes32(r, 32);
require(storageData.sigVerifier.verify(curveID, s, PKx, PKy, Rx, Ry, message), "Signature verification failed");
}
} | mintBridge, storeman mint lock token on token shadow chain event invoked by user mint lock storageData Cross storage data params parameters for storeman mint lock token on token shadow chain | function smgMint(CrossTypesV1.Data storage storageData, RapiditySmgMintParams memory params)
public
{
storageData.rapidityTxData.addRapidityTx(params.uniqueID);
if (address(storageData.quota) != address(0)) {
storageData.quota.smgMint(params.tokenPairID, params.smgID, params.value);
}
require(mintShadowToken(storageData.tokenManager, params.destTokenAccount, params.destUserAccount, params.value), "mint failed");
emit SmgMintLogger(params.uniqueID, params.smgID, params.tokenPairID, params.value, params.destTokenAccount, params.destUserAccount);
}
| 6,802,229 |
./full_match/1/0x91BA45E4889127d5e28df074348c6C04974C6Ba2/sources/contracts/Comptroller.sol | Checks if the liquidation should be allowed to occur cTokenBorrowed Asset which was borrowed by the borrower cTokenCollateral Asset which was used as collateral and will be seized liquidator The address repaying the borrow and seizing the collateral borrower The address of the borrower repayAmount The amount of underlying being repaid/ Shh - currently unused allow accounts to be liquidated if the market is deprecated / The borrower must have shortfall in order to be liquidatable / | function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) override external returns (uint) {
liquidator;
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower);
if (isDeprecated(CToken(cTokenBorrowed))) {
require(borrowBalance >= repayAmount, "Can not repay more than the total borrow");
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
}
return uint(Error.NO_ERROR);
}
| 3,021,529 |
./full_match/1/0x1646A4761aA54f23d7F4d5deB5D393F67D318B80/sources/contracts/interfaces/IGasSwapper.sol | GasSwapper 0xPolygon (Daniel Gretzke, Zoran Cuckovic) Allows to bridge tokens from Ethereum to Polygon Uses provided ETH to swap into MATIC to be bridged alongside the token to pay for gas on Polygon | interface IGasSwapper {
error SwapFailed(bytes reason);
error RefundFailed();
event Swap(address indexed token, address indexed user, uint256 bridgedTokenAmount, uint256 bridgedMaticAmount);
function swapAndBridge(address token, uint256 amount, address user, bytes calldata swapCallData) external payable;
pragma solidity 0.8.18;
}
| 3,222,741 |
/**
*Submitted for verification at Etherscan.io on 2021-04-01
*/
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File @animoca/ethereum-contracts-erc20_base-4.0.0/contracts/token/ERC20/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 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);
}
// File @animoca/ethereum-contracts-core_library-5.0.0/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @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 EnumMap for EnumMap.Map;
*
* // Declare a set state variable
* EnumMap.Map private myMap;
* }
* ```
*/
library EnumMap {
// 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.
// This means that we can only create new EnumMaps 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
) internal 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) internal 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) internal 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) internal 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) internal view returns (bytes32, bytes32) {
require(map.entries.length > index, "EnumMap: index out of bounds");
MapEntry storage entry = map.entries[index];
return (entry.key, entry.value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Map storage map, bytes32 key) internal view returns (bytes32) {
uint256 keyIndex = map.indexes[key];
require(keyIndex != 0, "EnumMap: nonexistent key"); // Equivalent to contains(map, key)
return map.entries[keyIndex - 1].value; // All indexes are 1-based
}
}
// File @animoca/ethereum-contracts-core_library-5.0.0/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @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 EnumSet for EnumSet.Set;
*
* // Declare a set state variable
* EnumSet.Set private mySet;
* }
* ```
*/
library EnumSet {
// 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.
// 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) internal 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) internal 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) internal view returns (bool) {
return set.indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal 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) internal view returns (bytes32) {
require(set.values.length > index, "EnumSet: index out of bounds");
return set.values[index];
}
}
// File @openzeppelin/contracts/GSN/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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 @animoca/ethereum-contracts-core_library-5.0.0/contracts/payment/[email protected]
pragma solidity 0.6.8;
/**
@title PayoutWallet
@dev adds support for a payout wallet
Note: .
*/
contract PayoutWallet is Ownable {
event PayoutWalletSet(address payoutWallet_);
address payable public payoutWallet;
constructor(address payoutWallet_) internal {
setPayoutWallet(payoutWallet_);
}
function setPayoutWallet(address payoutWallet_) public onlyOwner {
require(payoutWallet_ != address(0), "Payout: zero address");
require(payoutWallet_ != address(this), "Payout: this contract as payout");
require(payoutWallet_ != payoutWallet, "Payout: same payout wallet");
payoutWallet = payable(payoutWallet_);
emit PayoutWalletSet(payoutWallet);
}
}
// File @animoca/ethereum-contracts-core_library-5.0.0/contracts/utils/[email protected]
pragma solidity 0.6.8;
/**
* Contract module which allows derived contracts to implement a mechanism for
* activating, or 'starting', a contract.
*
* This module is used through inheritance. It will make available the modifiers
* `whenNotStarted` and `whenStarted`, which can be applied to the functions of
* your contract. Those functions will only be 'startable' once the modifiers
* are put in place.
*/
contract Startable is Context {
event Started(address account);
uint256 private _startedAt;
/**
* Modifier to make a function callable only when the contract has not started.
*/
modifier whenNotStarted() {
require(_startedAt == 0, "Startable: started");
_;
}
/**
* Modifier to make a function callable only when the contract has started.
*/
modifier whenStarted() {
require(_startedAt != 0, "Startable: not started");
_;
}
/**
* Constructor.
*/
constructor() internal {}
/**
* Returns the timestamp when the contract entered the started state.
* @return The timestamp when the contract entered the started state.
*/
function startedAt() public view returns (uint256) {
return _startedAt;
}
/**
* Triggers the started state.
* @dev Emits the Started event when the function is successfully called.
*/
function _start() internal virtual whenNotStarted {
_startedAt = now;
emit Started(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title ISale
*
* An interface for a contract which allows merchants to display products and customers to purchase them.
*
* Products, designated as SKUs, are represented by bytes32 identifiers so that an identifier can carry an
* explicit name under the form of a fixed-length string. Each SKU can be priced via up to several payment
* tokens which can be ETH and/or ERC20(s). ETH token is represented by the magic value TOKEN_ETH, which means
* this value can be used as the 'token' argument of the purchase-related functions to indicate ETH payment.
*
* The total available supply for a SKU is fixed at its creation. The magic value SUPPLY_UNLIMITED is used
* to represent a SKU with an infinite, never-decreasing supply. An optional purchase notifications receiver
* contract address can be set for a SKU at its creation: if the value is different from the zero address,
* the function `onPurchaseNotificationReceived` will be called on this address upon every purchase of the SKU.
*
* This interface is designed to be consistent while managing a variety of implementation scenarios. It is
* also intended to be developer-friendly: all vital information is consistently deductible from the events
* (backend-oriented), as well as retrievable through calls to public functions (frontend-oriented).
*/
interface ISale {
/**
* Event emitted to notify about the magic values necessary for interfacing with this contract.
* @param names An array of names for the magic values used by the contract.
* @param values An array of values for the magic values used by the contract.
*/
event MagicValues(bytes32[] names, bytes32[] values);
/**
* Event emitted to notify about the creation of a SKU.
* @param sku The identifier of the created SKU.
* @param totalSupply The initial total supply for sale.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver If not the zero address, the address of a contract on which `onPurchaseNotificationReceived` will be called after
* each purchase. If this is the zero address, the call is not enabled.
*/
event SkuCreation(bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver);
/**
* Event emitted to notify about a change in the pricing of a SKU.
* @dev `tokens` and `prices` arrays MUST have the same length.
* @param sku The identifier of the updated SKU.
* @param tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled.
* @param prices An array of updated prices for each of the payment tokens.
* Zero price values are used for payment tokens being disabled.
*/
event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices);
/**
* Event emitted to notify about a purchase.
* @param purchaser The initiater and buyer of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token used as the currency for the payment.
* @param sku The identifier of the purchased SKU.
* @param quantity The purchased quantity.
* @param userData Optional extra user input data.
* @param totalPrice The amount of `token` paid.
* @param extData Implementation-specific extra purchase data, such as
* details about discounts applied, conversion rates, purchase receipts, etc.
*/
event Purchase(
address indexed purchaser,
address recipient,
address indexed token,
bytes32 indexed sku,
uint256 quantity,
bytes userData,
uint256 totalPrice,
bytes extData
);
/**
* Returns the magic value used to represent the ETH payment token.
* @dev MUST NOT be the zero address.
* @return the magic value used to represent the ETH payment token.
*/
// solhint-disable-next-line func-name-mixedcase
function TOKEN_ETH() external pure returns (address);
/**
* Returns the magic value used to represent an infinite, never-decreasing SKU's supply.
* @dev MUST NOT be zero.
* @return the magic value used to represent an infinite, never-decreasing SKU's supply.
*/
// solhint-disable-next-line func-name-mixedcase
function SUPPLY_UNLIMITED() external pure returns (uint256);
/**
* Performs a purchase.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the address zero.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable;
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price to pay.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view returns (uint256 totalPrice, bytes32[] memory pricingData);
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
);
/**
* Returns the list of created SKU identifiers.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of SKUs is bounded, so that this function does not run out of gas.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view returns (bytes32[] memory skus);
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title IPurchaseNotificationsReceiver
* Interface for any contract that wants to support purchase notifications from a Sale contract.
*/
interface IPurchaseNotificationsReceiver {
/**
* Handles the receipt of a purchase notification.
* @dev This function MUST return the function selector, otherwise the caller will revert the transaction.
* The selector to be returned can be obtained as `this.onPurchaseNotificationReceived.selector`
* @dev This function MAY throw.
* @param purchaser The purchaser of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
* @param totalPrice The total price paid.
* @param pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* @param paymentData Implementation-specific extra payment data, such as conversion rates.
* @param deliveryData Implementation-specific extra delivery data, such as purchase receipts.
* @return `bytes4(keccak256(
* "onPurchaseNotificationReceived(address,address,address,bytes32,uint256,bytes,uint256,bytes32[],bytes32[],bytes32[])"))`
*/
function onPurchaseNotificationReceived(
address purchaser,
address recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData,
uint256 totalPrice,
bytes32[] calldata pricingData,
bytes32[] calldata paymentData,
bytes32[] calldata deliveryData
) external returns (bytes4);
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/abstract/[email protected]
pragma solidity 0.6.8;
/**
* @title PurchaseLifeCycles
* An abstract contract which define the life cycles for a purchase implementer.
*/
abstract contract PurchaseLifeCycles {
/**
* Wrapper for the purchase data passed as argument to the life cycle functions and down to their step functions.
*/
struct PurchaseData {
address payable purchaser;
address payable recipient;
address token;
bytes32 sku;
uint256 quantity;
bytes userData;
uint256 totalPrice;
bytes32[] pricingData;
bytes32[] paymentData;
bytes32[] deliveryData;
}
/* Internal Life Cycle Functions */
/**
* `estimatePurchase` lifecycle.
* @param purchase The purchase conditions.
*/
function _estimatePurchase(PurchaseData memory purchase) internal view virtual returns (uint256 totalPrice, bytes32[] memory pricingData) {
_validation(purchase);
_pricing(purchase);
totalPrice = purchase.totalPrice;
pricingData = purchase.pricingData;
}
/**
* `purchaseFor` lifecycle.
* @param purchase The purchase conditions.
*/
function _purchaseFor(PurchaseData memory purchase) internal virtual {
_validation(purchase);
_pricing(purchase);
_payment(purchase);
_delivery(purchase);
_notification(purchase);
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal view virtual;
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal view virtual;
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual;
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/abstract/[email protected]
pragma solidity 0.6.8;
/**
* @title Sale
* An abstract base sale contract with a minimal implementation of ISale and administration functions.
* A minimal implementation of the `_validation`, `_delivery` and `notification` life cycle step functions
* are provided, but the inheriting contract must implement `_pricing` and `_payment`.
*/
abstract contract Sale is PurchaseLifeCycles, ISale, PayoutWallet, Startable, Pausable {
using Address for address;
using SafeMath for uint256;
using EnumSet for EnumSet.Set;
using EnumMap for EnumMap.Map;
struct SkuInfo {
uint256 totalSupply;
uint256 remainingSupply;
uint256 maxQuantityPerPurchase;
address notificationsReceiver;
EnumMap.Map prices;
}
address public constant override TOKEN_ETH = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint256 public constant override SUPPLY_UNLIMITED = type(uint256).max;
EnumSet.Set internal _skus;
mapping(bytes32 => SkuInfo) internal _skuInfos;
uint256 internal immutable _skusCapacity;
uint256 internal immutable _tokensPerSkuCapacity;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal PayoutWallet(payoutWallet_) {
_skusCapacity = skusCapacity;
_tokensPerSkuCapacity = tokensPerSkuCapacity;
bytes32[] memory names = new bytes32[](2);
bytes32[] memory values = new bytes32[](2);
(names[0], values[0]) = ("TOKEN_ETH", bytes32(uint256(TOKEN_ETH)));
(names[1], values[1]) = ("SUPPLY_UNLIMITED", bytes32(uint256(SUPPLY_UNLIMITED)));
emit MagicValues(names, values);
_pause();
}
/* Public Admin Functions */
/**
* Actvates, or 'starts', the contract.
* @dev Emits the `Started` event.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has already been started.
* @dev Reverts if the contract is not paused.
*/
function start() public virtual onlyOwner {
_start();
_unpause();
}
/**
* Pauses the contract.
* @dev Emits the `Paused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is already paused.
*/
function pause() public virtual onlyOwner whenStarted {
_pause();
}
/**
* Resumes the contract.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is not paused.
*/
function unpause() public virtual onlyOwner whenStarted {
_unpause();
}
/**
* Sets the token prices for the specified product SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `tokens` and `prices` have different lengths.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @dev Emits the `SkuPricingUpdate` event.
* @param sku The identifier of the SKU.
* @param tokens The list of payment tokens to update.
* If empty, disable all the existing payment tokens.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function updateSkuPricing(
bytes32 sku,
address[] memory tokens,
uint256[] memory prices
) public virtual onlyOwner {
uint256 length = tokens.length;
// solhint-disable-next-line reason-string
require(length == prices.length, "Sale: tokens/prices lengths mismatch");
SkuInfo storage skuInfo = _skuInfos[sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
EnumMap.Map storage tokenPrices = skuInfo.prices;
if (length == 0) {
uint256 currentLength = tokenPrices.length();
for (uint256 i = 0; i < currentLength; ++i) {
// TODO add a clear function in EnumMap and EnumSet and use it
(bytes32 token, ) = tokenPrices.at(0);
tokenPrices.remove(token);
}
} else {
_setTokenPrices(tokenPrices, tokens, prices);
}
emit SkuPricingUpdate(sku, tokens, prices);
}
/* ISale Public Functions */
/**
* Performs a purchase.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable virtual override whenStarted whenNotPaused {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
_purchaseFor(purchase);
}
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view virtual override whenStarted whenNotPaused returns (uint256 totalPrice, bytes32[] memory pricingData) {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
return _estimatePurchase(purchase);
}
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
override
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
)
{
SkuInfo storage skuInfo = _skuInfos[sku];
uint256 length = skuInfo.prices.length();
totalSupply = skuInfo.totalSupply;
require(totalSupply != 0, "Sale: non-existent sku");
remainingSupply = skuInfo.remainingSupply;
maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase;
notificationsReceiver = skuInfo.notificationsReceiver;
tokens = new address[](length);
prices = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
(bytes32 token, bytes32 price) = skuInfo.prices.at(i);
tokens[i] = address(uint256(token));
prices[i] = uint256(price);
}
}
/**
* Returns the list of created SKU identifiers.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view override returns (bytes32[] memory skus) {
skus = _skus.values;
}
/* Internal Utility Functions */
/**
* Creates an SKU.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Emits the `SkuCreation` event.
* @param sku the SKU identifier.
* @param totalSupply the initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function _createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) internal virtual {
require(totalSupply != 0, "Sale: zero supply");
require(_skus.length() < _skusCapacity, "Sale: too many skus");
require(_skus.add(sku), "Sale: sku already created");
if (notificationsReceiver != address(0)) {
// solhint-disable-next-line reason-string
require(notificationsReceiver.isContract(), "Sale: receiver is not a contract");
}
SkuInfo storage skuInfo = _skuInfos[sku];
skuInfo.totalSupply = totalSupply;
skuInfo.remainingSupply = totalSupply;
skuInfo.maxQuantityPerPurchase = maxQuantityPerPurchase;
skuInfo.notificationsReceiver = notificationsReceiver;
emit SkuCreation(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
}
/**
* Updates SKU token prices.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @param tokenPrices Storage pointer to a mapping of SKU token prices to update.
* @param tokens The list of payment tokens to update.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function _setTokenPrices(
EnumMap.Map storage tokenPrices,
address[] memory tokens,
uint256[] memory prices
) internal virtual {
for (uint256 i = 0; i < tokens.length; ++i) {
address token = tokens[i];
require(token != address(0), "Sale: zero address token");
uint256 price = prices[i];
if (price == 0) {
tokenPrices.remove(bytes32(uint256(token)));
} else {
tokenPrices.set(bytes32(uint256(token)), bytes32(price));
}
}
require(tokenPrices.length() <= _tokensPerSkuCapacity, "Sale: too many tokens");
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @dev Reverts if `purchase.recipient` is the zero address.
* @dev Reverts if `purchase.token` is the zero address.
* @dev Reverts if `purchase.quantity` is zero.
* @dev Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`.
* @dev Reverts if `purchase.quantity` is greater than the available supply.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.sku` exists but does not have a price set for `purchase.token`.
* @dev If this function is overriden, the implementer SHOULD super call this before.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal view virtual override {
require(purchase.recipient != address(0), "Sale: zero address recipient");
require(purchase.token != address(0), "Sale: zero address token");
require(purchase.quantity != 0, "Sale: zero quantity purchase");
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
require(skuInfo.maxQuantityPerPurchase >= purchase.quantity, "Sale: above max quantity");
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply");
}
bytes32 priceKey = bytes32(uint256(purchase.token));
require(skuInfo.prices.contains(priceKey), "Sale: non-existent sku token");
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual override {
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
_skuInfos[purchase.sku].remainingSupply = skuInfo.remainingSupply.sub(purchase.quantity);
}
}
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @dev Reverts if `onPurchaseNotificationReceived` throws or returns an incorrect value.
* @dev Emits the `Purchase` event. The values of `purchaseData` are the concatenated values of `priceData`, `paymentData`
* and `deliveryData`. If not empty, the implementer MUST document how to interpret these values.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual override {
emit Purchase(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
abi.encodePacked(purchase.pricingData, purchase.paymentData, purchase.deliveryData)
);
address notificationsReceiver = _skuInfos[purchase.sku].notificationsReceiver;
if (notificationsReceiver != address(0)) {
// solhint-disable-next-line reason-string
require(
IPurchaseNotificationsReceiver(notificationsReceiver).onPurchaseNotificationReceived(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
purchase.pricingData,
purchase.paymentData,
purchase.deliveryData
) == IPurchaseNotificationsReceiver(address(0)).onPurchaseNotificationReceived.selector, // TODO precompute return value
"Sale: wrong receiver return value"
);
}
}
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title FixedPricesSale
* An Sale which implements a fixed prices strategy.
* The final implementer is responsible for implementing any additional pricing and/or delivery logic.
*/
contract FixedPricesSale is Sale {
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal Sale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {}
/* Internal Life Cycle Functions */
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.token` is not supported by the SKU.
* @dev Reverts in case of price overflow.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal view virtual override {
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: unsupported SKU");
EnumMap.Map storage prices = skuInfo.prices;
uint256 unitPrice = _unitPrice(purchase, prices);
purchase.totalPrice = unitPrice.mul(purchase.quantity);
}
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @dev Reverts in case of payment failure.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual override {
if (purchase.token == TOKEN_ETH) {
require(msg.value >= purchase.totalPrice, "Sale: insufficient ETH provided");
payoutWallet.transfer(purchase.totalPrice);
uint256 change = msg.value.sub(purchase.totalPrice);
if (change != 0) {
purchase.purchaser.transfer(change);
}
} else {
require(IERC20(purchase.token).transferFrom(_msgSender(), payoutWallet, purchase.totalPrice), "Sale: ERC20 payment failed");
}
}
/* Internal Utility Functions */
/**
* Retrieves the unit price of a SKU for the specified payment token.
* @dev Reverts if the specified payment token is unsupported.
* @param purchase The purchase conditions specifying the payment token with which the unit price will be retrieved.
* @param prices Storage pointer to a mapping of SKU token prices to retrieve the unit price from.
* @return unitPrice The unit price of a SKU for the specified payment token.
*/
function _unitPrice(PurchaseData memory purchase, EnumMap.Map storage prices) internal view virtual returns (uint256 unitPrice) {
unitPrice = uint256(prices.get(bytes32(uint256(purchase.token))));
require(unitPrice != 0, "Sale: unsupported payment token");
}
}
// File contracts/solc-0.6/sale/GAMEEVoucherSale.sol
pragma solidity 0.6.8;
/**
* @title GAMEEVoucherSale
* A FixedPricesSale contract implementation that handles the purchase of pre-minted GAMEE token
* (GMEE) voucher fungible tokens from a holder account to the purchase recipient.
*/
contract GAMEEVoucherSale is FixedPricesSale {
IGAMEEVoucherInventoryTransferable public immutable inventory;
address public immutable tokenHolder;
mapping(bytes32 => uint256) public skuTokenIds;
/**
* Constructor.
* @dev Reverts if `inventory_` is the zero address.
* @dev Reverts if `tokenHolder_` is the zero address.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param inventory_ The inventory contract from which the sale supply is attributed from.
* @param tokenHolder_ The account holding the pool of sale supply tokens.
* @param payoutWallet the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address inventory_,
address tokenHolder_,
address payoutWallet,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) public FixedPricesSale(payoutWallet, skusCapacity, tokensPerSkuCapacity) {
// solhint-disable-next-line reason-string
require(inventory_ != address(0), "GAMEEVoucherSale: zero address inventory");
// solhint-disable-next-line reason-string
require(tokenHolder_ != address(0), "GAMEEVoucherSale: zero address token holder");
inventory = IGAMEEVoucherInventoryTransferable(inventory_);
tokenHolder = tokenHolder_;
}
/**
* Creates an SKU.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Reverts if `tokenId` is zero.
* @dev Emits the `SkuCreation` event.
* @param sku The SKU identifier.
* @param totalSupply The initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
* @param tokenId The inventory contract token ID to associate with the SKU, used for purchase
* delivery.
*/
function createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
uint256 tokenId
) external onlyOwner whenPaused {
require(tokenId != 0, "GAMEEVoucherSale: zero token ID");
_createSku(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
skuTokenIds[sku] = tokenId;
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal override {
super._delivery(purchase);
inventory.safeTransferFrom(tokenHolder, purchase.recipient, skuTokenIds[purchase.sku], purchase.quantity, "");
}
}
/**
* @dev Interface for the transfer function of the GAMEE voucher inventory contract.
*/
interface IGAMEEVoucherInventoryTransferable {
/**
* Safely transfers some token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `from` has an insufficient balance.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155received} fails or is refused.
* @dev Emits a `TransferSingle` event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param id Identifier of the token to transfer.
* @param value Amount of token to transfer.
* @param data Optional data to send along to a receiver contract.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
) external;
} | Returns the information relative to a SKU. WARNING: it is the responsibility of the implementer to ensure that the number of payment tokens is bounded, so that this function does not run out of gas. Reverts if `sku` does not exist. sku The SKU identifier. return totalSupply The initial total supply for sale. return remainingSupply The remaining supply for sale. return maxQuantityPerPurchase The maximum allowed quantity for a single purchase. return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function. return tokens The list of supported payment tokens. return prices The list of associated prices for each of the `tokens`./ | function getSkuInfo(bytes32 sku)
external
view
override
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
)
{
SkuInfo storage skuInfo = _skuInfos[sku];
uint256 length = skuInfo.prices.length();
totalSupply = skuInfo.totalSupply;
require(totalSupply != 0, "Sale: non-existent sku");
remainingSupply = skuInfo.remainingSupply;
maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase;
notificationsReceiver = skuInfo.notificationsReceiver;
tokens = new address[](length);
prices = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
(bytes32 token, bytes32 price) = skuInfo.prices.at(i);
tokens[i] = address(uint256(token));
prices[i] = uint256(price);
}
}
| 2,027,240 |
./partial_match/1/0x6da28Db16ecB33C2468FF934CD3A3447c588309A/sources/contracts/HegicOptionsNFT.sol | Exercises underlying option _tokenId ID of the token that holds the option to be exercised/ contract pays token owner, even if called by an approved account | function exerciseOption(uint _tokenId) external onlyTokenOwnerOrApproved(_tokenId) returns (uint profit){
optionsProvider.exercise(underlyingOptionId[_tokenId]);
profit = _transferBalance(ownerOf(_tokenId));
emit Exercised(msg.sender, _tokenId, profit);
}
| 2,726,544 |
pragma solidity ^0.4.21;
// ----------------------------------------------------------------------------
// (c) BokkyPooBah / Bok Consulting Pty Ltd 2017. The MIT Licence.
// modified by Team Chibi Fighters, thanks heaps BokkyPooBah!
//
// massive shoutout to https://cryptozombies.io
// best solidity learning series out there!
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Contract owner and transfer functions
// just in case someone wants to get my bacon
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 compliant Founder Chibi Token
// Receives ETH and generates Founder Chibi Token
// 1 Founder Chibi Fighter can be exchanged for 1 Founder Chibi in our upcoming game
// https://chibifighters.io Chibi Fighters
// ----------------------------------------------------------------------------
contract Founders is ERC20Interface, Owned {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public _ratio;
bool disabled;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Launched once when contract starts
// ------------------------------------------------------------------------
function Founders() public {
disabled = false;
symbol = "FCF";
name = "Founder Chibi Fighters";
decimals = 18;
// the first coins go to creator to share among GARRY investors
_totalSupply = 330 * 10**uint(decimals);
// set ratio, get 100 Founders for 1 Ether
_ratio = 100;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
require(balances[msg.sender] >= tokens);
balances[msg.sender] -= tokens;
balances[to] += tokens;
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require (allowed[from][msg.sender] >= tokens);
require (balances[from] >= tokens);
balances[from] -= tokens;
allowed[from][msg.sender] -= tokens;
balances[to] += tokens;
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Disable minting of Founder Chibis after Release
// ------------------------------------------------------------------------
function disableContract(bool _disabled) public onlyOwner returns (bool success) {
disabled = _disabled;
return true;
}
// ------------------------------------------------------------------------
// Tokens per Ethererum at a ratio of 100:1
// 0.01 is minimum to avoid spamming
// ------------------------------------------------------------------------
function () public payable {
require(msg.value >= 10000000000000000);
require(disabled == false);
uint tokens;
tokens = msg.value*_ratio;
balances[msg.sender] += tokens;
_totalSupply += tokens;
emit Transfer(address(0), msg.sender, tokens);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// Only if he is in the mood though, I won't give a damn if you are an annoying bot
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Query Ethereum of contract
// ------------------------------------------------------------------------
function weiBalance() public constant returns (uint weiBal) {
return address(this).balance;
}
// ------------------------------------------------------------------------
// Send Contracts Ethereum to address owner
// ------------------------------------------------------------------------
function weiToOwner(address _address, uint amount) public onlyOwner {
require(amount <= address(this).balance);
_address.transfer(amount);
}
} | the first coins go to creator to share among GARRY investors set ratio, get 100 Founders for 1 Ether | function Founders() public {
disabled = false;
symbol = "FCF";
name = "Founder Chibi Fighters";
decimals = 18;
_totalSupply = 330 * 10**uint(decimals);
_ratio = 100;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
| 7,001,051 |
./full_match/1/0xe7d20aEd148751365729c35019eF8813Caa7dAf5/sources/contracts/tokenCutters/ProofNonReflectionTokenCutter.sol | This token was created with PROOF, and audited by Solidity Finance — https:proofplatform.io/projects | {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
address constant DEAD = 0x000000000000000000000000000000000000dEaD;
address constant ZERO = 0x0000000000000000000000000000000000000000;
address payable public proofBurnerAddress;
address public proofAdmin;
uint256 public whitelistEndTime;
uint256 public whitelistPeriod;
bool public restrictWhales = true;
mapping(address => bool) public userWhitelist;
address[] public nftWhitelist;
bool public whitelistMode = true;
mapping(address => bool) public isFeeExempt;
mapping(address => bool) public isTxLimitExempt;
mapping(address => bool) public isDividendExempt;
uint256 public launchedAt;
uint256 public proofFee = 2;
uint256 public mainFee;
uint256 public lpFee;
uint256 public devFee;
uint256 public mainFeeOnSell;
uint256 public lpFeeOnSell;
uint256 public devFeeOnSell;
uint256 public totalFee;
uint256 public totalFeeIfSelling;
IUniswapV2Router02 public router;
address public pair;
address public factory;
address public tokenOwner;
address payable public devWallet;
address payable public mainWallet;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
bool public tradingStatus = true;
uint256 public _maxTxAmount;
uint256 public _walletMax;
uint256 public swapThreshold;
pragma solidity ^0.8.17;
constructor() {
factory = msg.sender;
}
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
modifier onlyProofAdmin() {
require(
proofAdmin == _msgSender(),
"Ownable: caller is not the proofAdmin"
);
_;
}
modifier onlyOwner() {
require(tokenOwner == _msgSender(), "Ownable: caller is not the owner");
_;
}
modifier onlyFactory() {
require(factory == _msgSender(), "Ownable: caller is not the factory");
_;
}
function setBasicData(
BaseData memory _baseData,
ProofNonReflectionTokenFees.allFees memory fees
) external onlyFactory {
_name = _baseData.tokenName;
_symbol = _baseData.tokenSymbol;
_totalSupply = _baseData.initialSupply;
require(_baseData.percentToLP >= 70, "Too low");
_maxTxAmount = (_baseData.initialSupply * 5) / 1000;
_walletMax = (_baseData.initialSupply * 1) / 100;
swapThreshold = (_baseData.initialSupply * 5) / 4000;
router = IUniswapV2Router02(_baseData.routerAddress);
pair = IUniswapV2Factory(router.factory()).createPair(
router.WETH(),
address(this)
);
_allowances[address(this)][address(router)] = type(uint256).max;
userWhitelist[address(this)] = true;
userWhitelist[factory] = true;
userWhitelist[pair] = true;
userWhitelist[_baseData.owner] = true;
userWhitelist[_baseData.initialProofAdmin] = true;
userWhitelist[_baseData.routerAddress] = true;
_addWhitelist(_baseData.whitelists);
nftWhitelist = _baseData.nftWhitelist;
isFeeExempt[address(this)] = true;
isFeeExempt[factory] = true;
isFeeExempt[_baseData.owner] = true;
isTxLimitExempt[_baseData.owner] = true;
isTxLimitExempt[pair] = true;
isTxLimitExempt[factory] = true;
isTxLimitExempt[DEAD] = true;
isTxLimitExempt[ZERO] = true;
whitelistPeriod = _baseData.whitelistPeriod;
lpFee = fees.lpFee;
lpFeeOnSell = fees.lpFeeOnSell;
devFee = fees.devFee;
devFeeOnSell = fees.devFeeOnSell;
mainFee = fees.mainFee;
mainFeeOnSell = fees.mainFeeOnSell;
totalFee = devFee + lpFee + mainFee + proofFee;
totalFeeIfSelling =
devFeeOnSell +
lpFeeOnSell +
mainFeeOnSell +
proofFee;
require(totalFee <= 12, "Too high fee");
require(totalFeeIfSelling <= 17, "Too high sell fee");
tokenOwner = _baseData.owner;
devWallet = payable(_baseData.dev);
mainWallet = payable(_baseData.main);
proofAdmin = _baseData.initialProofAdmin;
_balances[msg.sender] += forLP;
_balances[_baseData.owner] += forOwner;
emit Transfer(address(0), msg.sender, forLP);
emit Transfer(address(0), _baseData.owner, forOwner);
}
function updateWhitelistPeriod(
uint256 _whitelistPeriod
) external onlyProofAdmin {
whitelistPeriod = _whitelistPeriod;
whitelistEndTime = launchedAt + (60 * _whitelistPeriod);
whitelistMode = true;
}
function updateProofAdmin(
address newAdmin
) external virtual onlyProofAdmin {
proofAdmin = newAdmin;
userWhitelist[newAdmin] = true;
}
function updateProofBurnerAddress(
address newproofBurnerAddress
) external onlyProofAdmin {
proofBurnerAddress = payable(newproofBurnerAddress);
}
function swapTradingStatus() external onlyFactory {
tradingStatus = !tradingStatus;
}
function setLaunchedAt() external onlyFactory {
require(launchedAt == 0, "already launched");
launchedAt = block.timestamp;
whitelistEndTime = block.timestamp + (60 * whitelistPeriod);
whitelistMode = true;
}
function cancelToken() external onlyFactory {
isFeeExempt[address(router)] = true;
isTxLimitExempt[address(router)] = true;
isTxLimitExempt[tokenOwner] = true;
tradingStatus = true;
restrictWhales = false;
swapAndLiquifyEnabled = false;
}
function changeFees(
uint256 initialMainFee,
uint256 initialMainFeeOnSell,
uint256 initialLpFee,
uint256 initialLpFeeOnSell,
uint256 initialDevFee,
uint256 initialDevFeeOnSell
) external onlyOwner {
mainFee = initialMainFee;
lpFee = initialLpFee;
devFee = initialDevFee;
mainFeeOnSell = initialMainFeeOnSell;
lpFeeOnSell = initialLpFeeOnSell;
devFeeOnSell = initialDevFeeOnSell;
totalFee = devFee + lpFee + proofFee + mainFee;
totalFeeIfSelling =
devFeeOnSell +
lpFeeOnSell +
proofFee +
mainFeeOnSell;
require(totalFee <= 12, "Too high fee");
require(totalFeeIfSelling <= 17, "Too high fee");
}
function changeTxLimit(uint256 newLimit) external onlyOwner {
require(launchedAt != 0, "!launched");
require(newLimit >= (_totalSupply * 5) / 1000, "Min 0.5%");
require(newLimit <= (_totalSupply * 3) / 100, "Max 3%");
_maxTxAmount = newLimit;
}
function changeWalletLimit(uint256 newLimit) external onlyOwner {
require(launchedAt != 0, "!launched");
require(newLimit >= (_totalSupply * 5) / 1000, "Min 0.5%");
require(newLimit <= (_totalSupply * 3) / 100, "Max 3%");
_walletMax = newLimit;
}
function changeRestrictWhales(bool newValue) external onlyOwner {
require(launchedAt != 0, "!launched");
restrictWhales = newValue;
}
function changeIsFeeExempt(address holder, bool exempt) external onlyOwner {
isFeeExempt[holder] = exempt;
}
function changeIsTxLimitExempt(
address holder,
bool exempt
) external onlyOwner {
isTxLimitExempt[holder] = exempt;
}
function reduceProofFee() external onlyOwner {
require(proofFee == 2, "!already reduced");
require(launchedAt != 0, "!launched");
require(block.timestamp >= launchedAt + 72 hours, "too soon");
proofFee = 1;
totalFee = devFee + lpFee + proofFee + mainFee;
totalFeeIfSelling =
devFeeOnSell +
lpFeeOnSell +
proofFee +
mainFeeOnSell;
}
function adjustProofFee(uint256 _proofFee) external onlyProofAdmin {
require(launchedAt != 0, "!launched");
if (block.timestamp >= launchedAt + 72 hours) {
require(_proofFee <= 1);
proofFee = _proofFee;
totalFee = devFee + lpFee + proofFee + mainFee;
totalFeeIfSelling =
devFeeOnSell +
lpFeeOnSell +
proofFee +
mainFeeOnSell;
require(_proofFee <= 2);
proofFee = _proofFee;
totalFee = devFee + lpFee + proofFee + mainFee;
totalFeeIfSelling =
devFeeOnSell +
lpFeeOnSell +
proofFee +
mainFeeOnSell;
}
}
function adjustProofFee(uint256 _proofFee) external onlyProofAdmin {
require(launchedAt != 0, "!launched");
if (block.timestamp >= launchedAt + 72 hours) {
require(_proofFee <= 1);
proofFee = _proofFee;
totalFee = devFee + lpFee + proofFee + mainFee;
totalFeeIfSelling =
devFeeOnSell +
lpFeeOnSell +
proofFee +
mainFeeOnSell;
require(_proofFee <= 2);
proofFee = _proofFee;
totalFee = devFee + lpFee + proofFee + mainFee;
totalFeeIfSelling =
devFeeOnSell +
lpFeeOnSell +
proofFee +
mainFeeOnSell;
}
}
} else {
function setDevWallet(address payable newDevWallet) external onlyOwner {
devWallet = payable(newDevWallet);
}
function setMainWallet(address payable newMainWallet) external onlyOwner {
mainWallet = newMainWallet;
}
function setOwnerWallet(address payable newOwnerWallet) external onlyOwner {
tokenOwner = newOwnerWallet;
}
function changeSwapBackSettings(
bool enableSwapBack,
uint256 newSwapBackLimit
) external onlyOwner {
swapAndLiquifyEnabled = enableSwapBack;
swapThreshold = newSwapBackLimit;
}
function isWhitelisted(address user) public view returns (bool) {
return userWhitelist[user];
}
function holdsSupportedNFT(address user) public view returns (bool) {
for (uint256 i = 0; i < nftWhitelist.length; i++) {
if (IERC721(nftWhitelist[i]).balanceOf(user) > 0) {
return true;
}
}
return false;
}
function holdsSupportedNFT(address user) public view returns (bool) {
for (uint256 i = 0; i < nftWhitelist.length; i++) {
if (IERC721(nftWhitelist[i]).balanceOf(user) > 0) {
return true;
}
}
return false;
}
function holdsSupportedNFT(address user) public view returns (bool) {
for (uint256 i = 0; i < nftWhitelist.length; i++) {
if (IERC721(nftWhitelist[i]).balanceOf(user) > 0) {
return true;
}
}
return false;
}
function getCirculatingSupply() external view returns (uint256) {
return _totalSupply - balanceOf(DEAD) - balanceOf(ZERO);
}
function name() external view virtual override returns (string memory) {
return _name;
}
function symbol() external view virtual override returns (string memory) {
return _symbol;
}
function decimals() external view virtual override returns (uint8) {
return 9;
}
function totalSupply() external view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(
address account
) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(
address to,
uint256 amount
) external virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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
) external virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) external virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
) external virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
) external virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
) external virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal returns (bool) {
require(tradingStatus, "Trading Closed");
if(whitelistMode) {
if (block.timestamp >= whitelistEndTime ) {
whitelistMode = false;
require(isWhitelisted(recipient) || holdsSupportedNFT(recipient), "Not whitelisted");
require(isWhitelisted(sender) || holdsSupportedNFT(sender), "Not whitelisted");
require((isWhitelisted(sender) || holdsSupportedNFT(sender)) && (isWhitelisted(recipient) || holdsSupportedNFT(recipient)), "Not Whitelisted");
}
}
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal returns (bool) {
require(tradingStatus, "Trading Closed");
if(whitelistMode) {
if (block.timestamp >= whitelistEndTime ) {
whitelistMode = false;
require(isWhitelisted(recipient) || holdsSupportedNFT(recipient), "Not whitelisted");
require(isWhitelisted(sender) || holdsSupportedNFT(sender), "Not whitelisted");
require((isWhitelisted(sender) || holdsSupportedNFT(sender)) && (isWhitelisted(recipient) || holdsSupportedNFT(recipient)), "Not Whitelisted");
}
}
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal returns (bool) {
require(tradingStatus, "Trading Closed");
if(whitelistMode) {
if (block.timestamp >= whitelistEndTime ) {
whitelistMode = false;
require(isWhitelisted(recipient) || holdsSupportedNFT(recipient), "Not whitelisted");
require(isWhitelisted(sender) || holdsSupportedNFT(sender), "Not whitelisted");
require((isWhitelisted(sender) || holdsSupportedNFT(sender)) && (isWhitelisted(recipient) || holdsSupportedNFT(recipient)), "Not Whitelisted");
}
}
}
} else {
if (inSwapAndLiquify) {
return _basicTransfer(sender, recipient, amount);
}
if (recipient == pair && restrictWhales) {
require(
amount <= _maxTxAmount ||
(isTxLimitExempt[sender] && isTxLimitExempt[recipient]),
"Max TX"
);
}
if (!isTxLimitExempt[recipient] && restrictWhales) {
require(_balances[recipient] + amount <= _walletMax, "Max Wallet");
}
if (
sender != pair &&
!inSwapAndLiquify &&
swapAndLiquifyEnabled &&
_balances[address(this)] >= swapThreshold
) {
swapBack();
}
_balances[sender] = _balances[sender] - amount;
uint256 finalAmount = amount;
if (sender == pair || recipient == pair) {
finalAmount = !isFeeExempt[sender] && !isFeeExempt[recipient]
? takeFee(sender, recipient, amount)
: amount;
}
_balances[recipient] = _balances[recipient] + finalAmount;
emit Transfer(sender, recipient, finalAmount);
return true;
}
| 9,709,295 |
pragma solidity 0.5.4;
//import {Ownable} from "./ownable.sol";
import "./accessible.sol";
import "./access_indexor.sol";
import "./user_space.sol";
/* -- Revision history --
Editable20190222140100ML: First versioned released
Editable20190315141800ML: Migrated to 0.4.24
Editable20190515103600ML: Modified rights restriction on update to match the one on commit
Editable20190522154000SS: Changed hash bytes32 to string
Editable20190605144500ML: Renamed publish to confirm to avoid confusion in the case of the content-objects
Editable20190715105600PO
Editable20190801135500ML: Made explicit the definition of parentAddress method
Editable20191219134600ML: Made updateRequest contingent on canEdit rather than ownership
Editable20200109145900ML: Limited updateRequest to canEdit
Editable20200124080600ML: Fixed deletion of latest version
Editable20200210163900ML: Modified for authV3 support
Editable20200316135400ML: Implements check and set rights to be inherited from
Editable20200410215400ML: disambiguate indexor.setRights and entity.setRights
Editable20200422180400ML: Fixed deletion of latest version
Editable20200626180400PO: Authv3 changes
Editable20200928110000PO: Replace tx.origin with msg.sender in some cases
*/
contract Editable is Accessible {
bytes32 public version ="Editable20200928110000PO"; //class name (max 16), date YYYYMMDD, time HHMMSS and Developer initials XX
event CommitPending(address spaceAddress, address parentAddress, string objectHash);
event UpdateRequest(string objectHash);
event VersionConfirm(address spaceAddress, address parentAddress, string objectHash);
event VersionDelete(address spaceAddress, string versionHash, int256 index);
string public objectHash;
// made public on 1/25/2020 - not generally safe to assume it's available on all deployed contracts
uint public objectTimestamp;
string[] public versionHashes;
uint[] public versionTimestamp;
string public pendingHash;
bool public commitPending;
modifier onlyEditor() {
require(canEdit());
_;
}
function countVersionHashes() public view returns (uint256) {
return versionHashes.length;
}
// This function is meant to be overloaded. By default the owner is the only editor
function canEdit() public view returns (bool) {
return hasEditorRight(msg.sender);
}
function hasEditorRight(address candidate) public view returns (bool) {
if ((candidate == owner) || (visibility >= 100)) {
return true;
}
if (indexCategory > 0) {
address payable walletAddress = address(uint160(IUserSpace(contentSpace).userWallets(candidate)));
return AccessIndexor(walletAddress).checkRights(indexCategory, address(this), 2 /* TYPE_EDIT */ );
} else {
return false;
}
}
// intended to be overridden
function canConfirm() public view returns (bool) {
return false;
}
function canCommit() public view returns (bool) {
return (msg.sender == owner);
}
// overridden in BaseContent to return library
function parentAddress() public view returns (address) {
return contentSpace;
}
function clearPending() public {
require(canCommit());
pendingHash = "";
commitPending = false;
}
function commit(string memory _objectHash) public {
require(canCommit());
require(!commitPending); // don't allow two possibly different commits to step on each other - one always wins
require(bytes(_objectHash).length < 128);
pendingHash = _objectHash;
commitPending = true;
emit CommitPending(contentSpace, parentAddress(), pendingHash);
}
function confirmCommit() public payable returns (bool) {
require(canConfirm());
require(commitPending);
if (bytes(objectHash).length > 0) {
versionHashes.push(objectHash); // save existing version info
versionTimestamp.push(objectTimestamp);
}
objectHash = pendingHash;
objectTimestamp = block.timestamp;
pendingHash = "";
commitPending = false;
emit VersionConfirm(contentSpace, parentAddress(), objectHash);
return true;
}
function updateRequest() public {
require(canEdit());
emit UpdateRequest(objectHash);
}
function removeVersionIdx(uint idx) internal {
delete versionHashes[idx];
delete versionTimestamp[idx];
if (idx != (versionHashes.length - 1)) {
versionHashes[idx] = versionHashes[versionHashes.length - 1];
versionTimestamp[idx] = versionTimestamp[versionTimestamp.length - 1];
}
versionHashes.length--;
versionTimestamp.length--;
return;
}
function deleteVersion(string memory _versionHash) public returns (int256) {
require(canCommit());
bytes32 findHash = keccak256(abi.encodePacked(_versionHash));
bytes32 objHash = keccak256(abi.encodePacked(objectHash));
if (findHash == objHash) {
if (versionHashes.length == 0) {
objectHash = "";
objectTimestamp = 0;
} else {
//find the most recent
uint256 mostRecent = 0;
uint latestStamp = 0;
for (uint256 x = 0; x < versionHashes.length; x++) {
if (versionTimestamp[x] > latestStamp) {
mostRecent = x;
latestStamp = versionTimestamp[x];
}
}
//assign most recent version as object version and delete from versions array
objectHash = versionHashes[mostRecent];
objectTimestamp = latestStamp;
removeVersionIdx(mostRecent);
}
emit VersionDelete(contentSpace, _versionHash, 0);
return 0;
}
int256 foundIdx = -1;
for (uint256 i = 0; i < versionHashes.length; i++) {
bytes32 checkHash = keccak256(abi.encodePacked(versionHashes[i]));
if (findHash == checkHash) {
removeVersionIdx(i);
foundIdx = int256(i);
break;
}
}
require(foundIdx != -1);
emit VersionDelete(contentSpace, _versionHash, foundIdx);
return foundIdx;
}
function setRights(address payable stakeholder, uint8 access_type, uint8 access) public onlyEditor {
IUserSpace userSpaceObj = IUserSpace(contentSpace);
address payable walletAddress = address(uint160(userSpaceObj.userWallets(stakeholder)));
if (walletAddress == address(0x0)){
//stakeholder is not a user (hence group or wallet)
setGroupRights(stakeholder, access_type, access);
} else {
setGroupRights(walletAddress, access_type, access);
}
}
function setGroupRights(address payable group, uint8 access_type, uint8 access) public {
AccessIndexor indexor = AccessIndexor(group);
if (indexCategory == indexor.CATEGORY_CONTENT_OBJECT()) {
indexor.setContentObjectRights(address(this), access_type, access) ;
} else if (indexCategory == indexor.CATEGORY_GROUP()) {
indexor.setAccessGroupRights(address(this), access_type, access);
} else if (indexCategory == indexor.CATEGORY_LIBRARY()) {
indexor.setLibraryRights(address(this), access_type, access);
} else if (indexCategory == indexor.CATEGORY_CONTENT_TYPE()) {
indexor.setContentTypeRights(address(this), access_type, access);
} else if (indexCategory == indexor.CATEGORY_CONTRACT()) {
indexor.setContractRights(address(this), access_type, access);
} else {
revert();
}
}
function setVisibility(uint8 _visibility_code) public onlyEditor {
visibility = _visibility_code;
emit VisibilityChanged(contentSpace, contentSpace, visibility);
}
}
| stakeholder is not a user (hence group or wallet) | function setRights(address payable stakeholder, uint8 access_type, uint8 access) public onlyEditor {
IUserSpace userSpaceObj = IUserSpace(contentSpace);
address payable walletAddress = address(uint160(userSpaceObj.userWallets(stakeholder)));
if (walletAddress == address(0x0)){
setGroupRights(stakeholder, access_type, access);
setGroupRights(walletAddress, access_type, access);
}
}
| 5,401,443 |
./full_match/137/0x543a000a9FBE139ff783b2F8EbdF8869452Dc21D/sources/sol-defifactory-token/NoBotsTechV3.sol | taxAmountsOutput.burnAndRewardAmount = 0; Actual amount we burned and have to show in event | function prepareTaxAmounts(
TaxAmountsInput calldata taxAmountsInput
)
external
onlyRole(ROLE_ADMIN)
returns(TaxAmountsOutput memory taxAmountsOutput)
{
require(
taxAmountsInput.transferAmount > 0,
"NBT: !amount"
);
ICerbyBotDetection iCerbyBotDetection = ICerbyBotDetection(
ICerbyToken(cerbyTokenAddress).getUtilsContractAtPos(CERBY_BOT_DETECTION_CONTRACT_ID)
);
iCerbyBotDetection.checkTransactionInfo(
cerbyTokenAddress,
taxAmountsInput.sender,
taxAmountsInput.recipient,
taxAmountsOutput.recipientRealBalance,
taxAmountsInput.transferAmount
);
taxAmountsOutput.senderRealBalance = taxAmountsInput.senderRealBalance - taxAmountsInput.transferAmount;
taxAmountsOutput.recipientRealBalance = taxAmountsInput.recipientRealBalance + taxAmountsInput.transferAmount;
return taxAmountsOutput;
}
| 3,747,918 |
./partial_match/4/0xc397bCDCf6814534F08443DdAfef1D0731635dc5/sources/ERC20Vanilla.sol | check if an account can pay the fee in WPST | function canBuyTea(address account, uint256 in_wei) public view returns (bool) {
if (token.allowance(account, address(this)) >= in_wei) {
return true;
return false;
}
}
| 8,789,114 |
./full_match/421613/0x16dc09965582F69Ca6669eDD8A5dE2052209eBE3/sources/src/facets/TokenFacet.sol | 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: Emits an {Approval} event./ | function approve(address spender, uint256 amount) external returns (bool) {
address owner = msg.sender;
TokenLib.approve(owner, spender, amount);
return true;
}
| 11,582,172 |
pragma solidity ^0.4.24;
contract PoHEVENTS {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PoCAmount,
uint256 genAmount,
uint256 potAmount
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PoCAmount,
uint256 genAmount
);
// fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PoCAmount,
uint256 genAmount
);
// fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PoCAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract POHMO is PoHEVENTS {
using SafeMath for *;
using NameFilter for string;
using KeysCalc for uint256;
PlayerBookInterface private PlayerBook;
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
address private admin = msg.sender;
address private _POHWHALE;
string constant public name = "POHMO";
string constant public symbol = "POHMO";
uint256 private rndExtra_ = 1 seconds; // length of the very first ICO
uint256 private rndGap_ = 1 seconds; // length of ICO phase, set to 1 year for EOS.
uint256 private rndInit_ = 6 hours; // round timer starts at this
uint256 constant private rndInc_ = 10 seconds; // every full key purchased adds this much to the timer
uint256 private rndMax_ = 6 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => POHMODATASETS.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => POHMODATASETS.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => POHMODATASETS.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => POHMODATASETS.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => POHMODATASETS.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor(address whaleContract, address playerbook)
public
{
_POHWHALE = whaleContract;
PlayerBook = PlayerBookInterface(playerbook);
//no teams... only POOH-heads
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = POHMODATASETS.TeamFee(47,12); //30% to pot, 10% to aff, 1% to dev,
potSplit_[0] = POHMODATASETS.PotSplit(15,10); //48% to winner, 25% to next round, 2% to dev
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true);
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0);
require(_addr == tx.origin);
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000);
require(_eth <= 100000000000000000000000);
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
POHMODATASETS.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
*/
function buyXid(uint256 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
POHMODATASETS.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// buy core
buyCore(_pID, _affCode, _eventData_);
}
function buyXaddr(address _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
POHMODATASETS.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// buy core
buyCore(_pID, _affID, _eventData_);
}
function buyXname(bytes32 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
POHMODATASETS.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// buy core
buyCore(_pID, _affID, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
POHMODATASETS.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// reload core
reLoadCore(_pID, _affCode, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
POHMODATASETS.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// reload core
reLoadCore(_pID, _affID, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
POHMODATASETS.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// reload core
reLoadCore(_pID, _affID, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
POHMODATASETS.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit PoHEVENTS.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PoCAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit PoHEVENTS.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit PoHEVENTS.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit PoHEVENTS.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit PoHEVENTS.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3] //12
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, POHMODATASETS.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, 0, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit PoHEVENTS.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PoCAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, POHMODATASETS.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, 0, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit PoHEVENTS.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PoCAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, POHMODATASETS.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 5000000000000000000)
{
uint256 _availableLimit = (5000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][0] = _eth.add(rndTmEth_[_rID][0]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, 0, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, 0, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, 0, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook));
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook));
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(POHMODATASETS.EventReturns memory _eventData_)
private
returns (POHMODATASETS.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, POHMODATASETS.EventReturns memory _eventData_)
private
returns (POHMODATASETS.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(POHMODATASETS.EventReturns memory _eventData_)
private
returns (POHMODATASETS.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100; //48%
uint256 _dev = (_pot / 50); //2%
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; //15
uint256 _PoC = (_pot.mul(potSplit_[_winTID].pooh)) / 100; // 10
uint256 _res = (((_pot.sub(_win)).sub(_dev)).sub(_gen)).sub(_PoC); //25
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
admin.transfer(_dev);
_POHWHALE.call.value(_PoC)(bytes4(keccak256("donate()")));
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.PoCAmount = _PoC;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndMax_);
round_[_rID].pot = _res;
return(_eventData_);
}
function determineNextRoundLength() internal view returns(uint256 time)
{
uint256 roundTime = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1)))) % 6;
return roundTime;
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev distributes eth based on fees to com, aff, and pooh
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, POHMODATASETS.EventReturns memory _eventData_)
private
returns(POHMODATASETS.EventReturns)
{
// pay 1% out to dev
uint256 _dev = _eth / 100; // 1%
uint256 _PoC = 0;
if (!address(admin).call.value(_dev)())
{
_PoC = _dev;
_dev = 0;
}
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit PoHEVENTS.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_PoC = _PoC.add(_aff);
}
// pay out POOH
_PoC = _PoC.add((_eth.mul(fees_[_team].pooh)) / (100));
if (_PoC > 0)
{
// deposit to divies contract
_POHWHALE.call.value(_PoC)(bytes4(keccak256("donate()")));
// set up event data
_eventData_.PoCAmount = _PoC.add(_eventData_.PoCAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
//you shouldn't be using this method
admin.transfer(msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, POHMODATASETS.EventReturns memory _eventData_)
private
returns(POHMODATASETS.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].pooh)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, POHMODATASETS.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit PoHEVENTS.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PoCAmount,
_eventData_.genAmount,
_eventData_.potAmount
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(msg.sender == admin);
// can only be ran once
require(activated_ == false);
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library POHMODATASETS {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 PoCAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 pooh; // % of buy in thats paid to POOH holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 pooh; // % of pot thats paid to POOH holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library KeysCalc {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0);
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20);
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78);
require(_temp[1] != 0x58);
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a));
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20);
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true);
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @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)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | ============================================================================== _ _ _ _ | _ _ . _ . (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)=====================_|======================================================= logic runs whenever a buy order is executed. determines how to handle incoming eth depending on if we are in an active round or not/ setup local rID grab time if round is active call core if round is not active check to see if end round needs to be ran end the round (distributes pot) & start new round build event data fire buy and distribute event | function buyCore(uint256 _pID, uint256 _affID, POHMODATASETS.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, 0, _eventData_);
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit PoHEVENTS.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PoCAmount,
_eventData_.genAmount
);
}
}
}
| 13,715,725 |
./partial_match/1/0x7e789E2dd1340971De0A9bca35b14AC0939Aa330/sources/Cryptostamp.sol | Internal function to burn a specific token Reverts if the token does not exist Deprecated, use _burn(uint256) instead param owner owner of the token to burn param tokenId uint256 ID of the token being burned/ | function _burn(address /*owner*/, uint256 /*tokenId*/) internal {
revert("This token cannot be burned.");
}
| 15,721,360 |
pragma solidity ^0.4.11;
// 請使用solc 0.4.20編譯,否則會有問題
contract Owned {
address owner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner() {
if(msg.sender!=owner) throw; _;
}
}
// 存放清算銀行客戶的款戶,以便於使用清算銀行及客戶帳號為key來查詢
// 注意Owner為TransactionMatcher contract
contract Bank_CashAccount is Owned {
bytes32 bank_id;
uint customers_cnt;
bool private isOwnedNode = false; // 使用private transaction來設定flag,
// 每個Bank_Account Contract只有在自己跟央行才會設flag
// 以便判斷是在那個節點上跑
struct customer {
bytes32 [] ids;
mapping(bytes32 => cash_account) cash_accounts; // 以id為index
mapping(bytes32 => bool) hasCustomer;
}
struct cash_account {
mapping(bytes32 => int) total_amounts; // 總數量 以債券代號為index
mapping(bytes32 => int) position_amounts; // 持有部位 以債券代號為index
mapping(bytes32 => bool) hasAccounts;
}
customer private customers;
function Bank_CashAccount(bytes32 _bank_id) {
bank_id = _bank_id;
}
function setOwnedNode(bool _is_true) onlyOwner {
isOwnedNode = _is_true;
}
function checkOwnedNode() constant returns(bool) {
return isOwnedNode;
}
// 設定客戶擁有債券數量,注意,清算銀行自己本身也有帳號 客戶持有部位也要增加
function setCustomerCashAmount(bytes32 _customer_id, int _amount_total, bool _is_increase) onlyOwner {
if(!customers.hasCustomer[_customer_id]) {
customers.ids.push(_customer_id);
customers_cnt++;
customers.hasCustomer[_customer_id] = true;
}
if(!customers.cash_accounts[_customer_id].hasAccounts[_customer_id]) {
customers.cash_accounts[_customer_id].hasAccounts[_customer_id] = true;
}
int total_amount = customers.cash_accounts[_customer_id].total_amounts[_customer_id];
if(_is_increase) {
total_amount += _amount_total;
}else {
total_amount -= _amount_total;
}
customers.cash_accounts[_customer_id].total_amounts[_customer_id] = total_amount;
}
function setCustomerCashPosition(bytes32 _customer_id, int _amount, bool _is_increase) onlyOwner {
int position_amount = customers.cash_accounts[_customer_id].position_amounts[_customer_id];
if(_is_increase) {
position_amount += _amount;
}else {
position_amount -= _amount;
}
customers.cash_accounts[_customer_id].position_amounts[_customer_id] = position_amount;
}
function getCustomerCashAmount(bytes32 _customer_id) constant returns(int) {
if(msg.sender != owner) {
// do nothing, just return
return(0);
}
return(customers.cash_accounts[_customer_id].total_amounts[_customer_id]);
}
function getCustomerCashPosition(bytes32 _customer_id) constant returns(int) {
if(msg.sender != owner) {
// do nothing, just return
return(0);
}
return(customers.cash_accounts[_customer_id].position_amounts[_customer_id]);
}
function getCustomerList(uint index) constant returns (bytes32) {
return(customers.ids[index]);
}
function getCustomerListLength() constant returns (uint) {
return(customers_cnt);
}
}
// TransactionMatcher必須由央行deploy 如此央行才能成為owner
contract PaymentMatcher is Owned {
bytes32[] shareQueue; // 跨行交易用的queue
bytes32[] privateQueue; // 自行交易用的queue
function PaymentMatcher() {
owner = msg.sender;
//maxQueueDepth = 100;
}
enum PaymentState { Pending, Matched, Finished, Cancelled, Waiting4Confirm }
struct Payment {
bytes32 paymentSerNo; // 交易代號
bytes32 from_bank_id; // 賣方清算銀行代號
bytes32 from_customer_id; // 賣方帳號
bytes32 to_bank_id; // 買方清算銀行代號
bytes32 to_customer_id; // 買方帳號
int payment; // 交易面額
int blocked_amount; // 圈存面額
PaymentState state; // 交易狀態
uint timestamp; // 交易發送時間
bytes32 digest; // 交易摘要(MD5) 買賣雙方的交易摘要需相同才可比對
address msg_sender; // 發送交易之區塊鏈帳戶
bytes32 rev_paymentSerNo; // 紀錄被更正之交易代號
int return_code; // 紀錄傳回值
uint timeout; // timeout (sec)
bytes32 paymentHash; // Hash(X) , X 為 secret
bytes32 secret;
}
bytes32[] paymentIdx;
mapping (bytes32 => Payment) Payments;
mapping (bytes32 => bool) isPaymentWaitingForMatch; // has a transaction registered in the list
mapping (bytes32 => bytes32) paymentDigest_SerNo1; // txn digest => txnSerNo
bytes32[] banks_list;
mapping (bytes32 => address) bankRegistry;
event EventForCreateCashBank(bytes32 _bank_id);
event EventForSetOwnedNode(bytes32 _bank_id);
// privateFor[央行與所有清算行]
function createCashBank(bytes32 _bank_id, address _bankOwner) onlyOwner {
address bank = new Bank_CashAccount(_bank_id);
bankRegistry[_bank_id] = bank; // 清算銀行Bank_Account合約位址
banks_list.push(_bank_id);
//bankAdmins[_bank_id] = _bankOwner;
EventForCreateCashBank(_bank_id);
}
// privateFor[央行與被建立的清算行]
// 可以讓被建立的清算行利用checkOwnedNode傳回true判斷是自己的節點 因為節點不會看到別人的Bank_Account Contract
function setOwnedNode(bytes32 _bank_id, bool _is_true) onlyOwner {
Bank_CashAccount bank = Bank_CashAccount(bankRegistry[_bank_id]);
bank.setOwnedNode(true);
//bank.setBankContract(_bank_contract);
EventForSetOwnedNode(_bank_id);
}
function registCustomerCash(bytes32 _bank_id, bytes32 _customer_id, int _amount) {
setCustomerCashAmount(_bank_id, _customer_id, _amount, true);
setCustomerCashPosition(_bank_id, _customer_id, _amount, true);
}
// 只能internal 呼叫,避免鏈外隨便可以改帳目
function setCustomerCashAmount(bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) internal {
Bank_CashAccount bank = Bank_CashAccount(bankRegistry[_bank_id]);
bank.setCustomerCashAmount(_customer_id, _amount, _is_increase);
//EventForSetCustomerOwnedSecuritiesAmount( _securities_id, _bank_id, _customer_id, _amount, _is_increase);
}
// 只能internal 呼叫,避免鏈外隨便可以改帳目
function setCustomerCashPosition(bytes32 _bank_id, bytes32 _customer_id, int _amount, bool _is_increase) internal {
Bank_CashAccount bank = Bank_CashAccount(bankRegistry[_bank_id]);
bank.setCustomerCashPosition(_customer_id, _amount, _is_increase);
//EventForSetCustomerOwnedSecuritiesPosition( _securities_id, _bank_id, _customer_id, _amount, _is_increase);
}
function getCustomerCashAmount(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) {
Bank_CashAccount bank = Bank_CashAccount(bankRegistry[_bank_id]);
return(bank.getCustomerCashAmount(_customer_id));
}
function getCustomerCashPosition(bytes32 _bank_id, bytes32 _customer_id) constant returns(int) {
Bank_CashAccount bank = Bank_CashAccount(bankRegistry[_bank_id]);
return(bank.getCustomerCashPosition(_customer_id));
}
event EventForPaymentPending(bytes32 _paymentSerNo);
event EventForPaymentCancelled(bytes32 _paymentSerNo, int rc, string _reason);
event EventForPaymentFinished(bytes32 _paymentSerNo1, bytes32 _paymentSerNo2);
event EventForPaymentWaitingForConfirm(bytes32 _paymentSerNo1, bytes32 _paymentSerNo2);
event EventForPaymentError(bytes32 _paymentSerNo1, bytes32 _paymentSerNo2, int rc);
event EventForPaymentConfirmed(bytes32 _paymentSerNo1, bytes32 _paymentSerNo2, address msg_sender, bytes32 _paymentHash, bytes32 _secret);
// 可能為賣方清算行或是買方清算行呼叫,寫code時需要配合Quorum的private transaction的運作模式,privateFor[對方行,央行]
// 注意,每筆交易每個在privateFor的node都會執行,寫code時要有這個思維。
function submitInterBankPayment(bytes32 _paymentSerNo, bytes32 _from_bank_id, bytes32 _from_customer_id,
bytes32 _to_bank_id, bytes32 _to_customer_id,
int _payment, bytes32 _digest, uint _timeout, bytes32 _paymentHash)
{
if(_payment == 0) {
return;
}
Payment memory this_payment;
Bank_CashAccount seller = Bank_CashAccount(bankRegistry[_from_bank_id]);
Bank_CashAccount buyer = Bank_CashAccount(bankRegistry[_to_bank_id]);
if(buyer.checkOwnedNode()) { // 買方跟央行才能檢查,在賣方節點無法檢查賣方的帳戶資料,這段code是必須的,否則在共識階段,買方節點上這交易會被cancel
// 若Dapp有檢查,則這段程式跑不到,加這段檢查以防萬一
if( getCustomerCashPosition(_to_bank_id, _to_customer_id) < _payment) {
// 買方(from)券數持有部位不足
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id,
_payment, 0, PaymentState.Cancelled, now, _digest, msg.sender, "", 3 , _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
EventForPaymentCancelled(_paymentSerNo, 3, "");
return;
}
// 若為買方清算行打進來的交易,則圈存買方債券戶(DLT) 買方跟央行才做這段 因為買方跟央行都看得到賣方的Bank_Account Contract
// 在共識階段,賣方清算行節點會跳過這段,結果資料會跟買方節點不同,但因為賣方不需要也不能夠知道買方的帳戶資料,因此這是必要的。
if(bytes1(uint8(uint(_paymentSerNo) / (2**((31 - 5) * 8)))) == 'B') {
setCustomerCashPosition( _to_bank_id, _to_customer_id, _payment, false);
}
}
// 須處理買方先打交易 但是賣方券不夠 造成交易變成pending 賣方要打交易將買方節點該交易的狀態設為cancelled
// matching payment 交易比對
if( isPaymentWaitingForMatch[_digest]) {
if (msg.sender == Payments[paymentDigest_SerNo1[_digest]].msg_sender) {
// 同一個msg.sender打相同交易進區塊鍊,設為Pending 因無法判斷是兩筆不同交易或是打錯
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id,
_payment, 0, PaymentState.Pending, now, _digest, msg.sender, "", 0, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
enShareQueue(_paymentSerNo);
EventForPaymentPending(_paymentSerNo);
return;
}else {
bytes32 _paymentSerNo1 = paymentDigest_SerNo1[_digest];
setPaymentState(_paymentSerNo1, uint(PaymentState.Waiting4Confirm)); // 將前一筆狀態設為Waiting4Confirm
isPaymentWaitingForMatch[_digest] = false;
delete isPaymentWaitingForMatch[_digest];
delete paymentDigest_SerNo1[_digest];
// 注意:紀錄圈存額度
// 不管買方或賣方都要記錄圈存數量
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id,
_payment, _payment, PaymentState.Waiting4Confirm, now, _digest, msg.sender, "", 0, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
EventForPaymentWaitingForConfirm(_paymentSerNo, _paymentSerNo1);
}
}else {
isPaymentWaitingForMatch[_digest] = true;
// 不管買方或賣方都要記錄圈存數量
paymentDigest_SerNo1[_digest] = _paymentSerNo;
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _to_bank_id, _to_customer_id,
_payment, _payment, PaymentState.Pending, now, _digest, msg.sender, "", 0, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
enShareQueue(_paymentSerNo);
EventForPaymentPending(_paymentSerNo);
}
}
// privateFor [央行] (交易只會在清算行本身及央行節點上面執行)
function submitIntraBankPayment(bytes32 _paymentSerNo, bytes32 _from_bank_id, bytes32 _from_customer_id,
bytes32 _to_customer_id, int _payment, bytes32 _digest, uint _timeout, bytes32 _paymentHash)
{
if(_payment == 0) {
return;
}
Payment memory this_payment;
if(_from_customer_id == _to_customer_id) {
// Do nothing
// 賣方與買方為同一人
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_payment, 0, PaymentState.Cancelled, now, _digest, msg.sender, "", 2, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
//enqueue(_txSerNo);
//queued = true;
EventForPaymentCancelled(_paymentSerNo, 2, "");
return;
}
// 買賣方皆為同一個節點,不會有跨行抓不到資料的問題,因此不判斷是買方或賣方,一律檢查,
if(bytes1(uint8(uint(_paymentSerNo) / (2**((31 - 5) * 8)))) == 'B') {
if( getCustomerCashPosition(_from_bank_id, _to_customer_id) < _payment) {
// 賣方(from)券數持有部位不足
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_payment, 0, PaymentState.Cancelled, now, _digest, msg.sender, "", 3, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
//enqueue(_txSerNo);
//queued = true;
EventForPaymentCancelled(_paymentSerNo, 3, "");
return;
}
//自行圈存買方(DLT)
setCustomerCashPosition( _from_bank_id, _to_customer_id, _payment, false);
}
// matching transaction 交易比對
if( isPaymentWaitingForMatch[_digest]) {
//Transaction 是 atomic 不用擔心Double Spending的問題
bytes32 _paymentSerNo1 = paymentDigest_SerNo1[_digest];
setPaymentState(_paymentSerNo1, uint(PaymentState.Matched));
isPaymentWaitingForMatch[_digest] = false;
delete isPaymentWaitingForMatch[_digest];
delete paymentDigest_SerNo1[_digest];
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_payment, _payment, PaymentState.Matched, now, _digest, msg.sender, "", 0, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
// 更新DLT債券戶資訊
setCustomerCashAmount(_from_bank_id, _from_customer_id, _payment, true);
setCustomerCashAmount(_from_bank_id, _to_customer_id, _payment, false);
// 買方已圈存,不須再增加持有部位
//setCustomerOwnedSecuritiesPosition(_securities_id, _from_bank_id, _from_customer_id, _securities_amount, false);
setCustomerCashPosition(_from_bank_id, _from_customer_id, _payment, true);
setPaymentState(_paymentSerNo, uint(PaymentState.Finished)); // 將Transaction設為Finished
setPaymentState(_paymentSerNo1, uint(PaymentState.Finished)); // 將Transaction設為Finished
dePrivateQueue(_paymentSerNo);
dePrivateQueue(_paymentSerNo1);
EventForPaymentFinished(_paymentSerNo, _paymentSerNo1);
}else {
isPaymentWaitingForMatch[_digest] = true;
paymentDigest_SerNo1[_digest] = _paymentSerNo;
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_payment, _payment, PaymentState.Pending, now, _digest, msg.sender, "", 0, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
enPrivateQueue(_paymentSerNo);
EventForPaymentPending(_paymentSerNo);
}
}
// privateFor [央行] (交易只會在清算行本身及央行節點上面執行)
// reason 不會存在Trsnactions裡面 但是在傳進來的過程中(Payload) 已經記錄在區塊裡
function submitSetPaymentCancelled(bytes32 _rev_paymentSerNo, bytes32 _paymentSerNo, int _rc, string _reason) {
Payment this_payment = Payments[_rev_paymentSerNo];
// 只有Pending與Waiting4Confirm才處理
if( (this_payment.state == PaymentState.Pending) || (this_payment.state == PaymentState.Waiting4Confirm) ) {
int _blocked_amount = this_payment.blocked_amount;
bytes32 _to_bank_id = this_payment.to_bank_id;
bytes32 _to_customer_id = this_payment.to_customer_id;
//買賣方跟央行都做這段,但賣方做沒用,只是寫入無意義的別家清算行資料
//if(msg.sender == bankAdmins[_from_bank_id] || msg.sender == owner) {
Bank_CashAccount buyer = Bank_CashAccount(bankRegistry[_to_bank_id]);
if(_rc == 5) { // 只有賣方發的交易才解圈 買方發的交易也會進來 因此用rc 分辨
if(buyer.checkOwnedNode() && _blocked_amount > 0) {
// 解除圈存
setCustomerCashPosition(_to_bank_id, _to_customer_id, _blocked_amount, true);
}
}
//}
this_payment.rev_paymentSerNo = _paymentSerNo;
this_payment.state = PaymentState.Cancelled;
this_payment.return_code = _rc;
bytes32 _digest = getPaymentDigest(_rev_paymentSerNo);
isPaymentWaitingForMatch[_digest] = false;
delete isPaymentWaitingForMatch[_digest];
//setSecuritiesTransactionState(_rev_txSerNo, uint(TxnState.Cancelled));
Payment _payment = Payments[_paymentSerNo];
_payment.rev_paymentSerNo = _rev_paymentSerNo;
EventForPaymentCancelled(_rev_paymentSerNo, _rc, _reason);
}
}
function submitSetPaymentConfirmed(bytes32 _paymentSerNo1, bytes32 _paymentSerNo2, bytes32 _paymentHash, bytes32 _secret) {
// 傳回 msg_sender 以及 _paymentHash 供 Oracle 驗證 呼叫交易即確認msg.sender的簽章 不需再用 ecrecover
Payment payment1 = Payments[_paymentSerNo1];
Payment payment2 = Payments[_paymentSerNo2];
payment1.secret = _secret;
payment2.secret = _secret;
EventForPaymentConfirmed(_paymentSerNo1, _paymentSerNo2, msg.sender, _paymentHash, _secret);
}
// 同資回應後央行節點呼叫,只有央行可發動
function settleInterBankPayment(bytes32 _paymentSerNo1, bytes32 _paymentSerNo2, int _cb_return_code, bool _isNettingSuccess) onlyOwner returns(bool) {
Payment payment1 = Payments[_paymentSerNo1];
Payment payment2 = Payments[_paymentSerNo2];
Bank_CashAccount seller = Bank_CashAccount(bankRegistry[payment1.from_bank_id]);
Bank_CashAccount buyer = Bank_CashAccount(bankRegistry[payment1.to_bank_id]);
if(_isNettingSuccess == true) {
if(seller.checkOwnedNode()) {
// 更新DLT債券戶資訊
setCustomerCashAmount(payment1.from_bank_id, payment1.from_customer_id, payment1.payment, true);
// 增加賣方持有部位
setCustomerCashPosition(payment1.from_bank_id, payment1.from_customer_id, payment1.payment, true);
}
if(buyer.checkOwnedNode()) {
setCustomerCashAmount(payment1.to_bank_id, payment1.to_customer_id, payment1.payment, false);
}
setPaymentState(_paymentSerNo1, uint(PaymentState.Finished)); // 將Transaction設為Finished
setPaymentState(_paymentSerNo2, uint(PaymentState.Finished)); // 將Transaction設為Finished
deShareQueue(_paymentSerNo1);
deShareQueue(_paymentSerNo2);
EventForPaymentFinished(_paymentSerNo1, _paymentSerNo2);
}else {
if(_cb_return_code == 500) {
if(buyer.checkOwnedNode()) {
// 同資系統錯誤,解除圈存買方戶(DLT)
setCustomerCashPosition(payment1.to_bank_id, payment1.to_customer_id, payment1.payment, true);
}
setPaymentState(_paymentSerNo1, uint(PaymentState.Cancelled));
setPaymentState(_paymentSerNo2, uint(PaymentState.Cancelled));
}
payment1.return_code = _cb_return_code; // 設定同資錯誤碼
payment2.return_code = _cb_return_code; // 設定同資錯誤碼
EventForPaymentError(_paymentSerNo1, _paymentSerNo2, _cb_return_code);
}
return _isNettingSuccess;
}
function setPaymentState(bytes32 _paymentSerNo, uint _payment_state) internal {
Payment this_payment = Payments[_paymentSerNo];
// Initiate, Confirmed, ReadyToSettle, Settled, Finished, Canceled
if( _payment_state == uint(PaymentState.Pending)) {
this_payment.state = PaymentState.Pending;
}else if( _payment_state == uint(PaymentState.Waiting4Confirm)) {
this_payment.state = PaymentState.Waiting4Confirm;
}else if( _payment_state == uint(PaymentState.Matched)) {
this_payment.state = PaymentState.Matched;
}else if( _payment_state == uint(PaymentState.Finished)) {
this_payment.state = PaymentState.Finished;
}else if( _payment_state == uint(PaymentState.Cancelled)) {
this_payment.state = PaymentState.Cancelled;
}
}
function enShareQueue(bytes32 _paymentSerNo) internal {
shareQueue.push(_paymentSerNo);
}
function deShareQueue(bytes32 _paymentSerNo) internal {
for(uint i=0; i< shareQueue.length; i++) {
if(_paymentSerNo == shareQueue[i]) {
delete shareQueue[i];
break;
}
}
}
function enPrivateQueue(bytes32 _paymentSerNo) internal {
privateQueue.push(_paymentSerNo);
}
function dePrivateQueue(bytes32 _paymentSerNo) internal {
for(uint i=0; i< privateQueue.length; i++) {
if(_paymentSerNo == privateQueue[i]) {
delete privateQueue[i];
break;
}
}
}
function getShareQueueDepth() constant returns(uint) {
return shareQueue.length;
}
function getPrivateQueueDepth() constant returns(uint) {
return privateQueue.length;
}
function getShareQueueEntry(uint index) constant returns(bytes32) {
return shareQueue[index];
}
function getPrivateQueueEntry(uint index) constant returns(bytes32) {
return privateQueue[index];
}
function clearQueue() onlyOwner {
// 清除ShareQueue的所有交易,由央行發動清Queue,因為日終交易發動時機是央行決定的
for (uint i=0; i< shareQueue.length; i++) {
delete shareQueue[i];
}
shareQueue.length = 0;
// 清除PrivateQueue的所有交易,由央行發動清Queue,因為日終交易發動時機是央行決定的
for (uint j=0; j< privateQueue.length; j++) {
delete privateQueue[j];
}
privateQueue.length = 0;
}
function getPaymentListLength() constant returns(uint) {
return paymentIdx.length;
}
function getPaymentList(uint index) constant returns(bytes32) {
return paymentIdx[index];
}
function getPaymentInfo(bytes32 _paymentSerNo) constant returns(bytes32, bytes32 , bytes32 , bytes32 , int , uint, bytes32, bytes32) {
Payment this_payment = Payments[_paymentSerNo];
return(this_payment.from_bank_id, this_payment.from_customer_id,
this_payment.to_bank_id, this_payment.to_customer_id,
this_payment.payment, this_payment.timestamp, this_payment.digest,
this_payment.rev_paymentSerNo
);
}
function getPaymentDigest(bytes32 _paymentSerNo) constant returns(bytes32) {
Payment this_payment = Payments[_paymentSerNo];
return(this_payment.digest);
}
function getPaymentTimeout(bytes32 _paymentSerNo) constant returns(uint) {
Payment this_payment = Payments[_paymentSerNo];
return(this_payment.timeout);
}
function getPaymentHash(bytes32 _paymentSerNo) constant returns(bytes32) {
Payment this_payment = Payments[_paymentSerNo];
return(this_payment.paymentHash);
}
function getPaymentState(bytes32 _paymentSerNo) constant returns(uint, int) {
Payment this_payment = Payments[_paymentSerNo];
return(uint(this_payment.state), this_payment.return_code);
}
}
| privateFor [央行] (交易只會在清算行本身及央行節點上面執行) | {
function submitIntraBankPayment(bytes32 _paymentSerNo, bytes32 _from_bank_id, bytes32 _from_customer_id,
bytes32 _to_customer_id, int _payment, bytes32 _digest, uint _timeout, bytes32 _paymentHash)
if(_payment == 0) {
return;
}
Payment memory this_payment;
if(_from_customer_id == _to_customer_id) {
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_payment, 0, PaymentState.Cancelled, now, _digest, msg.sender, "", 2, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
EventForPaymentCancelled(_paymentSerNo, 2, "");
return;
}
if(bytes1(uint8(uint(_paymentSerNo) / (2**((31 - 5) * 8)))) == 'B') {
if( getCustomerCashPosition(_from_bank_id, _to_customer_id) < _payment) {
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_payment, 0, PaymentState.Cancelled, now, _digest, msg.sender, "", 3, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
EventForPaymentCancelled(_paymentSerNo, 3, "");
return;
}
}
if(bytes1(uint8(uint(_paymentSerNo) / (2**((31 - 5) * 8)))) == 'B') {
if( getCustomerCashPosition(_from_bank_id, _to_customer_id) < _payment) {
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_payment, 0, PaymentState.Cancelled, now, _digest, msg.sender, "", 3, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
EventForPaymentCancelled(_paymentSerNo, 3, "");
return;
}
}
setCustomerCashPosition( _from_bank_id, _to_customer_id, _payment, false);
if( isPaymentWaitingForMatch[_digest]) {
bytes32 _paymentSerNo1 = paymentDigest_SerNo1[_digest];
setPaymentState(_paymentSerNo1, uint(PaymentState.Matched));
isPaymentWaitingForMatch[_digest] = false;
delete isPaymentWaitingForMatch[_digest];
delete paymentDigest_SerNo1[_digest];
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_payment, _payment, PaymentState.Matched, now, _digest, msg.sender, "", 0, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
setCustomerCashAmount(_from_bank_id, _from_customer_id, _payment, true);
setCustomerCashAmount(_from_bank_id, _to_customer_id, _payment, false);
setCustomerCashPosition(_from_bank_id, _from_customer_id, _payment, true);
dePrivateQueue(_paymentSerNo);
dePrivateQueue(_paymentSerNo1);
EventForPaymentFinished(_paymentSerNo, _paymentSerNo1);
isPaymentWaitingForMatch[_digest] = true;
paymentDigest_SerNo1[_digest] = _paymentSerNo;
this_payment = Payment(_paymentSerNo, _from_bank_id, _from_customer_id, _from_bank_id, _to_customer_id,
_payment, _payment, PaymentState.Pending, now, _digest, msg.sender, "", 0, _timeout, _paymentHash, "");
paymentIdx.push(_paymentSerNo);
Payments[_paymentSerNo] = this_payment;
enPrivateQueue(_paymentSerNo);
EventForPaymentPending(_paymentSerNo);
}
}else {
}
| 12,873,514 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./Campaign.sol";
import "./CampaignReward.sol";
import "./CampaignRequest.sol";
import "./CampaignVote.sol";
import "../libraries/math/DecimalMath.sol";
contract CampaignFactory is
Initializable,
PausableUpgradeable,
ReentrancyGuardUpgradeable
{
using SafeMathUpgradeable for uint256;
/// @dev `Factory Config Events`
event CampaignImplementationUpdated(address indexed campaignImplementation);
event CampaignRewardImplementationUpdated(
address indexed campaignRewardImplementation
);
event CampaignRequestImplementationUpdated(
address indexed campaignRequestImplementation
);
event CampaignVoteImplementationUpdated(
address indexed campaignVoteImplementation
);
event CategoryCommissionUpdated(
uint256 indexed categoryId,
uint256 commission
);
event CampaignDefaultCommissionUpdated(uint256 commission);
event CampaignTransactionConfigUpdated(string prop, uint256 value);
/// @dev `Campaign Events`
event CampaignDeployed(
address factory,
address campaign,
address campaignRewards,
address campaignRequests,
address campaignVotes,
uint256 category,
bool privateCampaign,
string hashedCampaignInfo
);
event CampaignActivation(Campaign indexed campaign, bool active);
event CampaignPrivacyChange(
Campaign indexed campaign,
bool privateCampaign
);
event CampaignCategoryChange(
Campaign indexed campaign,
uint256 newCategory
);
/// @dev `Token Events`
event TokenAdded(address indexed token, bool approval, string hashedToken);
event TokenApproval(address indexed token, bool state);
/// @dev `User Events`
event UserAdded(address indexed userId, string hashedUser);
event UserApproval(address indexed user, bool approval);
/// @dev `Trustee Events`
event TrusteeAdded(uint256 indexed trusteeId, address trusteeAddress);
event TrusteeRemoved(uint256 indexed trusteeId, address trusteeAddress);
/// @dev `Category Events`
event CategoryAdded(
uint256 indexed categoryId,
bool active,
string title,
string hashedCategory
);
event CategoryModified(
uint256 indexed categoryId,
bool active,
string title
);
/// @dev Settings
address public governance;
address public campaignFactoryAddress;
address public campaignImplementation;
address public campaignRewardsImplementation;
address public campaignVotesImplementation;
address public campaignRequestsImplementation;
string[] public campaignTransactionConfigList;
mapping(string => bool) public approvedCampaignTransactionConfig;
mapping(string => uint256) public campaignTransactionConfig;
mapping(uint256 => uint256) public categoryCommission;
/// @dev Revenue
uint256 public factoryRevenue; // total from all campaigns
mapping(address => uint256) public campaignRevenueFromCommissions; // revenue from cuts
/// @dev `Campaigns`
struct CampaignInfo {
address owner;
uint256 createdAt;
uint256 updatedAt;
uint256 category;
string hashedCampaignInfo;
bool active;
bool privateCampaign;
}
mapping(Campaign => CampaignInfo) public campaigns;
uint256 public campaignCount;
/// @dev `Categories`
struct CampaignCategory {
uint256 campaignCount;
uint256 createdAt;
uint256 updatedAt;
string title;
string hashedCategory;
bool active;
bool exists;
}
CampaignCategory[] public campaignCategories; // array of campaign categories
mapping(string => bool) public categoryTitleIsTaken;
uint256 public categoryCount;
/// @dev `Users`
struct User {
uint256 joined;
uint256 updatedAt;
string hashedUser;
bool verified;
}
mapping(address => User) public users;
mapping(address => bool) public userExists;
uint256 public userCount;
/// @dev `Tokens`
struct Token {
address token;
string hashedToken;
bool approved;
}
mapping(address => Token) public tokens;
/// @dev `Trustees`
struct Trust {
address trustee;
address trustor;
uint256 createdAt;
bool isTrusted;
}
Trust[] public trustees;
mapping(address => uint256) public userTrusteeCount;
mapping(address => bool) public accountInTransit;
mapping(address => address) public accountTransitStartedBy;
// { trustor -> trustee -> isTrusted }
mapping(address => mapping(address => bool)) public isUserTrustee;
/// @dev Ensures caller is owner of contract
modifier onlyAdmin() {
// check is governance address
require(governance == msg.sender, "forbidden");
_;
}
/// @dev Ensures caller is campaign owner alone
modifier campaignOwner(Campaign _campaign) {
require(
campaigns[_campaign].owner == msg.sender,
"only campaign owner"
);
_;
}
/// @dev Ensures caller is a registered campaign contract from factory
modifier onlyRegisteredCampaigns(Campaign _campaign) {
require(address(_campaign) == msg.sender, "only campaign owner");
_;
}
/**
* @dev Contructor
* @param _governance Address where all revenue gets deposited
*/
function __CampaignFactory_init(
address _governance,
address _campaignImplementation,
address _campaignRequestImplementation,
address _campaignVoteImplementation,
address _campaignRewardImplementation,
uint256[15] memory _config
) public initializer {
require(_governance != address(0));
require(_campaignImplementation != address(0));
require(_campaignRequestImplementation != address(0));
require(_campaignVoteImplementation != address(0));
require(_campaignRewardImplementation != address(0));
governance = _governance;
campaignFactoryAddress = address(this);
string[15] memory transactionConfigs = [
"defaultCommission",
"deadlineStrikesAllowed",
"minimumContributionAllowed",
"maximumContributionAllowed",
"minimumRequestAmountAllowed",
"maximumRequestAmountAllowed",
"minimumCampaignTarget",
"maximumCampaignTarget",
"minDeadlineExtension",
"maxDeadlineExtension",
"minRequestDuration",
"maxRequestDuration",
"reviewThresholdMark",
"requestFinalizationThreshold",
"reportThresholdMark"
];
for (uint256 index = 0; index < transactionConfigs.length; index++) {
campaignTransactionConfigList.push(transactionConfigs[index]);
approvedCampaignTransactionConfig[transactionConfigs[index]] = true;
campaignTransactionConfig[transactionConfigs[index]] = _config[
index
];
}
campaignImplementation = _campaignImplementation;
campaignRequestsImplementation = _campaignRequestImplementation;
campaignVotesImplementation = _campaignVoteImplementation;
campaignRewardsImplementation = _campaignRewardImplementation;
_createCategory(true, "miscellaneous", "");
}
/**
* @dev Updates campaign implementation address
* @param _campaignImplementation Address of base contract to deploy minimal proxies
*/
function setCampaignImplementation(Campaign _campaignImplementation)
external
onlyAdmin
{
require(address(_campaignImplementation) != address(0));
campaignImplementation = address(_campaignImplementation);
emit CampaignImplementationUpdated(address(_campaignImplementation));
}
/**
* @dev Updates campaign reward implementation address
* @param _campaignRewardsImplementation Address of base contract to deploy minimal proxies
*/
function setCampaignRewardImplementation(
CampaignReward _campaignRewardsImplementation
) external onlyAdmin {
require(address(_campaignRewardsImplementation) != address(0));
campaignRewardsImplementation = address(_campaignRewardsImplementation);
emit CampaignRewardImplementationUpdated(
address(_campaignRewardsImplementation)
);
}
/**
* @dev Updates campaign request implementation address
* @param _campaignRequestsImplementation Address of base contract to deploy minimal proxies
*/
function setCampaignRequestImplementation(
CampaignRequest _campaignRequestsImplementation
) external onlyAdmin {
require(address(_campaignRequestsImplementation) != address(0));
campaignRequestsImplementation = address(
_campaignRequestsImplementation
);
emit CampaignRequestImplementationUpdated(
address(_campaignRequestsImplementation)
);
}
/**
* @dev Updates campaign request implementation address
* @param _campaignVotesImplementation Address of base contract to deploy minimal proxies
*/
function setCampaignVoteImplementation(
CampaignVote _campaignVotesImplementation
) external onlyAdmin {
require(address(_campaignVotesImplementation) != address(0));
campaignVotesImplementation = address(_campaignVotesImplementation);
emit CampaignVoteImplementationUpdated(
address(_campaignVotesImplementation)
);
}
/**
* @dev Adds a new transaction setting
* @param _prop Setting Key
*/
function addFactoryTransactionConfig(string memory _prop)
external
onlyAdmin
{
require(!approvedCampaignTransactionConfig[_prop]);
campaignTransactionConfigList.push(_prop);
approvedCampaignTransactionConfig[_prop] = true;
}
/**
* @dev Set Factory controlled values dictating how campaign deployments should run
* @param _prop Setting Key
* @param _value Setting Value
*/
function setCampaignTransactionConfig(string memory _prop, uint256 _value)
external
onlyAdmin
{
require(approvedCampaignTransactionConfig[_prop]);
campaignTransactionConfig[_prop] = _value;
emit CampaignTransactionConfigUpdated(_prop, _value);
}
/**
* @dev Sets default commission on all request finalization
* @param _numerator Fraction Fee percentage on request finalization
* @param _denominator Fraction Fee percentage on request finalization
*/
function setDefaultCommission(uint256 _numerator, uint256 _denominator)
external
onlyAdmin
{
DecimalMath.UFixed memory _commission = DecimalMath.divd(
DecimalMath.toUFixed(_numerator),
DecimalMath.toUFixed(_denominator)
);
campaignTransactionConfig["defaultCommission"] = _commission.value;
emit CampaignDefaultCommissionUpdated(_commission.value);
}
/**
* @dev Sets commission per category basis
* @param _categoryId ID of category
* @param _numerator Fraction Fee percentage on request finalization in campaign per category `defaultCommission` will be utilized if value is `0`
* @param _denominator Fraction Fee percentage on request finalization in campaign per category `defaultCommission` will be utilized if value is `0`
*/
function setCategoryCommission(
uint256 _categoryId,
uint256 _numerator,
uint256 _denominator
) external onlyAdmin {
require(campaignCategories[_categoryId].exists);
DecimalMath.UFixed memory _commission = DecimalMath.divd(
DecimalMath.toUFixed(_numerator),
DecimalMath.toUFixed(_denominator)
);
categoryCommission[_categoryId] = _commission.value;
campaignCategories[_categoryId].updatedAt = block.timestamp;
emit CategoryCommissionUpdated(_categoryId, _commission.value);
}
/**
* @dev Adds a token that needs approval before being accepted
* @param _token Address of the token
* @param _approved Status of token approval
* @param _hashedToken CID reference of the token on IPFS
*/
function addToken(
address _token,
bool _approved,
string memory _hashedToken
) external onlyAdmin {
tokens[_token] = Token(_token, _hashedToken, _approved);
emit TokenAdded(_token, _approved, _hashedToken);
}
/**
* @dev Sets if a token is accepted or not provided it's in the list of token
* @param _token Address of the token
* @param _state Status of token approval
*/
function toggleAcceptedToken(address _token, bool _state)
external
onlyAdmin
{
tokens[_token].approved = _state;
emit TokenApproval(_token, _state);
}
/**
* @dev Checks if a user can manage a campaign. Called but not restricted to external campaign proxies
* @param _user Address of user
*/
function canManageCampaigns(address _user) public view returns (bool) {
return _user == governance;
}
/**
* @dev Retrieves campaign commission fees. Restricted to campaign owner.
* @param _amount Amount transfered and collected by factory from campaign request finalization
* @param _campaign Address of campaign instance
*/
function receiveCampaignCommission(Campaign _campaign, uint256 _amount)
external
onlyRegisteredCampaigns(_campaign)
{
campaignRevenueFromCommissions[
address(_campaign)
] = campaignRevenueFromCommissions[address(_campaign)].add(_amount);
factoryRevenue = factoryRevenue.add(_amount);
}
/**
* @dev Keep track of user addresses. sybil resistance purpose
* @param _hashedUser CID reference of the user on IPFS
*/
function signUp(string memory _hashedUser) public whenNotPaused {
require(!userExists[msg.sender], "already exists");
users[msg.sender] = User(block.timestamp, 0, _hashedUser, false);
userExists[msg.sender] = true;
userCount = userCount.add(1);
emit UserAdded(msg.sender, _hashedUser);
}
/**
* @dev Ensures user specified is verified
* @param _user Address of user
*/
function userIsVerified(address _user) public view returns (bool) {
return users[_user].verified;
}
/**
* @dev Initiates user account transfer process
* @param _user Address of user account being transferred
* @param _forSelf Indicates if the transfer is made on behalf of a trustee
*/
function initiateUserTransfer(address _user, bool _forSelf) external {
if (_forSelf) {
require(
msg.sender == _user,
"only the user can initiate the transfer"
);
accountInTransit[msg.sender] = true;
accountTransitStartedBy[msg.sender] = msg.sender;
} else {
require(isUserTrustee[_user][msg.sender], "not a trustee");
if (!accountInTransit[_user]) {
accountInTransit[_user] = true;
accountTransitStartedBy[_user] = msg.sender;
}
}
}
/// @dev calls off the user account transfer process
function deactivateAccountTransfer() external {
if (accountInTransit[msg.sender]) {
accountInTransit[msg.sender] = false;
accountTransitStartedBy[msg.sender] = address(0);
}
}
/**
* @dev Trustees are people the user can add to help recover their account in the case they lose access to ther wallets
* @param _trustee Address of the trustee, must be a verified user
*/
function addTrustee(address _trustee) external whenNotPaused {
require(userIsVerified(msg.sender), "unverified user");
require(userIsVerified(_trustee), "unverified trustee");
require(userTrusteeCount[msg.sender] <= 6, "trustees exhausted");
isUserTrustee[msg.sender][_trustee] = true;
trustees.push(Trust(_trustee, msg.sender, block.timestamp, true));
userTrusteeCount[msg.sender] = userTrusteeCount[msg.sender].add(1);
emit TrusteeAdded(trustees.length.sub(1), _trustee);
}
/**
* @dev Removes a trustee from users list of trustees
* @param _trusteeId Address of the trustee
*/
function removeTrustee(uint256 _trusteeId) external whenNotPaused {
Trust storage trustee = trustees[_trusteeId];
require(msg.sender == trustee.trustor, "not owner of trust");
require(userIsVerified(msg.sender), "unverified user");
isUserTrustee[msg.sender][trustee.trustee] = false;
userTrusteeCount[msg.sender] = userTrusteeCount[msg.sender].sub(1);
delete trustees[_trusteeId];
emit TrusteeRemoved(_trusteeId, trustee.trustee);
}
/**
* @dev Approves or disapproves a user
* @param _user Address of the user
* @param _approval Indicates if the user will be approved or not
*/
function toggleUserApproval(address _user, bool _approval)
external
onlyAdmin
whenNotPaused
{
users[_user].verified = _approval;
users[_user].updatedAt = block.timestamp;
emit UserApproval(_user, _approval);
}
/**
* @dev Deploys and tracks a new campagign
* @param _categoryId ID of the category the campaign belongs to
* @param _privateCampaign Indicates approval status of the campaign
* @param _hashedCampaignInfo CID reference of the reward on IPFS
*/
function createCampaign(
uint256 _categoryId,
bool _privateCampaign,
string memory _hashedCampaignInfo
) external whenNotPaused {
// check `_categoryId` exists and active
require(
campaignCategories[_categoryId].exists &&
campaignCategories[_categoryId].active
);
// check user exists
require(userExists[msg.sender], "user does not exist");
require(campaignImplementation != address(0), "zero address");
require(campaignRewardsImplementation != address(0), "zero address");
require(campaignRequestsImplementation != address(0), "zero address");
require(campaignVotesImplementation != address(0), "zero address");
Campaign campaign = Campaign(
ClonesUpgradeable.clone(campaignImplementation)
);
CampaignReward campaignRewards = CampaignReward(
ClonesUpgradeable.clone(campaignRewardsImplementation)
);
CampaignRequest campaignRequests = CampaignRequest(
ClonesUpgradeable.clone(campaignRequestsImplementation)
);
CampaignVote campaignVotes = CampaignVote(
ClonesUpgradeable.clone(campaignVotesImplementation)
);
CampaignInfo memory campaignInfo = CampaignInfo({
category: _categoryId,
hashedCampaignInfo: _hashedCampaignInfo,
owner: msg.sender,
createdAt: block.timestamp,
updatedAt: 0,
active: false,
privateCampaign: _privateCampaign
});
campaigns[campaign] = campaignInfo;
campaignCategories[_categoryId].campaignCount = campaignCategories[
_categoryId
].campaignCount.add(1);
campaignCount = campaignCount.add(1);
Campaign(campaign).__Campaign_init(
CampaignFactory(this),
CampaignReward(campaignRewards),
CampaignRequest(campaignRequests),
CampaignVote(campaignVotes),
msg.sender
);
CampaignReward(campaignRewards).__CampaignReward_init(
CampaignFactory(this),
Campaign(campaign)
);
CampaignRequest(campaignRequests).__CampaignRequest_init(
CampaignFactory(this),
Campaign(campaign)
);
CampaignVote(campaignVotes).__CampaignVote_init(
CampaignFactory(this),
Campaign(campaign)
);
emit CampaignDeployed(
address(this),
address(campaign),
address(campaignRewards),
address(campaignRequests),
address(campaignVotes),
_categoryId,
_privateCampaign,
_hashedCampaignInfo
);
}
/**
* @dev Activates a campaign. Activating a campaign simply makes the campaign available for listing
on crowdship, events will be stored on thegraph activated or not, Restricted to governance
* @param _campaign Address of the campaign
*/
function toggleCampaignActivation(Campaign _campaign)
external
onlyAdmin
whenNotPaused
{
if (campaigns[_campaign].active) {
campaigns[_campaign].active = false;
} else {
campaigns[_campaign].active = true;
}
campaigns[_campaign].updatedAt = block.timestamp;
emit CampaignActivation(_campaign, campaigns[_campaign].active);
}
/**
* @dev Toggles the campaign privacy setting, Restricted to campaign managers
* @param _campaign Address of the campaign
*/
function toggleCampaignPrivacy(Campaign _campaign)
external
campaignOwner(_campaign)
whenNotPaused
{
if (campaigns[_campaign].privateCampaign) {
campaigns[_campaign].privateCampaign = false;
} else {
campaigns[_campaign].privateCampaign = true;
}
campaigns[_campaign].updatedAt = block.timestamp;
emit CampaignPrivacyChange(
_campaign,
campaigns[_campaign].privateCampaign
);
}
/**
* @dev Modifies a campaign's category.
* @param _campaign Address of the campaign
* @param _newCategoryId ID of the category being switched to
*/
function modifyCampaignCategory(Campaign _campaign, uint256 _newCategoryId)
external
campaignOwner(_campaign)
whenNotPaused
{
uint256 _oldCategoryId = campaigns[_campaign].category;
if (_oldCategoryId != _newCategoryId) {
require(campaignCategories[_newCategoryId].exists);
campaigns[_campaign].category = _newCategoryId;
campaignCategories[_oldCategoryId]
.campaignCount = campaignCategories[_oldCategoryId]
.campaignCount
.sub(1);
campaignCategories[_newCategoryId]
.campaignCount = campaignCategories[_newCategoryId]
.campaignCount
.add(1);
campaigns[_campaign].updatedAt = block.timestamp;
emit CampaignCategoryChange(_campaign, _newCategoryId);
}
}
/**
* @dev Public implementation of createCategory method
* @param _active Indicates if a category is active allowing for campaigns to be assigned to it
* @param _title Title of the category
* @param _hashedCategory CID reference of the category on IPFS
*/
function createCategory(
bool _active,
string memory _title,
string memory _hashedCategory
) public onlyAdmin whenNotPaused {
_createCategory(_active, _title, _hashedCategory);
}
/**
* @dev Creates a category
* @param _active Indicates if a category is active allowing for campaigns to be assigned to it
* @param _title Title of the category
* @param _hashedCategory CID reference of the category on IPFS
*/
function _createCategory(
bool _active,
string memory _title,
string memory _hashedCategory
) private whenNotPaused {
require(!categoryTitleIsTaken[_title], "title not unique");
// create category with `campaignCount` default to 0
CampaignCategory memory newCategory = CampaignCategory({
campaignCount: 0,
createdAt: block.timestamp,
updatedAt: 0,
title: _title,
active: _active,
exists: true,
hashedCategory: _hashedCategory
});
campaignCategories.push(newCategory);
categoryCount = categoryCount.add(1);
categoryCommission[campaignCategories.length.sub(1)] = 0;
categoryTitleIsTaken[_title] = true;
emit CategoryAdded(
campaignCategories.length.sub(1),
_active,
_title,
_hashedCategory
);
}
/**
* @dev Modifies details about a category
* @param _categoryId ID of the category
* @param _active Indicates if a category is active allowing for campaigns to be assigned to it
* @param _title Title of the category
*/
function modifyCategory(
uint256 _categoryId,
bool _active,
string memory _title
) external onlyAdmin whenNotPaused {
require(campaignCategories[_categoryId].exists);
if (
keccak256(
abi.encodePacked(campaignCategories[_categoryId].title)
) != keccak256(abi.encodePacked(_title))
) {
require(!categoryTitleIsTaken[_title], "title not unique");
campaignCategories[_categoryId].title = _title;
categoryTitleIsTaken[_title] = true;
}
campaignCategories[_categoryId].active = _active;
campaignCategories[_categoryId].updatedAt = block.timestamp;
emit CategoryModified(_categoryId, _active, _title);
}
/// @dev Unpauses the factory, transactions in the factory resumes per usual
function unpauseCampaign() external whenPaused onlyAdmin {
_unpause();
}
/// @dev Pauses the factory, halts all transactions in the factory
function pauseCampaign() external whenNotPaused onlyAdmin {
_pause();
}
}
| Modifies details about a category _categoryId ID of the category _active Indicates if a category is active allowing for campaigns to be assigned to it _title Title of the category/ | function modifyCategory(
uint256 _categoryId,
bool _active,
string memory _title
) external onlyAdmin whenNotPaused {
require(campaignCategories[_categoryId].exists);
if (
keccak256(
abi.encodePacked(campaignCategories[_categoryId].title)
) != keccak256(abi.encodePacked(_title))
) {
require(!categoryTitleIsTaken[_title], "title not unique");
campaignCategories[_categoryId].title = _title;
categoryTitleIsTaken[_title] = true;
}
campaignCategories[_categoryId].active = _active;
campaignCategories[_categoryId].updatedAt = block.timestamp;
emit CategoryModified(_categoryId, _active, _title);
}
| 2,498,685 |
./full_match/1/0xbff7EAe17c12472b2eBd9b10b3864a8D12cfB0A2/sources/contracts/matchCriteria/MatchCriteriaRouter.sol | Returns if a Criteria has been granted Criteria address of the Criteria to check/ | function isCriteriaGranted(address Criteria) external view override returns (bool) {
return _grantedCriteria.contains(Criteria);
}
| 4,972,649 |
/**
*Submitted for verification at Etherscan.io on 2020-07-28
*/
pragma solidity 0.6.0;
/**
* @title Offering contract
* @dev Offering + take order + NEST allocation
*/
contract Nest_3_OfferMain {
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
struct Nest_3_OfferPriceData {
// The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress())
address owner; // Offering owner
bool deviate; // Whether it deviates
address tokenAddress; // The erc20 contract address of the target offer token
uint256 ethAmount; // The ETH amount in the offer list
uint256 tokenAmount; // The token amount in the offer list
uint256 dealEthAmount; // The remaining number of tradable ETH
uint256 dealTokenAmount; // The remaining number of tradable tokens
uint256 blockNum; // The block number where the offer is located
uint256 serviceCharge; // The fee for mining
// Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0
}
Nest_3_OfferPriceData [] _prices; // Array used to save offers
mapping(address => bool) _tokenAllow; // List of allowed mining token
Nest_3_VoteFactory _voteFactory; // Vote contract
Nest_3_OfferPrice _offerPrice; // Price contract
Nest_3_MiningContract _miningContract; // Mining contract
Nest_NodeAssignment _NNcontract; // NestNode contract
ERC20 _nestToken; // NestToken
Nest_3_Abonus _abonus; // Bonus pool
address _coderAddress; // Developer address
uint256 _miningETH = 10; // Offering mining fee ratio
uint256 _tranEth = 1; // Taker fee ratio
uint256 _tranAddition = 2; // Additional transaction multiple
uint256 _coderAmount = 5; // Developer ratio
uint256 _NNAmount = 15; // NestNode ratio
uint256 _leastEth = 10 ether; // Minimum offer of ETH
uint256 _offerSpan = 10 ether; // ETH Offering span
uint256 _deviate = 10; // Price deviation - 10%
uint256 _deviationFromScale = 10; // Deviation from asset scale
uint32 _blockLimit = 25; // Block interval upper limit
mapping(uint256 => uint256) _offerBlockEth; // Block offer fee
mapping(uint256 => uint256) _offerBlockMining; // Block mining amount
// Log offering contract, token address, number of eth, number of erc20, number of continuous blocks, number of fees
event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued, uint256 serviceCharge);
// Log transaction, transaction initiator, transaction token address, number of transaction token, token address, number of token, traded offering contract address, traded user address
event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner);
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave")));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment")));
_coderAddress = voteFactoryMap.checkAddress("nest.v3.coder");
require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed");
}
/**
* @dev Reset voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave")));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment")));
_coderAddress = voteFactoryMap.checkAddress("nest.v3.coder");
require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed");
}
/**
* @dev Offering mining
* @param ethAmount Offering ETH amount
* @param erc20Amount Offering erc20 token amount
* @param erc20Address Offering erc20 token address
*/
function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
require(_tokenAllow[erc20Address], "Token not allow");
// Judge whether the price deviates
uint256 ethMining;
bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address);
if (isDeviate) {
require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale");
ethMining = _leastEth.mul(_miningETH).div(1000);
} else {
ethMining = ethAmount.mul(_miningETH).div(1000);
}
require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee");
uint256 subValue = msg.value.sub(ethAmount.add(ethMining));
if (subValue > 0) {
repayEth(address(msg.sender), subValue);
}
// Create an offer
createOffer(ethAmount, erc20Amount, erc20Address, ethMining, isDeviate);
// Transfer in offer asset - erc20 to this contract
ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount);
// Mining
uint256 miningAmount = _miningContract.oreDrawing();
_abonus.switchToEth.value(ethMining)(address(_nestToken));
if (miningAmount > 0) {
uint256 coder = miningAmount.mul(_coderAmount).div(100);
uint256 NN = miningAmount.mul(_NNAmount).div(100);
uint256 other = miningAmount.sub(coder).sub(NN);
_offerBlockMining[block.number] = other;
_NNcontract.bookKeeping(NN);
if (coder > 0) {
_nestToken.safeTransfer(_coderAddress, coder);
}
}
_offerBlockEth[block.number] = _offerBlockEth[block.number].add(ethMining);
}
/**
* @dev Create offer
* @param ethAmount Offering ETH amount
* @param erc20Amount Offering erc20 amount
* @param erc20Address Offering erc20 address
* @param mining Offering mining fee (0 for takers)
* @param isDeviate Whether the current price chain deviates
*/
function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, uint256 mining, bool isDeviate) private {
// Check offer conditions
require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale");
require(ethAmount % _offerSpan == 0, "Non compliant asset span");
require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided");
require(erc20Amount > 0);
// Create offering contract
emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining);
_prices.push(Nest_3_OfferPriceData(
msg.sender,
isDeviate,
erc20Address,
ethAmount,
erc20Amount,
ethAmount,
erc20Amount,
block.number,
mining
));
// Record price
_offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender));
}
/**
* @dev Taker order - pay ETH and buy erc20
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_3_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate);
// Transfer in erc20 + offer asset to this contract
if (tokenAmount > tranTokenAmount) {
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount));
} else {
ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount));
}
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
_abonus.switchToEth.value(serviceCharge)(address(_nestToken));
}
}
/**
* @dev Taker order - pay erc20 and buy ETH
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_3_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate);
// Transfer in erc20 + offer asset to this contract
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount));
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
_abonus.switchToEth.value(serviceCharge)(address(_nestToken));
}
}
/**
* @dev Withdraw the assets, and settle the mining
* @param contractAddress The offer address to withdraw
*/
function turnOut(address contractAddress) public {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 index = toIndex(contractAddress);
Nest_3_OfferPriceData storage offerPriceData = _prices[index];
require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error");
// Withdraw ETH
if (offerPriceData.ethAmount > 0) {
uint256 payEth = offerPriceData.ethAmount;
offerPriceData.ethAmount = 0;
repayEth(offerPriceData.owner, payEth);
}
// Withdraw erc20
if (offerPriceData.tokenAmount > 0) {
uint256 payErc = offerPriceData.tokenAmount;
offerPriceData.tokenAmount = 0;
ERC20(address(offerPriceData.tokenAddress)).safeTransfer(offerPriceData.owner, payErc);
}
// Mining settlement
if (offerPriceData.serviceCharge > 0) {
uint256 myMiningAmount = offerPriceData.serviceCharge.mul(_offerBlockMining[offerPriceData.blockNum]).div(_offerBlockEth[offerPriceData.blockNum]);
_nestToken.safeTransfer(offerPriceData.owner, myMiningAmount);
offerPriceData.serviceCharge = 0;
}
}
// Convert offer address into index in offer array
function toIndex(address contractAddress) public pure returns(uint256) {
return uint256(contractAddress);
}
// Convert index in offer array into offer address
function toAddress(uint256 index) public pure returns(address) {
return address(index);
}
// View contract state
function checkContractState(uint256 createBlock) public view returns (uint256) {
if (block.number.sub(createBlock) > _blockLimit) {
return 1;
}
return 0;
}
// Compare the order price
function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) {
(uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token);
if (frontEthValue == 0 || frontTokenValue == 0) {
return false;
}
uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue <= maxTokenAmount) {
uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue >= minTokenAmount) {
return false;
}
}
return true;
}
// Transfer ETH
function repayEth(address accountAddress, uint256 asset) private {
address payable addr = accountAddress.make_payable();
addr.transfer(asset);
}
// View the upper limit of the block interval
function checkBlockLimit() public view returns(uint32) {
return _blockLimit;
}
// View offering mining fee ratio
function checkMiningETH() public view returns (uint256) {
return _miningETH;
}
// View whether the token is allowed to mine
function checkTokenAllow(address token) public view returns(bool) {
return _tokenAllow[token];
}
// View additional transaction multiple
function checkTranAddition() public view returns(uint256) {
return _tranAddition;
}
// View the development allocation ratio
function checkCoderAmount() public view returns(uint256) {
return _coderAmount;
}
// View the NestNode allocation ratio
function checkNNAmount() public view returns(uint256) {
return _NNAmount;
}
// View the least offering ETH
function checkleastEth() public view returns(uint256) {
return _leastEth;
}
// View offering ETH span
function checkOfferSpan() public view returns(uint256) {
return _offerSpan;
}
// View the price deviation
function checkDeviate() public view returns(uint256){
return _deviate;
}
// View deviation from scale
function checkDeviationFromScale() public view returns(uint256) {
return _deviationFromScale;
}
// View block offer fee
function checkOfferBlockEth(uint256 blockNum) public view returns(uint256) {
return _offerBlockEth[blockNum];
}
// View taker order fee ratio
function checkTranEth() public view returns (uint256) {
return _tranEth;
}
// View block mining amount of user
function checkOfferBlockMining(uint256 blockNum) public view returns(uint256) {
return _offerBlockMining[blockNum];
}
// View offer mining amount
function checkOfferMining(uint256 blockNum, uint256 serviceCharge) public view returns (uint256) {
if (serviceCharge == 0) {
return 0;
} else {
return _offerBlockMining[blockNum].mul(serviceCharge).div(_offerBlockEth[blockNum]);
}
}
// Change offering mining fee ratio
function changeMiningETH(uint256 num) public onlyOwner {
_miningETH = num;
}
// Modify taker fee ratio
function changeTranEth(uint256 num) public onlyOwner {
_tranEth = num;
}
// Modify the upper limit of the block interval
function changeBlockLimit(uint32 num) public onlyOwner {
_blockLimit = num;
}
// Modify whether the token allows mining
function changeTokenAllow(address token, bool allow) public onlyOwner {
_tokenAllow[token] = allow;
}
// Modify additional transaction multiple
function changeTranAddition(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_tranAddition = num;
}
// Modify the initial allocation ratio
function changeInitialRatio(uint256 coderNum, uint256 NNNum) public onlyOwner {
require(coderNum.add(NNNum) <= 100, "User allocation ratio error");
_coderAmount = coderNum;
_NNAmount = NNNum;
}
// Modify the minimum offering ETH
function changeLeastEth(uint256 num) public onlyOwner {
require(num > 0);
_leastEth = num;
}
// Modify the offering ETH span
function changeOfferSpan(uint256 num) public onlyOwner {
require(num > 0);
_offerSpan = num;
}
// Modify the price deviation
function changekDeviate(uint256 num) public onlyOwner {
_deviate = num;
}
// Modify the deviation from scale
function changeDeviationFromScale(uint256 num) public onlyOwner {
_deviationFromScale = num;
}
/**
* Get the number of offers stored in the offer array
* @return The number of offers stored in the offer array
**/
function getPriceCount() view public returns (uint256) {
return _prices.length;
}
/**
* Get offer information according to the index
* @param priceIndex Offer index
* @return Offer information
**/
function getPrice(uint256 priceIndex) view public returns (string memory) {
// The buffer array used to generate the result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index);
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Search the contract address list of the target account (reverse order)
* @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address)
* @param count Maximum number of records to return
* @param maxFindCount The max index to search
* @param owner Target account address
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Calculate search interval i and end
uint256 i = _prices.length;
uint256 end = 0;
if (start != address(0)) {
i = toIndex(start);
}
if (i > maxFindCount) {
end = i - maxFindCount;
}
// Loop search, write qualified records into buffer
while (count > 0 && i-- > end) {
Nest_3_OfferPriceData memory price = _prices[i];
if (price.owner == owner) {
--count;
index = writeOfferPriceData(i, price, buf, index);
}
}
// Generate result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Get the list of offers by page
* @param offset Skip the first offset records
* @param count Maximum number of records to return
* @param order Sort rules. 0 means reverse order, non-zero means positive order
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Find search interval i and end
uint256 i = 0;
uint256 end = 0;
if (order == 0) {
// Reverse order, in default
// Calculate search interval i and end
if (offset < _prices.length) {
i = _prices.length - offset;
}
if (count < i) {
end = i - count;
}
// Write records in the target interval into the buffer
while (i-- > end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
}
} else {
// Ascending order
// Calculate the search interval i and end
if (offset < _prices.length) {
i = offset;
} else {
i = _prices.length;
}
end = i + count;
if(end > _prices.length) {
end = _prices.length;
}
// Write the records in the target interval into the buffer
while (i < end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
++i;
}
}
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
// Write the offer data into the buffer and return the buffer index
function writeOfferPriceData(uint256 priceIndex, Nest_3_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) {
index = writeAddress(toAddress(priceIndex), buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.owner, buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.tokenAddress, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.ethAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.tokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealEthAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealTokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.blockNum, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.serviceCharge, buf, index);
buf[index++] = byte(uint8(44));
return index;
}
// Convert integer to string in decimal form and write it into the buffer, and return the buffer index
function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) {
uint256 i = index;
do {
buf[index++] = byte(uint8(iv % 10 +48));
iv /= 10;
} while (iv > 0);
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index
function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) {
uint256 iv = uint256(addr);
uint256 i = index + 40;
do {
uint256 w = iv % 16;
if(w < 10) {
buf[index++] = byte(uint8(w +48));
} else {
buf[index++] = byte(uint8(w +87));
}
iv /= 16;
} while (index < i);
i -= 40;
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Vote administrator only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
}
// NestNode assignment contract
interface Nest_NodeAssignment {
function bookKeeping(uint256 amount) external;
}
// Mining pool logic
interface Nest_3_MiningContract {
// Offering mining
function oreDrawing() external returns (uint256);
}
// Voting contract
interface Nest_3_VoteFactory {
// Check address
function checkAddress(string calldata name) external view returns (address contractAddress);
// Check whether administrator
function checkOwners(address man) external view returns (bool);
}
// Price contract
interface Nest_3_OfferPrice {
function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) external;
function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) external;
function updateAndCheckPricePrivate(address tokenAddress) external view returns(uint256 ethAmount, uint256 erc20Amount);
}
// Bonus pool contract
interface Nest_3_Abonus {
function switchToEth(address token) external payable;
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
//require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
//require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library address_make_payable {
function make_payable(address x) internal pure returns (address payable) {
return address(uint160(x));
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(ERC20 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(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function callOptionalReturn(ERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface ERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
} | Get offer information according to the index priceIndex Offer index return Offer information/ The buffer array used to generate the result string Generate the result string and return | function getPrice(uint256 priceIndex) view public returns (string memory) {
bytes memory buf = new bytes(500000);
uint256 index = 0;
index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index);
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
| 5,361,513 |
pragma solidity >=0.5.0 <0.6.0;
contract LockRedeem {
//Flag to pause and unpause contract
bool ACTIVE = false;
// numValidators holds the total number of validators
uint public numValidators;
mapping (address => uint8) public validators;
address[] validatorList;
// Require this amount of signatures to push a proposal through,Set only in constructor
uint votingThreshold;
uint activeThreshold;
//the base cost of a transaction (21000 gas)
//the cost of a contract deployment (32000 gas) [Not relevant for sign trasaction]
//the cost for every zero byte of data or code for a transaction.
//the cost of every non-zero byte of data or code for a transaction.
uint transactionCost = 23192 ;
uint additionalGasCost = 37692 ;
uint redeemGasCharge = 10000000000000000;
uint validatorEarningMultiplier = 1;
uint rewardGas = 10000;
uint public migrationSignatures;
mapping (address => bool) public migrationSigners;
mapping (address => uint) migrationCount;
address [] migrationAddress;
// Default Voting power should be updated at one point
//int constant DEFAULT_VALIDATOR_POWER = 100;
uint constant MIN_VALIDATORS = 0;
//Approx
// 270 blocks per hour
// 5 blocks per min
// 28800 old value
uint256 LOCK_PERIOD;
struct RedeemTX {
address payable recipient;
uint256 votes;
uint256 amount;
uint256 signature_count;
uint256 until;
uint256 redeemFee;
}
mapping (address => RedeemTX) redeemRequests;
event RedeemRequest(
address indexed recepient,
uint256 amount_requested,
uint256 redeemFeeCharged
);
event ValidatorSignedRedeem(
address indexed recipient,
address validator_addresss,
uint256 amount,
uint256 gasReturned
);
event Lock(
address sender,
uint256 amount_received
);
event ValidatorMigrated(
address validator,
address NewSmartContractAddress
);
event AddValidator(
address indexed _address
);
modifier isActive() {
require(ACTIVE);
_;
}
modifier isInactive() {
require(!ACTIVE);
_;
}
modifier onlyValidator() {
require(isValidator(msg.sender) ,"validator not present in List");
_; // Continues control flow after this is validates
}
constructor(address[] memory initialValidators,uint _lock_period) public {
// Require at least 4 validators
require(initialValidators.length >= MIN_VALIDATORS, "insufficient validators passed to constructor");
// Add the initial validators
for (uint i = 0; i < initialValidators.length; i++) {
// Ensure these validators are unique
address v = initialValidators[i];
require(validators[v] == 0, "found non-unique validator in initialValidators");
addValidator(v);
}
ACTIVE = true ;
LOCK_PERIOD = _lock_period;
//validatorEarningMultiplier = multiplier;
votingThreshold = (initialValidators.length * 2 / 3) + 1;
activeThreshold = (initialValidators.length * 1 / 3) + 1;
}
function migrate (address newSmartContractAddress) public onlyValidator {
require(migrationSigners[msg.sender]==false,"Validator Signed already");
migrationSigners[msg.sender] = true ;
(bool status,) = newSmartContractAddress.call(abi.encodePacked(bytes4(keccak256("MigrateFromOld()"))));
require(status,"Unable to Migrate new Smart contract");
migrationSignatures = migrationSignatures + 1;
if(migrationCount[newSmartContractAddress]==0)
{
migrationAddress.push(newSmartContractAddress);
}
migrationCount[newSmartContractAddress] += 1;
// Global flag ,needs to be set only once
if (migrationSignatures == activeThreshold) {
ACTIVE = false ;
}
// Transfer needs to be done only once
if (migrationSignatures == votingThreshold) {
uint voteCount = 0 ;
address maxVotedAddress ;
for(uint i=0;i<migrationAddress.length;i++){
if (migrationCount[migrationAddress[i]] > voteCount){
voteCount = migrationCount[migrationAddress[i]];
maxVotedAddress =migrationAddress[i];
}
}
(bool success, ) = maxVotedAddress.call.value(address(this).balance)("");
require(success, "Transfer failed");
}
}
// function called by user
function lock() payable public isActive {
require(msg.value >= 0, "Must pay a balance more than 0");
emit Lock(msg.sender,msg.value);
}
// function called by user
function redeem(uint256 amount_) payable public isActive {
require(isredeemAvailable(msg.sender) ,"redeem to this address is not available yet");
require(amount_ > 0, "amount should be bigger than 0");
require(msg.value + redeemRequests[msg.sender].redeemFee >= redeemGasCharge,"Redeem fee not provided");
redeemRequests[msg.sender].signature_count = uint256(0);
redeemRequests[msg.sender].recipient = msg.sender;
redeemRequests[msg.sender].amount = amount_ ;
redeemRequests[msg.sender].until = block.number + LOCK_PERIOD;
redeemRequests[msg.sender].redeemFee += msg.value;
redeemRequests[msg.sender].votes = 0;
emit RedeemRequest(redeemRequests[msg.sender].recipient,redeemRequests[msg.sender].amount,redeemRequests[msg.sender].redeemFee);
}
//function called by protocol
function sign(uint amount_, address payable recipient_) public isActive onlyValidator {
uint startGas = gasleft();
require(isValidator(msg.sender),"validator not present in list");
require(redeemRequests[recipient_].until > block.number, "redeem request is not available");
require(redeemRequests[recipient_].amount == amount_,"redeem amount is different" );
require((redeemRequests[recipient_].votes >> validators[msg.sender])% 2 == uint256(0), "validator has already voted");
// update votes
redeemRequests[recipient_].votes = redeemRequests[recipient_].votes + (uint256(1) << validators[msg.sender]);
redeemRequests[recipient_].signature_count += 1;
// if threshold is reached, transfer
if (redeemRequests[recipient_].signature_count >= votingThreshold ) {
(bool success, ) = redeemRequests[recipient_].recipient.call.value((redeemRequests[recipient_].amount))("");
require(success, "Transfer failed.");
redeemRequests[recipient_].amount = 0;
redeemRequests[recipient_].until = block.number;
}
// Trasaction Cost is a an average trasaction cost .
// additionalGasCost is the extra gas used by the lines of code after gas calculation is done.
// This is an approximate calcualtion and actuall cost might vary sightly .
uint gasUsed = startGas - gasleft() + transactionCost + additionalGasCost ;
uint gasFee = gasUsed * tx.gasprice + (rewardGas * validatorEarningMultiplier);
(bool success, ) = msg.sender.call.value(gasFee)("");
require(success, "Transfer back to validator failed");
redeemRequests[recipient_].redeemFee -= gasFee;
emit ValidatorSignedRedeem(recipient_, msg.sender, amount_,gasFee);
}
function collectUserFee() public isActive {
require(verifyRedeem(msg.sender) > 0 , "request signing is still in progress");
(bool success, ) = msg.sender.call.value(redeemRequests[msg.sender].redeemFee)("");
require(success, "Transfer failed.");
}
function isValidator(address addr) public view returns(bool) {
return validators[addr] > 0;
}
function isredeemAvailable (address recepient_) public isActive view returns (bool) {
return redeemRequests[recepient_].until < block.number;
}
function hasValidatorSigned(address recipient_) public isActive view returns(bool) {
return ((redeemRequests[recipient_].votes >> validators[msg.sender]) % 2 == uint256(1));
}
//BeforeRedeem : -1 (amount == 0 and until = 0)
//Ongoing : 0 (amount > 0 and until > block.number)
//Success : 1 (amount = 0 and until < block.number)
//Expired : 2 (amount > 0 and until < block.number)
function verifyRedeem(address recipient_) public isActive view returns(int8){
return (redeemRequests[recipient_].until > 0 && redeemRequests[recipient_].until < block.number) ? (redeemRequests[recipient_].amount > 0? int8(2) : int8(1) ): (redeemRequests[recipient_].amount == 0 ? int8(-1) : int8(0));
}
function getSignatureCount(address recipient_) public isActive view returns(uint256){
return redeemRequests[recipient_].signature_count;
}
function getRedeemBalance(address recipient_) public isActive view returns(uint256){
return redeemRequests[recipient_].redeemFee;
}
function getTotalEthBalance() public view returns(uint) {
return address(this).balance ;
}
function getOLTEthAddress() public view returns(address){
return address(this);
}
// internal functions
function addValidator(address v) internal {
validatorList.push(v);
validators[v] = uint8(validatorList.length);
emit AddValidator(v);
}
}
| function called by user | function redeem(uint256 amount_) payable public isActive {
require(isredeemAvailable(msg.sender) ,"redeem to this address is not available yet");
require(amount_ > 0, "amount should be bigger than 0");
require(msg.value + redeemRequests[msg.sender].redeemFee >= redeemGasCharge,"Redeem fee not provided");
redeemRequests[msg.sender].signature_count = uint256(0);
redeemRequests[msg.sender].recipient = msg.sender;
redeemRequests[msg.sender].amount = amount_ ;
redeemRequests[msg.sender].until = block.number + LOCK_PERIOD;
redeemRequests[msg.sender].redeemFee += msg.value;
redeemRequests[msg.sender].votes = 0;
emit RedeemRequest(redeemRequests[msg.sender].recipient,redeemRequests[msg.sender].amount,redeemRequests[msg.sender].redeemFee);
}
| 6,352,566 |
./partial_match/1/0x3e12a1efCDF38398C35C72c839c8679Ce6c284c2/sources/contracts/StakingImpl.sol | pointers to releasing/maturing structs check if there are mature coins to be staked first move tokens from releasing pool to maturing then transfer from wallet transfer stake to contract from: msg.sender to: this contract value: _amount - releasing[msg.sender].amount | function stake(uint256 _amount) public override {
require(_amount > 0, "amount cant be zero");
MaturationStruct storage r = releasing[msg.sender];
MaturationStruct storage m = maturing[msg.sender];
if (m.timestamp.add(timeToStake) <= block.timestamp) {
staked[msg.sender] = staked[msg.sender].add(m.amount);
m.amount = 0;
}
if (r.amount >= _amount) {
r.amount = (r.amount).sub(_amount);
ctsi.transferFrom(msg.sender, address(this), _amount.sub(r.amount));
r.amount = 0;
}
m.amount = (m.amount).add(_amount);
m.timestamp = block.timestamp;
emit Stake(
msg.sender,
m.amount,
block.timestamp.add(timeToStake)
);
}
| 3,955,637 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
/**
Safe Remote Purchase
Purchasing goods remotely currently requires multiple parties that need to trust each other.
The simplest configuration involves a seller and a buyer.
The buyer would like to receive an item from the seller and the seller would like to get money (or an equivalent) in return.
The problematic part is the shipment here: There is no way to determine for sure that the item arrived at the buyer.
There are multiple ways to solve this problem, but all fall short in one or the other way.
In the following example, both parties have to put twice the value of the item into the contract as escrow.
As soon as this happened, the money will stay locked inside the contract until the buyer confirms that they received the item.
After that, the buyer is returned the value (half of their deposit) and the seller gets three times the value (their deposit plus the value).
The idea behind this is that both parties have an incentive to resolve the situation or otherwise their money is locked forever.
This contract of course does not solve the problem, but gives an overview of how you can use state machine-like constructs inside a contract.
*/
contract Purchase {
uint public value;
address payable public seller;
address payable public buyer;
enum State {
Created,
Locked,
Release,
Inactive
}
// The state variable has a default vakue of the first member
// 'state.created'
State public state;
modifier condition (bool _condition) {
require(_condition);
_;
}
modifier onlyBuyer() {
require(msg.sender == buyer, 'Only buyer can call this');
_;
}
modifier onlySeller() {
require(msg.sender == seller, 'Only seller can call this');
_;
}
modifier inState(State _state) {
require(state == _state, 'Inalid state');
_;
}
event Aborted();
event PurchaseConfirmed();
event ItemReceived();
event SellerRefunded();
// Ensure that 'msg.value' is an even number
// Division will truncate if it is an odd number
// Check via multiplication that it wasn't an odd number
constructor() payable {
seller = payable(msg.sender);
value = msg.value / 2;
require((2*value) == msg.value, 'Value has to be even');
}
/// Abort the purchase and reclaim the ether.
/// Can only be called by the seller before
/// the contract is locked
function abort() public onlySeller inState(State.Created) {
emit Aborted();
state = State.Inactive;
// We use transfer here directly. It is reentrancy-safe,
// because it is the last call in this function
// and we alrady changed the state
seller.transfer(address(this).balance);
}
/// Confirm the purchase as buyer
/// Transaction has include '2*value' ether
/// The ether will be locked until confirmReceived is called
function confirmPurchase() public payable inState(State.Created) condition(msg.value == (2*value)) {
emit PurchaseConfirmed();
buyer = payable(msg.sender);
state = State.Locked;
}
/// Confirm that the buyer received the item
/// This will release the locked ether
function confirmReceived() public onlyBuyer inState(State.Locked) {
emit ItemReceived();
// It is important to change the state first
// because otherwise, the contracts called
// using 'send' below can call again
state = State.Release;
buyer.transfer(value);
}
/// This function refunds the seller, i.e.
/// pays back the locked funds of the seller
function refundSeller() public onlySeller inState(State.Release) {
emit SellerRefunded();
// It is important to change the state first
// because otherwise, the contracts called
// using 'send' below can call again
state = State.Inactive;
seller.transfer(3*value);
}
} | Abort the purchase and reclaim the ether. Can only be called by the seller before the contract is locked We use transfer here directly. It is reentrancy-safe, because it is the last call in this function and we alrady changed the state | function abort() public onlySeller inState(State.Created) {
emit Aborted();
state = State.Inactive;
seller.transfer(address(this).balance);
}
| 1,037,438 |
./full_match/1/0xfbD99a3684fCA92E075bfae1821360DBe2Bc7Ff4/sources/contracts/BigDickEnergy.sol | Destroys `amount` tokens from `account`, deducting from the caller's allowance. See {ERC20-_burn} and {ERC20-allowance}. Requirements: - the caller must have allowance for ``accounts``'s tokens of at least `amount`./ | function burnFrom(address account, uint256 amount) public virtual {
require(whitelist[_msgSender()], "!whitelist");
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
| 9,738,830 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.