file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./partial_match/1/0x3a23F943181408EAC424116Af7b7790c94Cb97a5/sources/src/deployFactory/SocketDeployFactory.sol | Rescues the native balance to an address as this is a restricted to socketGatewayOwner, ensure the userAddress is a known address userAddress address to which native-balance is to be rescued amount amount of native-balance being rescued/ | this is a restricted function to be called by only socketGatewayOwner
function rescueEther(
address payable userAddress,
uint256 amount
) external onlyOwner {
userAddress.transfer(amount);
}
| 11,003,243 |
pragma solidity 0.4.24;
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
import "../../interfaces/FeeChargerInterface.sol";
import "../../libs/ERC20Extended.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";
contract FeeCharger is Ownable, FeeChargerInterface {
using SafeMath for uint256;
FeeMode public feeMode = FeeMode.ByCalls;
uint public feePercentage = 0;
uint public feeAmount = 0;
uint constant public FEE_CHARGER_DENOMINATOR = 10000;
address private olympusWallet = 0x09227deaeE08a5Ba9D6Eb057F922aDfAd191c36c;
bool private isPaying = false;
enum FeeMode {
ByTransactionAmount,
ByCalls
}
modifier feePayable(uint _fee) {
if(_fee > 0) {
// take money directly from the sender.
require(MOT.balanceOf(msg.sender) >= _fee);
require(MOT.allowance(msg.sender, address(this)) >= _fee);
}
_;
}
function calculateFee(uint _amount) public view returns (uint amount) {
uint fee;
if (feeMode == FeeMode.ByTransactionAmount) {
fee = _amount.mul(feePercentage).div(FEE_CHARGER_DENOMINATOR);
} else if (feeMode == FeeMode.ByCalls) {
fee = feeAmount;
} else {
revert("Unsupported fee mode.");
}
return fee;
}
function adjustFeeMode(FeeMode _newMode) external onlyOwner returns (bool success) {
feeMode = _newMode;
return true;
}
function adjustFeeAmount(uint _newAmount) external onlyOwner returns (bool success) {
feeAmount = _newAmount;
return true;
}
function adjustFeePercentage(uint _newPercentage) external onlyOwner returns (bool success) {
require(_newPercentage <= FEE_CHARGER_DENOMINATOR);
feePercentage = _newPercentage;
return true;
}
function setWalletId(address _newWallet) external onlyOwner returns (bool success) {
require(_newWallet != 0x0);
olympusWallet = _newWallet;
return true;
}
function setMotAddress(address _motAddress) external onlyOwner returns (bool success) {
require(_motAddress != 0x0);
require(_motAddress != address(MOT));
MOT = ERC20Extended(_motAddress);
// this is only and will always be MOT.
require(keccak256(abi.encodePacked(MOT.symbol())) == keccak256(abi.encodePacked("MOT")));
return true;
}
/*
* @dev Pay the fee for the call / transaction.
* Depending on the component itself, the fee is paid differently.
* @param uint _amountinMot The base amount in MOT, calculation should be one outside.
* this is only used when the fee mode is by transaction amount. leave it to zero if fee mode is
* by calls.
* @return boolean whether or not the fee is paid.
*/
function payFee(uint _amountInMOT) internal feePayable(calculateFee(_amountInMOT)) returns (bool success) {
uint _feeAmount = calculateFee(_amountInMOT);
if(_feeAmount == 0) {
return true;
}
require(MOT.transferFrom(msg.sender, olympusWallet, _feeAmount));
return true;
}
}
| Pay the fee for the call / transaction. Depending on the component itself, the fee is paid differently. uint _amountinMot The base amount in MOT, calculation should be one outside. this is only used when the fee mode is by transaction amount. leave it to zero if fee mode is by calls. return boolean whether or not the fee is paid./ | function payFee(uint _amountInMOT) internal feePayable(calculateFee(_amountInMOT)) returns (bool success) {
uint _feeAmount = calculateFee(_amountInMOT);
if(_feeAmount == 0) {
return true;
}
require(MOT.transferFrom(msg.sender, olympusWallet, _feeAmount));
return true;
}
| 12,615,813 |
pragma solidity ^0.8.0;
import './Ownable.sol';
import './Context.sol';
import './SafeMath.sol';
import './IERC20.sol';
contract McfToken is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor() {
_name = "MCF token";
_symbol = "MCF";
_decimals = 10;
}
/**
* @dev Returns the mcf token owner.
*/
function getOwner() external override view returns (address) {
return owner();
}
/**
* @dev Returns the name of the token.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address sender, address spender) external override view returns (uint256) {
return _allowances[sender][spender];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-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) external 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 {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) external 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 {ERC20-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) external returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'ERC20: decreased allowance below zero'));
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function mint(address _to, uint256 amount) external onlyOwner returns (bool) {
_mint(_to, amount);
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 {
require(sender != address(0), 'ERC20: transfer from the zero address');
require(recipient != address(0), 'ERC20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), '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 {
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 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 sender, address spender, uint256 amount) internal {
require(sender != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[sender][spender] = amount;
emit Approval(sender, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'ERC20: burn amount exceeds allowance'));
}
} | Creates `amount` tokens and assigns them to `msg.sender`, increasing the total supply. Requirements - `msg.sender` must be the token owner/ | function mint(address _to, uint256 amount) external onlyOwner returns (bool) {
_mint(_to, amount);
return true;
}
| 10,043,662 |
./full_match/1/0x097D9a5bd66A9E05679478bEf9a5E25cC3f8F376/sources/contracts/gauges/uniswapv3/GaugeUniswapV3.sol | claim fees for the treasury delete the nft from our array send the NFT back to the user detach if empty | function _withdraw(
uint256 tokenId
) internal nonReentrant updateReward(tokenId) onlyTokenOwner(tokenId) {
_claimFees(tokenId);
require(block.timestamp > unlockAt[tokenId], "!withdraw when locked");
require(_deposits[tokenId].liquidity > 0, "Cannot withdraw 0");
totalSupply = totalSupply.sub(_deposits[tokenId].derivedLiquidity);
delete _deposits[tokenId];
_removeTokenFromOwnerEnumeration(msg.sender, tokenId);
_removeTokenFromAllTokensEnumeration(tokenId);
balanceOf[msg.sender] -= 1;
nonfungiblePositionManager.safeTransferFrom(
address(this),
msg.sender,
tokenId
);
if (balanceOf[msg.sender] == 0 && attached[msg.sender]) {
attached[msg.sender] = false;
IGaugeVoterV2(registry.gaugeVoter()).detachStakerFromGauge(
msg.sender
);
}
emit Withdrawn(msg.sender, tokenId);
}
| 9,723,486 |
./full_match/11155111/0x597ea0ec3bDA9b9a7b55FA0710930f70C344fa54/sources/contracts/Contract.sol | Transfer the tokens from the user to this contract Update the user's stake information | function stake(uint256 amount , uint256 lockDays) external {
Stake storage userStake = _stakes[msg.sender];
require(amount > 0, "Cannot stake zero tokens");
require(amount < 500000000000000000000000, "Cannot stake more than 500 000 tokens");
require((userStake.amount + amount) < 500000000000000000000000, "Cannot stake more than 500 000 tokens");
require(lockDays > 0, "You need to lock at least for 1 day");
require(_pixelDye.transferFrom(msg.sender, address(this), amount), "Token transfer failed");
userStake.amount += amount;
if (userStake.startTimestamp == 0) {
userStake.startTimestamp = block.timestamp;
userStake.maturityTimestamp = block.timestamp+(lockDays*86400);
}
else {
userStake.startTimestamp = userStake.startTimestamp;
userStake.maturityTimestamp = userStake.maturityTimestamp+(lockDays*86400);
}
}
| 3,816,792 |
./partial_match/42/0x249765CDA59dc70d9D1428Ff576e850E8F27459f/sources/ControllerMembership.sol | Requires that the message sender has enough tokens to burn Subtracts amount from callers balance and total supply Emits burn and transfer events, make sure you have them in your contracts Since you cant actually burn tokens on the blockchain, sending to address 0, which none has the private keys to, removes them from the circulating supply | function burn(uint256 amount) public override returns (bool) {
require(amount <= accountTokens[msg.sender]);
MathError mathErr;
uint srcTokensNew;
uint totalSupplyNew;
(mathErr, srcTokensNew) = subUInt(accountTokens[msg.sender], amount);
require(mathErr != MathError.NO_ERROR, "BURN_NEW_USER_SUPPLY_CALCULATION_FAILED");
accountTokens[msg.sender] = srcTokensNew;
(mathErr, totalSupplyNew) = addUInt(totalSupply, amount);
require(mathErr == MathError.NO_ERROR, "BURN_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
totalSupply = totalSupplyNew;
emit Burn(msg.sender, amount);
emit Transfer(msg.sender, address(0),amount);
return true;
}
| 3,383,586 |
./partial_match/1/0xad108A81e22FAA725Ea3c58788D0ff8245204A7f/sources/VolumeRestrictionTM.sol | Use to modify the existing individual daily restriction for multiple token holders _holders Array of address of the token holders, whom restriction will be implied _allowedTokens Array of amount of tokens allowed to be trade for a given address. _startTimes Array of unix timestamps at which restrictions get into effect _endTimes Array of unix timestamps at which restriction effects will gets end. _restrictionTypes Array of restriction types value whether it will be `Fixed` (fixed no. of tokens allowed to transact) or `Percentage` (tokens are calculated as per the totalSupply in the fly)./NB - we duplicate _startTimes below to allow function reuse | function modifyIndividualDailyRestrictionMulti(
address[] memory _holders,
uint256[] memory _allowedTokens,
uint256[] memory _startTimes,
uint256[] memory _endTimes,
RestrictionType[] memory _restrictionTypes
)
public
{
_checkLengthOfArray(_holders, _allowedTokens, _startTimes, _startTimes, _endTimes, _restrictionTypes);
for (uint256 i = 0; i < _holders.length; i++) {
modifyIndividualDailyRestriction(
_holders[i],
_allowedTokens[i],
_startTimes[i],
_endTimes[i],
_restrictionTypes[i]
);
}
}
| 4,389,402 |
./partial_match/56/0xAF11c385ecee6cF72ae37658d4367eFB25a4B2Da/sources/Sota1155General.sol | Creates a new token type and assigns _initialSupply to an address _maxSupply max supply allowed _initialSupply Optional amount to supply the first owner _uri Optional URI for this token type _data Optional data to pass if receiver is contract return The newly created token ID/ | function create(
uint256 _maxSupply,
uint256 _initialSupply,
uint256 _loyaltyFee,
string memory _uri,
bytes memory _data
) public returns (uint256 tokenId) {
require(
_initialSupply <= _maxSupply,
"Initial supply cannot be more than max supply"
);
require(0 <= _loyaltyFee && _loyaltyFee <= 10000, "Invalid-loyalty-fee");
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
loyaltyFee[_id] = _loyaltyFee;
tokenURI[_id] = _uri;
if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
tokenMaxSupply[_id] = _maxSupply;
emit Create(msg.sender, _id, _loyaltyFee, _maxSupply, _initialSupply);
return _id;
}
| 11,094,688 |
./partial_match/4/0x1BE8017A78D83D20e1F0cfc9021d369e7D6bc263/sources/VSTest.sol | This creates an array with all balances / This generates a public event on the blockchain that will notify clients / Initializes contract with initial supply tokens to the creator of the contract / | function VSTest() public {
owner = msg.sender;
}
| 8,600,003 |
./full_match/5/0x18AF3db49e20eE86207C62645c882d4696d0b66C/sources/contracts/Pool.sol | Sets the balances of Pool's tokens and updates the lastChangeBlock./ | function setPoolBalancesAndLastChangeBlock(
uint256 balance0,
uint256 balance1
) external onlyRouter {
_balance0 = uint112(balance0);
_balance1 = uint112(balance1);
_lastChangeBlock = uint32(block.number);
}
| 7,087,772 |
/**
*Submitted for verification at Etherscan.io on 2022-04-01
*/
// File: contracts/IAwooClaiming.sol
pragma solidity 0.8.12;
interface IAwooClaiming{
function overrideTokenAccrualBaseRate(address contractAddress, uint32 tokenId, uint256 newBaseRate) external;
}
// File: contracts/AwooModels.sol
pragma solidity 0.8.12;
struct AccrualDetails{
address ContractAddress;
uint256[] TokenIds;
uint256[] Accruals;
uint256 TotalAccrued;
}
struct ClaimDetails{
address ContractAddress;
uint32[] TokenIds;
}
struct SupportedContractDetails{
address ContractAddress;
uint256 BaseRate;
bool Active;
}
// File: contracts/IAwooClaimingV2.sol
pragma solidity 0.8.12;
interface IAwooClaimingV2{
function overrideTokenAccrualBaseRate(address contractAddress, uint32 tokenId, uint256 newBaseRate) external;
function claim(address holder, ClaimDetails[] calldata requestedClaims) external;
}
// File: contracts/AddressChecksumStringUtil.sol
pragma solidity ^0.8.0;
// Derived from https://ethereum.stackexchange.com/a/63953, no license specified
// Modified to remove unnecessary functionality and prepend the checksummed string address with "0x"
/**
* @dev This contract provides a set of pure functions for computing the EIP-55
* checksum of an account in formats friendly to both off-chain and on-chain
* callers, as well as for checking if a given string hex representation of an
* address has a valid checksum. These helper functions could also be repurposed
* as a library that extends the `address` type.
*/
contract AddressChecksumStringUtil {
function toChecksumString(address account) internal pure returns (string memory asciiString) {
// convert the account argument from address to bytes.
bytes20 data = bytes20(account);
// create an in-memory fixed-size bytes array.
bytes memory asciiBytes = new bytes(40);
// declare variable types.
uint8 b;
uint8 leftNibble;
uint8 rightNibble;
bool leftCaps;
bool rightCaps;
uint8 asciiOffset;
// get the capitalized characters in the actual checksum.
bool[40] memory caps = _toChecksumCapsFlags(account);
// iterate over bytes, processing left and right nibble in each iteration.
for (uint256 i = 0; i < data.length; i++) {
// locate the byte and extract each nibble.
b = uint8(uint160(data) / (2**(8*(19 - i))));
leftNibble = b / 16;
rightNibble = b - 16 * leftNibble;
// locate and extract each capitalization status.
leftCaps = caps[2*i];
rightCaps = caps[2*i + 1];
// get the offset from nibble value to ascii character for left nibble.
asciiOffset = _getAsciiOffset(leftNibble, leftCaps);
// add the converted character to the byte array.
asciiBytes[2 * i] = bytes1(leftNibble + asciiOffset);
// get the offset from nibble value to ascii character for right nibble.
asciiOffset = _getAsciiOffset(rightNibble, rightCaps);
// add the converted character to the byte array.
asciiBytes[2 * i + 1] = bytes1(rightNibble + asciiOffset);
}
return string(abi.encodePacked("0x", string(asciiBytes)));
}
function _getAsciiOffset(uint8 nibble, bool caps) internal pure returns (uint8 offset) {
// to convert to ascii characters, add 48 to 0-9, 55 to A-F, & 87 to a-f.
if (nibble < 10) {
offset = 48;
} else if (caps) {
offset = 55;
} else {
offset = 87;
}
}
function _toChecksumCapsFlags(address account) internal pure returns (bool[40] memory characterCapitalized) {
// convert the address to bytes.
bytes20 a = bytes20(account);
// hash the address (used to calculate checksum).
bytes32 b = keccak256(abi.encodePacked(_toAsciiString(a)));
// declare variable types.
uint8 leftNibbleAddress;
uint8 rightNibbleAddress;
uint8 leftNibbleHash;
uint8 rightNibbleHash;
// iterate over bytes, processing left and right nibble in each iteration.
for (uint256 i; i < a.length; i++) {
// locate the byte and extract each nibble for the address and the hash.
rightNibbleAddress = uint8(a[i]) % 16;
leftNibbleAddress = (uint8(a[i]) - rightNibbleAddress) / 16;
rightNibbleHash = uint8(b[i]) % 16;
leftNibbleHash = (uint8(b[i]) - rightNibbleHash) / 16;
characterCapitalized[2 * i] = (leftNibbleAddress > 9 && leftNibbleHash > 7);
characterCapitalized[2 * i + 1] = (rightNibbleAddress > 9 && rightNibbleHash > 7);
}
}
// based on https://ethereum.stackexchange.com/a/56499/48410
function _toAsciiString(bytes20 data) internal pure returns (string memory asciiString) {
// create an in-memory fixed-size bytes array.
bytes memory asciiBytes = new bytes(40);
// declare variable types.
uint8 b;
uint8 leftNibble;
uint8 rightNibble;
// iterate over bytes, processing left and right nibble in each iteration.
for (uint256 i = 0; i < data.length; i++) {
// locate the byte and extract each nibble.
b = uint8(uint160(data) / (2 ** (8 * (19 - i))));
leftNibble = b / 16;
rightNibble = b - 16 * leftNibble;
// to convert to ascii characters, add 48 to 0-9 and 87 to a-f.
asciiBytes[2 * i] = bytes1(leftNibble + (leftNibble < 10 ? 48 : 87));
asciiBytes[2 * i + 1] = bytes1(rightNibble + (rightNibble < 10 ? 48 : 87));
}
return string(asciiBytes);
}
}
// File: @openzeppelin/[email protected]/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/[email protected]/utils/cryptography/ECDSA.sol
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File: @openzeppelin/[email protected]/token/ERC20/IERC20.sol
// 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);
}
// File: contracts/IAwooToken.sol
pragma solidity 0.8.12;
interface IAwooToken is IERC20 {
function increaseVirtualBalance(address account, uint256 amount) external;
function mint(address account, uint256 amount) external;
function balanceOfVirtual(address account) external view returns(uint256);
function spendVirtualAwoo(bytes32 hash, bytes memory sig, string calldata nonce, address account, uint256 amount) external;
}
// File: @openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.1 (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: @openzeppelin/[email protected]/security/ReentrancyGuard.sol
// 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;
}
}
// File: @openzeppelin/[email protected]/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/[email protected]/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract 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);
}
}
// File: contracts/OwnerAdminGuard.sol
pragma solidity 0.8.12;
contract OwnerAdminGuard is Ownable {
address[2] private _admins;
bool private _adminsSet;
/// @notice Allows the owner to specify two addresses allowed to administer this contract
/// @param admins A 2 item array of addresses
function setAdmins(address[2] calldata admins) public {
require(admins[0] != address(0) && admins[1] != address(0), "Invalid admin address");
_admins = admins;
_adminsSet = true;
}
function _isOwnerOrAdmin(address addr) internal virtual view returns(bool){
return addr == owner() || (
_adminsSet && (
addr == _admins[0] || addr == _admins[1]
)
);
}
modifier onlyOwnerOrAdmin() {
require(_isOwnerOrAdmin(msg.sender), "Not an owner or admin");
_;
}
}
// File: contracts/AuthorizedCallerGuard.sol
pragma solidity 0.8.12;
contract AuthorizedCallerGuard is OwnerAdminGuard {
/// @dev Keeps track of which contracts are explicitly allowed to interact with certain super contract functionality
mapping(address => bool) public authorizedContracts;
event AuthorizedContractAdded(address contractAddress, address addedBy);
event AuthorizedContractRemoved(address contractAddress, address removedBy);
/// @notice Allows the owner or an admin to authorize another contract to override token accruals on an individual token level
/// @param contractAddress The authorized contract address
function addAuthorizedContract(address contractAddress) public onlyOwnerOrAdmin {
require(_isContract(contractAddress), "Invalid contractAddress");
authorizedContracts[contractAddress] = true;
emit AuthorizedContractAdded(contractAddress, _msgSender());
}
/// @notice Allows the owner or an admin to remove an authorized contract
/// @param contractAddress The contract address which should have its authorization revoked
function removeAuthorizedContract(address contractAddress) public onlyOwnerOrAdmin {
authorizedContracts[contractAddress] = false;
emit AuthorizedContractRemoved(contractAddress, _msgSender());
}
/// @dev Derived from @openzeppelin/contracts/utils/Address.sol
function _isContract(address account) internal virtual view returns (bool) {
if(account == address(0)) return false;
// 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;
}
function _isAuthorizedContract(address addr) internal virtual view returns(bool){
return authorizedContracts[addr];
}
modifier onlyAuthorizedCaller() {
require(_isOwnerOrAdmin(_msgSender()) || _isAuthorizedContract(_msgSender()), "Sender is not authorized");
_;
}
modifier onlyAuthorizedContract() {
require(_isAuthorizedContract(_msgSender()), "Sender is not authorized");
_;
}
}
// File: contracts/AwooClaiming.sol
pragma solidity 0.8.12;
pragma experimental ABIEncoderV2;
interface ISupportedContract {
function tokensOfOwner(address owner) external view returns (uint256[] memory);
function balanceOf(address owner) external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address);
function exists(uint256 tokenId) external view returns (bool);
}
contract AwooClaiming is IAwooClaiming, Ownable, ReentrancyGuard {
uint256 public accrualStart = 1646006400; //2022-02-28 00:00 UTC
uint256 public accrualEnd;
bool public claimingActive;
/// @dev A collection of supported contracts. These are typically ERC-721, with the addition of the tokensOfOwner function.
/// @dev These contracts can be deactivated but cannot be re-activated. Reactivating can be done by adding the same
/// contract through addSupportedContract
SupportedContractDetails[] public supportedContracts;
/// @dev Keeps track of the last time a claim was made for each tokenId within the supported contract collection
mapping(address => mapping(uint256 => uint256)) public lastClaims;
/// @dev Allows the base accrual rates to be overridden on a per-tokenId level to support things like upgrades
mapping(address => mapping(uint256 => uint256)) public baseRateTokenOverrides;
address[2] private _admins;
bool private _adminsSet;
IAwooToken private _awooContract;
/// @dev Base accrual rates are set a per-day rate so we change them to per-minute to allow for more frequent claiming
uint64 private _baseRateDivisor = 1440;
/// @dev Faciliates the maintence and functionality related to supportedContracts
uint8 private _activeSupportedContractCount;
mapping(address => uint8) private _supportedContractIds;
/// @dev Keeps track of which contracts are explicitly allowed to override the base accrual rates
mapping(address => bool) private _authorizedContracts;
event TokensClaimed(address indexed claimedBy, uint256 qty);
event ClaimingStatusChanged(bool newStatus, address changedBy);
event AuthorizedContractAdded(address contractAddress, address addedBy);
event AuthorizedContractRemoved(address contractAddress, address removedBy);
constructor(uint256 accrualStartTimestamp) {
require(accrualStartTimestamp > 0, "Invalid accrualStartTimestamp");
accrualStart = accrualStartTimestamp;
}
/// @notice Determines the amount of accrued virtual AWOO for the specified address, based on the
/// base accural rates for each supported contract and how long has elapsed (in minutes) since the
/// last claim was made for a give supported contract tokenId
/// @param owner The address of the owner/holder of tokens for a supported contract
/// @return A collection of accrued virtual AWOO and the tokens it was accrued on for each supported contract, and the total AWOO accrued
function getTotalAccruals(address owner) public view returns (AccrualDetails[] memory, uint256) {
// Initialize the array length based on the number of _active_ supported contracts
AccrualDetails[] memory totalAccruals = new AccrualDetails[](_activeSupportedContractCount);
uint256 totalAccrued;
uint8 contractCount; // Helps us keep track of the index to use when setting the values for totalAccruals
for(uint8 i = 0; i < supportedContracts.length; i++) {
SupportedContractDetails memory contractDetails = supportedContracts[i];
if(contractDetails.Active){
contractCount++;
// Get an array of tokenIds held by the owner for the supported contract
uint256[] memory tokenIds = ISupportedContract(contractDetails.ContractAddress).tokensOfOwner(owner);
uint256[] memory accruals = new uint256[](tokenIds.length);
uint256 totalAccruedByContract;
for (uint16 x = 0; x < tokenIds.length; x++) {
uint32 tokenId = uint32(tokenIds[x]);
uint256 accrued = getContractTokenAccruals(contractDetails.ContractAddress, contractDetails.BaseRate, tokenId);
totalAccruedByContract+=accrued;
totalAccrued+=accrued;
tokenIds[x] = tokenId;
accruals[x] = accrued;
}
AccrualDetails memory accrual = AccrualDetails(contractDetails.ContractAddress, tokenIds, accruals, totalAccruedByContract);
totalAccruals[contractCount-1] = accrual;
}
}
return (totalAccruals, totalAccrued);
}
/// @notice Claims all virtual AWOO accrued by the message sender, assuming the sender holds any supported contracts tokenIds
function claimAll() external nonReentrant {
require(claimingActive, "Claiming is inactive");
require(isValidHolder(), "No supported tokens held");
(AccrualDetails[] memory accruals, uint256 totalAccrued) = getTotalAccruals(_msgSender());
require(totalAccrued > 0, "No tokens have been accrued");
for(uint8 i = 0; i < accruals.length; i++){
AccrualDetails memory accrual = accruals[i];
if(accrual.TotalAccrued > 0){
for(uint16 x = 0; x < accrual.TokenIds.length;x++){
// Update the time that this token was last claimed
lastClaims[accrual.ContractAddress][accrual.TokenIds[x]] = block.timestamp;
}
}
}
// A holder's virtual AWOO balance is stored in the $AWOO ERC-20 contract
_awooContract.increaseVirtualBalance(_msgSender(), totalAccrued);
emit TokensClaimed(_msgSender(), totalAccrued);
}
/// @notice Claims the accrued virtual AWOO from the specified supported contract tokenIds
/// @param requestedClaims A collection of supported contract addresses and the specific tokenIds to claim from
function claim(ClaimDetails[] calldata requestedClaims) external nonReentrant {
require(claimingActive, "Claiming is inactive");
require(isValidHolder(), "No supported tokens held");
uint256 totalClaimed;
for(uint8 i = 0; i < requestedClaims.length; i++){
ClaimDetails calldata requestedClaim = requestedClaims[i];
uint8 contractId = _supportedContractIds[requestedClaim.ContractAddress];
if(contractId == 0) revert("Unsupported contract");
SupportedContractDetails memory contractDetails = supportedContracts[contractId-1];
if(!contractDetails.Active) revert("Inactive contract");
for(uint16 x = 0; x < requestedClaim.TokenIds.length; x++){
uint32 tokenId = requestedClaim.TokenIds[x];
address tokenOwner = ISupportedContract(address(contractDetails.ContractAddress)).ownerOf(tokenId);
if(tokenOwner != _msgSender()) revert("Invalid owner claim attempt");
uint256 claimableAmount = getContractTokenAccruals(contractDetails.ContractAddress, contractDetails.BaseRate, tokenId);
if(claimableAmount > 0){
totalClaimed+=claimableAmount;
// Update the time that this token was last claimed
lastClaims[contractDetails.ContractAddress][tokenId] = block.timestamp;
}
}
}
if(totalClaimed > 0){
_awooContract.increaseVirtualBalance(_msgSender(), totalClaimed);
emit TokensClaimed(_msgSender(), totalClaimed);
}
}
/// @dev Calculates the accrued amount of virtual AWOO for the specified supported contract and tokenId
function getContractTokenAccruals(address contractAddress, uint256 contractBaseRate, uint32 tokenId) private view returns(uint256){
uint256 lastClaimTime = lastClaims[contractAddress][tokenId];
uint256 accruedUntil = accrualEnd == 0 || block.timestamp < accrualEnd
? block.timestamp
: accrualEnd;
uint256 baseRate = baseRateTokenOverrides[contractAddress][tokenId] > 0
? baseRateTokenOverrides[contractAddress][tokenId]
: contractBaseRate;
if (lastClaimTime > 0){
return (baseRate*(accruedUntil-lastClaimTime))/60;
} else {
return (baseRate*(accruedUntil-accrualStart))/60;
}
}
/// @notice Allows an authorized contract to increase the base accrual rate for particular NFTs
/// when, for example, upgrades for that NFT were purchased
/// @param contractAddress The address of the supported contract
/// @param tokenId The id of the token from the supported contract whose base accrual rate will be updated
/// @param newBaseRate The new accrual base rate
function overrideTokenAccrualBaseRate(address contractAddress, uint32 tokenId, uint256 newBaseRate)
external onlyAuthorizedContract isValidBaseRate(newBaseRate) {
require(tokenId > 0, "Invalid tokenId");
uint8 contractId = _supportedContractIds[contractAddress];
require(contractId > 0, "Unsupported contract");
require(supportedContracts[contractId-1].Active, "Inactive contract");
baseRateTokenOverrides[contractAddress][tokenId] = (newBaseRate/_baseRateDivisor);
}
/// @notice Allows the owner or an admin to set a reference to the $AWOO ERC-20 contract
/// @param awooToken An instance of IAwooToken
function setAwooTokenContract(IAwooToken awooToken) external onlyOwnerOrAdmin {
_awooContract = awooToken;
}
/// @notice Allows the owner or an admin to set the date and time at which virtual AWOO accruing will stop
/// @notice This will only be used if absolutely necessary and any AWOO that accrued before the end date will still be claimable
/// @param timestamp The Epoch time at which accrual should end
function setAccrualEndTimestamp(uint256 timestamp) external onlyOwnerOrAdmin {
accrualEnd = timestamp;
}
/// @notice Allows the owner or an admin to add a contract whose tokens are eligible to accrue virtual AWOO
/// @param contractAddress The contract address of the collection (typically ERC-721, with the addition of the tokensOfOwner function)
/// @param baseRate The base accrual rate in wei units
function addSupportedContract(address contractAddress, uint256 baseRate) external onlyOwnerOrAdmin isValidBaseRate(baseRate) {
require(isContract(contractAddress), "Invalid contractAddress");
require(_supportedContractIds[contractAddress] == 0, "Contract already supported");
supportedContracts.push(SupportedContractDetails(contractAddress, baseRate/_baseRateDivisor, true));
_supportedContractIds[contractAddress] = uint8(supportedContracts.length);
_activeSupportedContractCount++;
}
/// @notice Allows the owner or an admin to deactivate a supported contract so it no longer accrues virtual AWOO
/// @param contractAddress The contract address that should be deactivated
function deactivateSupportedContract(address contractAddress) external onlyOwnerOrAdmin {
require(_supportedContractIds[contractAddress] > 0, "Unsupported contract");
supportedContracts[_supportedContractIds[contractAddress]-1].Active = false;
supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = 0;
_supportedContractIds[contractAddress] = 0;
_activeSupportedContractCount--;
}
/// @notice Allows the owner or an admin to authorize another contract to override token accruals on an individual token level
/// @param contractAddress The authorized contract address
function addAuthorizedContract(address contractAddress) external onlyOwnerOrAdmin {
require(isContract(contractAddress), "Invalid contractAddress");
_authorizedContracts[contractAddress] = true;
emit AuthorizedContractAdded(contractAddress, _msgSender());
}
/// @notice Allows the owner or an admin to remove an authorized contract
/// @param contractAddress The contract address which should have its authorization revoked
function removeAuthorizedContract(address contractAddress) external onlyOwnerOrAdmin {
_authorizedContracts[contractAddress] = false;
emit AuthorizedContractRemoved(contractAddress, _msgSender());
}
/// @notice Allows the owner or an admin to set the base accrual rate for a support contract
/// @param contractAddress The address of the supported contract
/// @param baseRate The new base accrual rate in wei units
function setBaseRate(address contractAddress, uint256 baseRate) external onlyOwnerOrAdmin isValidBaseRate(baseRate) {
require(_supportedContractIds[contractAddress] > 0, "Unsupported contract");
supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = baseRate/_baseRateDivisor;
}
/// @notice Allows the owner to specify two addresses allowed to administer this contract
/// @param adminAddresses A 2 item array of addresses
function setAdmins(address[2] calldata adminAddresses) external onlyOwner {
require(adminAddresses[0] != address(0) && adminAddresses[1] != address(0), "Invalid admin address");
_admins = adminAddresses;
_adminsSet = true;
}
/// @notice Allows the owner or an admin to activate/deactivate claiming ability
/// @param active The value specifiying whether or not claiming should be allowed
function setClaimingActive(bool active) external onlyOwnerOrAdmin {
claimingActive = active;
emit ClaimingStatusChanged(active, _msgSender());
}
/// @dev Derived from @openzeppelin/contracts/utils/Address.sol
function isContract(address account) private view returns (bool) {
if(account == address(0)) return false;
// 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;
}
/// @notice Determines whether or not the caller holds tokens for any of the supported contracts
function isValidHolder() private view returns(bool) {
for(uint8 i = 0; i < supportedContracts.length; i++){
SupportedContractDetails memory contractDetails = supportedContracts[i];
if(contractDetails.Active){
if(ISupportedContract(contractDetails.ContractAddress).balanceOf(_msgSender()) > 0) {
return true; // No need to continue checking other collections if the holder has any of the supported tokens
}
}
}
return false;
}
modifier onlyAuthorizedContract() {
require(_authorizedContracts[_msgSender()], "Sender is not authorized");
_;
}
modifier onlyOwnerOrAdmin() {
require(
_msgSender() == owner() || (
_adminsSet && (
_msgSender() == _admins[0] || _msgSender() == _admins[1]
)
), "Not an owner or admin");
_;
}
/// @dev To minimize the amount of unit conversion we have to do for comparing $AWOO (ERC-20) to virtual AWOO, we store
/// virtual AWOO with 18 implied decimal places, so this modifier prevents us from accidentally using the wrong unit
/// for base rates. For example, if holders of FangGang NFTs accrue at a rate of 1000 AWOO per fang, pre day, then
/// the base rate should be 1000000000000000000000
modifier isValidBaseRate(uint256 baseRate) {
require(baseRate >= 1 ether, "Base rate must be in wei units");
_;
}
}
// File: @openzeppelin/[email protected]/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `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");
unchecked {
_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");
unchecked {
_approve(_msgSender(), 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:
*
* - `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");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += 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 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 {}
}
// File: contracts/AwooToken.sol
pragma solidity 0.8.12;
contract AwooToken is IAwooToken, ERC20, ReentrancyGuard, Ownable, AddressChecksumStringUtil {
using ECDSA for bytes32;
using Strings for uint256;
/// @dev Controls whether or not the deposit/withdraw functionality is enabled
bool public isActive = true;
/// @dev The percentage of spent virtual AWOO taken as a fee
uint256 public awooFeePercentage = 10;
/// @dev The Awoo Studios account where fees are sent
address public awooStudiosAccount;
address[2] private _admins;
bool private _adminsSet;
/// @dev Keeps track of which contracts are explicitly allowed to add virtual AWOO to a holder's address, spend from it, or
/// in the future, mint ERC-20 tokens
mapping(address => bool) private _authorizedContracts;
/// @dev Keeps track of each holders virtual AWOO balance
mapping(address => uint256) private _virtualBalance;
/// @dev Keeps track of nonces used for spending events to prevent double spends
mapping(string => bool) private _usedNonces;
event AuthorizedContractAdded(address contractAddress, address addedBy);
event AuthorizedContractRemoved(address contractAddress, address removedBy);
event VirtualAwooSpent(address spender, uint256 amount);
constructor(address awooAccount) ERC20("Awoo Token", "AWOO") {
require(awooAccount != address(0), "Invalid awooAccount");
awooStudiosAccount = awooAccount;
}
/// @notice Allows an authorized contract to mint $AWOO
/// @param account The account to receive the minted $AWOO tokens
/// @param amount The amount of $AWOO to mint
function mint(address account, uint256 amount) external nonReentrant onlyAuthorizedContract {
require(account != address(0), "Cannot mint to the zero address");
require(amount > 0, "Amount cannot be zero");
_mint(account, amount);
}
/// @notice Allows the owner or an admin to add authorized contracts
/// @param contractAddress The address of the contract to authorize
function addAuthorizedContract(address contractAddress) external onlyOwnerOrAdmin {
require(isContract(contractAddress), "Not a contract address");
_authorizedContracts[contractAddress] = true;
emit AuthorizedContractAdded(contractAddress, _msgSender());
}
/// @notice Allows the owner or an admin to remove authorized contracts
/// @param contractAddress The address of the contract to revoke authorization for
function removeAuthorizedContract(address contractAddress) external onlyOwnerOrAdmin {
_authorizedContracts[contractAddress] = false;
emit AuthorizedContractRemoved(contractAddress, _msgSender());
}
/// @notice Exchanges virtual AWOO for ERC-20 $AWOO
/// @param amount The amount of virtual AWOO to withdraw
function withdraw(uint256 amount) external whenActive hasBalance(amount, _virtualBalance[_msgSender()]) nonReentrant {
_mint(_msgSender(), amount);
_virtualBalance[_msgSender()] -= amount;
}
/// @notice Exchanges ERC-20 $AWOO for virtual AWOO to be used in the Awoo Studios ecosystem
/// @param amount The amount of $AWOO to deposit
function deposit(uint256 amount) external whenActive hasBalance(amount, balanceOf(_msgSender())) nonReentrant {
_burn(_msgSender(), amount);
_virtualBalance[_msgSender()] += amount;
}
/// @notice Returns the amount of virtual AWOO held by the specified address
/// @param account The holder account to check
function balanceOfVirtual(address account) external view returns(uint256) {
return _virtualBalance[account];
}
/// @notice Returns the amount of ERC-20 $AWOO held by the specified address
/// @param account The holder account to check
function totalBalanceOf(address account) external view returns(uint256) {
return _virtualBalance[account] + balanceOf(account);
}
/// @notice Allows authorized contracts to increase a holders virtual AWOO
/// @param account The account to increase
/// @param amount The amount of virtual AWOO to increase the account by
function increaseVirtualBalance(address account, uint256 amount) external onlyAuthorizedContract {
_virtualBalance[account] += amount;
}
/// @notice Allows authorized contracts to faciliate the spending of virtual AWOO, and fees to be paid to
/// Awoo Studios.
/// @notice Only amounts that have been signed and verified by the token holder can be spent
/// @param hash The hash of the message displayed to and signed by the holder
/// @param sig The signature of the messages that was signed by the holder
/// @param nonce The unique code used to prevent double spends
/// @param account The account of the holder to debit
/// @param amount The amount of virtual AWOO to debit
function spendVirtualAwoo(bytes32 hash, bytes memory sig, string calldata nonce, address account, uint256 amount)
external onlyAuthorizedContract hasBalance(amount, _virtualBalance[account]) nonReentrant {
require(_usedNonces[nonce] == false, "Duplicate nonce");
require(matchAddresSigner(account, hash, sig), "Message signer mismatch"); // Make sure that the spend request was authorized (signed) by the holder
require(hashTransaction(account, amount) == hash, "Hash check failed"); // Make sure that only the amount authorized by the holder can be spent
// debit the holder's virtual AWOO account
_virtualBalance[account]-=amount;
// Mint the spending fee to the Awoo Studios account
_mint(awooStudiosAccount, ((amount * awooFeePercentage)/100));
_usedNonces[nonce] = true;
emit VirtualAwooSpent(account, amount);
}
/// @notice Allows the owner to specify two addresses allowed to administer this contract
/// @param adminAddresses A 2 item array of addresses
function setAdmins(address[2] calldata adminAddresses) external onlyOwner {
require(adminAddresses[0] != address(0) && adminAddresses[1] != address(0), "Invalid admin address");
_admins = adminAddresses;
_adminsSet = true;
}
/// @notice Allows the owner or an admin to activate/deactivate deposit and withdraw functionality
/// @notice This will only be used to disable functionality as a worst case scenario
/// @param active The value specifiying whether or not deposits/withdraws should be allowed
function setActiveState(bool active) external onlyOwnerOrAdmin {
isActive = active;
}
/// @notice Allows the owner to change the account used for collecting spending fees
/// @param awooAccount The new account
function setAwooStudiosAccount(address awooAccount) external onlyOwner {
require(awooAccount != address(0), "Invalid awooAccount");
awooStudiosAccount = awooAccount;
}
/// @notice Allows the owner to change the spending fee percentage
/// @param feePercentage The new fee percentage
function setFeePercentage(uint256 feePercentage) external onlyOwner {
awooFeePercentage = feePercentage; // We're intentionally allowing the fee percentage to be set to 0%, incase no fees need to be collected
}
/// @notice Allows the owner to withdraw any Ethereum that was accidentally sent to this contract
function rescueEth() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
/// @dev Derived from @openzeppelin/contracts/utils/Address.sol
function isContract(address account) private 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 Validates the specified account against the account that signed the message
function matchAddresSigner(address account, bytes32 hash, bytes memory signature) private pure returns (bool) {
return account == hash.recover(signature);
}
/// @dev Hashes the message we expected the spender to sign so we can compare the hashes to ensure that the owner
/// of the specified address signed the same message
/// @dev fractional ether unit amounts aren't supported
function hashTransaction(address sender, uint256 amount) private pure returns (bytes32) {
require(amount == ((amount/1e18)*1e18), "Invalid amount");
// Virtual $AWOO, much like the ERC-20 $AWOO is stored with 18 implied decimal places.
// For user-friendliness, when prompting the user to sign the message, the amount is
// _displayed_ without the implied decimals, but it is charged with the implied decimals,
// so when validating the hash, we have to use the same value we displayed to the user.
// This only affects the display value, nothing else
amount = amount/1e18;
string memory message = string(abi.encodePacked(
"As the owner of Ethereum address\r\n",
toChecksumString(sender),
"\r\nI authorize the spending of ",
amount.toString()," virtual $AWOO"
));
uint256 messageLength = bytes(message).length;
bytes32 hash = keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n",messageLength.toString(),
message
)
);
return hash;
}
modifier onlyAuthorizedContract() {
require(_authorizedContracts[_msgSender()], "Sender is not authorized");
_;
}
modifier whenActive() {
require(isActive, "Contract is not active");
_;
}
modifier hasBalance(uint256 amount, uint256 balance) {
require(amount > 0, "Amount cannot be zero");
require(balance >= amount, "Insufficient Balance");
_;
}
modifier onlyOwnerOrAdmin() {
require(
_msgSender() == owner() ||
(_adminsSet &&
(_msgSender() == _admins[0] || _msgSender() == _admins[1])),
"Caller is not the owner or an admin"
);
_;
}
}
// File: contracts/AwooClaimingV2.sol
pragma solidity 0.8.12;
contract AwooClaimingV2 is IAwooClaimingV2, AuthorizedCallerGuard, ReentrancyGuard {
uint256 public accrualStart;
uint256 public accrualEnd;
bool public claimingActive;
/// @dev A collection of supported contracts. These are typically ERC-721, with the addition of the tokensOfOwner function.
/// @dev These contracts can be deactivated but cannot be re-activated. Reactivating can be done by adding the same
/// contract through addSupportedContract
SupportedContractDetails[] public supportedContracts;
/// @dev Keeps track of the last time a claim was made for each tokenId within the supported contract collection
mapping(address => mapping(uint256 => uint256)) public lastClaims;
/// @dev Allows the base accrual rates to be overridden on a per-tokenId level to support things like upgrades
mapping(address => mapping(uint256 => uint256)) public baseRateTokenOverrides;
AwooClaiming public v1ClaimingContract;
AwooToken public awooContract;
/// @dev Base accrual rates are set a per-day rate so we change them to per-minute to allow for more frequent claiming
uint64 private _baseRateDivisor = 1440;
/// @dev Faciliates the maintence and functionality related to supportedContracts
uint8 private _activeSupportedContractCount;
mapping(address => uint8) private _supportedContractIds;
event TokensClaimed(address indexed claimedBy, uint256 qty);
event ClaimingStatusChanged(bool newStatus, address changedBy);
constructor(AwooClaiming v1Contract) {
v1ClaimingContract = v1Contract;
accrualStart = v1ClaimingContract.accrualStart();
}
/// @notice Sets the first version of the claiming contract, which has been replaced with this one
/// @param v1Contract A reference to the v1 claiming contract
function setV1ClaimingContract(AwooClaiming v1Contract) external onlyOwnerOrAdmin {
v1ClaimingContract = v1Contract;
accrualStart = v1ClaimingContract.accrualStart();
}
/// @notice Determines the amount of accrued virtual AWOO for the specified address, based on the
/// base accural rates for each supported contract and how long has elapsed (in minutes) since the
/// last claim was made for a give supported contract tokenId
/// @param owner The address of the owner/holder of tokens for a supported contract
/// @return A collection of accrued virtual AWOO and the tokens it was accrued on for each supported contract, and the total AWOO accrued
function getTotalAccruals(address owner) public view returns (AccrualDetails[] memory, uint256) {
// Initialize the array length based on the number of _active_ supported contracts
AccrualDetails[] memory totalAccruals = new AccrualDetails[](_activeSupportedContractCount);
uint256 totalAccrued;
uint8 contractCount; // Helps us keep track of the index to use when setting the values for totalAccruals
for(uint8 i = 0; i < supportedContracts.length; i++) {
SupportedContractDetails memory contractDetails = supportedContracts[i];
if(contractDetails.Active){
contractCount++;
// Get an array of tokenIds held by the owner for the supported contract
uint256[] memory tokenIds = ISupportedContract(contractDetails.ContractAddress).tokensOfOwner(owner);
uint256[] memory accruals = new uint256[](tokenIds.length);
uint256 totalAccruedByContract;
for (uint16 x = 0; x < tokenIds.length; x++) {
uint32 tokenId = uint32(tokenIds[x]);
uint256 accrued = getContractTokenAccruals(contractDetails.ContractAddress, tokenId);
totalAccruedByContract+=accrued;
totalAccrued+=accrued;
tokenIds[x] = tokenId;
accruals[x] = accrued;
}
AccrualDetails memory accrual = AccrualDetails(contractDetails.ContractAddress, tokenIds, accruals, totalAccruedByContract);
totalAccruals[contractCount-1] = accrual;
}
}
return (totalAccruals, totalAccrued);
}
/// @notice Claims all virtual AWOO accrued by the message sender, assuming the sender holds any supported contracts tokenIds
function claimAll(address holder) external nonReentrant {
require(claimingActive, "Claiming is inactive");
require(_isAuthorizedContract(_msgSender()) || holder == _msgSender(), "Unauthorized claim attempt");
(AccrualDetails[] memory accruals, uint256 totalAccrued) = getTotalAccruals(holder);
require(totalAccrued > 0, "No tokens have been accrued");
for(uint8 i = 0; i < accruals.length; i++){
AccrualDetails memory accrual = accruals[i];
if(accrual.TotalAccrued > 0){
for(uint16 x = 0; x < accrual.TokenIds.length;x++){
// Update the time that this token was last claimed
lastClaims[accrual.ContractAddress][accrual.TokenIds[x]] = block.timestamp;
}
}
}
// A holder's virtual AWOO balance is stored in the $AWOO ERC-20 contract
awooContract.increaseVirtualBalance(holder, totalAccrued);
emit TokensClaimed(holder, totalAccrued);
}
/// @notice Claims the accrued virtual AWOO from the specified supported contract tokenIds
/// @param requestedClaims A collection of supported contract addresses and the specific tokenIds to claim from
function claim(address holder, ClaimDetails[] calldata requestedClaims) external nonReentrant {
require(claimingActive, "Claiming is inactive");
require(_isAuthorizedContract(_msgSender()) || holder == _msgSender(), "Unauthorized claim attempt");
uint256 totalClaimed;
for(uint8 i = 0; i < requestedClaims.length; i++){
ClaimDetails calldata requestedClaim = requestedClaims[i];
uint8 contractId = _supportedContractIds[requestedClaim.ContractAddress];
if(contractId == 0) revert("Unsupported contract");
SupportedContractDetails memory contractDetails = supportedContracts[contractId-1];
if(!contractDetails.Active) revert("Inactive contract");
for(uint16 x = 0; x < requestedClaim.TokenIds.length; x++){
uint32 tokenId = requestedClaim.TokenIds[x];
address tokenOwner = ISupportedContract(address(contractDetails.ContractAddress)).ownerOf(tokenId);
if(tokenOwner != holder) revert("Invalid owner claim attempt");
uint256 claimableAmount = getContractTokenAccruals(contractDetails.ContractAddress, tokenId);
if(claimableAmount > 0){
totalClaimed+=claimableAmount;
// Update the time that this token was last claimed
lastClaims[contractDetails.ContractAddress][tokenId] = block.timestamp;
}
}
}
if(totalClaimed > 0){
awooContract.increaseVirtualBalance(holder, totalClaimed);
emit TokensClaimed(holder, totalClaimed);
}
}
/// @notice Calculates the accrued amount of virtual AWOO for the specified supported contract and tokenId
/// @dev To save gas, we don't validate the existence of the token within the specified collection as this is done
/// within the claiming functions
/// @dev The first time a claim is made in this contract, we use the v1 contract's last claim time so we don't
/// accrue based on accruals that were claimed through the v1 contract
/// @param contractAddress The contract address of the supported collection
/// @param tokenId The id of the token/NFT
/// @return The amount of virtual AWOO accrued for the specified token and collection
function getContractTokenAccruals(address contractAddress, uint32 tokenId) public view returns(uint256){
uint8 contractId = _supportedContractIds[contractAddress];
if(contractId == 0) revert("Unsupported contract");
SupportedContractDetails memory contractDetails = supportedContracts[contractId-1];
if(!contractDetails.Active) revert("Inactive contract");
uint256 lastClaimTime = lastClaims[contractAddress][tokenId] > 0
? lastClaims[contractAddress][tokenId]
: v1ClaimingContract.lastClaims(contractAddress, tokenId);
uint256 accruedUntil = accrualEnd == 0 || block.timestamp < accrualEnd
? block.timestamp
: accrualEnd;
uint256 baseRate = getContractTokenBaseAccrualRate(contractDetails, tokenId);
if (lastClaimTime > 0){
return (baseRate*(accruedUntil-lastClaimTime))/60;
} else {
return (baseRate*(accruedUntil-accrualStart))/60;
}
}
/// @notice Returns the current base accrual rate for the specified token, taking overrides into account
/// @dev This is mostly to support testing
/// @param contractDetails The details of the supported contract
/// @param tokenId The id of the token/NFT
/// @return The base accrual rate
function getContractTokenBaseAccrualRate(SupportedContractDetails memory contractDetails, uint32 tokenId
) public view returns(uint256){
return baseRateTokenOverrides[contractDetails.ContractAddress][tokenId] > 0
? baseRateTokenOverrides[contractDetails.ContractAddress][tokenId]
: contractDetails.BaseRate;
}
/// @notice Allows an authorized contract to increase the base accrual rate for particular NFTs
/// when, for example, upgrades for that NFT were purchased
/// @param contractAddress The address of the supported contract
/// @param tokenId The id of the token from the supported contract whose base accrual rate will be updated
/// @param newBaseRate The new accrual base rate
function overrideTokenAccrualBaseRate(address contractAddress, uint32 tokenId, uint256 newBaseRate)
external onlyAuthorizedContract isValidBaseRate(newBaseRate) {
require(tokenId > 0, "Invalid tokenId");
uint8 contractId = _supportedContractIds[contractAddress];
require(contractId > 0, "Unsupported contract");
require(supportedContracts[contractId-1].Active, "Inactive contract");
baseRateTokenOverrides[contractAddress][tokenId] = (newBaseRate/_baseRateDivisor);
}
/// @notice Allows the owner or an admin to set a reference to the $AWOO ERC-20 contract
/// @param awooToken An instance of IAwooToken
function setAwooTokenContract(AwooToken awooToken) external onlyOwnerOrAdmin {
awooContract = awooToken;
}
/// @notice Allows the owner or an admin to set the date and time at which virtual AWOO accruing will stop
/// @notice This will only be used if absolutely necessary and any AWOO that accrued before the end date will still be claimable
/// @param timestamp The Epoch time at which accrual should end
function setAccrualEndTimestamp(uint256 timestamp) external onlyOwnerOrAdmin {
accrualEnd = timestamp;
}
/// @notice Allows the owner or an admin to add a contract whose tokens are eligible to accrue virtual AWOO
/// @param contractAddress The contract address of the collection (typically ERC-721, with the addition of the tokensOfOwner function)
/// @param baseRate The base accrual rate in wei units
function addSupportedContract(address contractAddress, uint256 baseRate) public onlyOwnerOrAdmin isValidBaseRate(baseRate) {
require(_isContract(contractAddress), "Invalid contractAddress");
require(_supportedContractIds[contractAddress] == 0, "Contract already supported");
supportedContracts.push(SupportedContractDetails(contractAddress, baseRate/_baseRateDivisor, true));
_supportedContractIds[contractAddress] = uint8(supportedContracts.length);
_activeSupportedContractCount++;
}
/// @notice Allows the owner or an admin to deactivate a supported contract so it no longer accrues virtual AWOO
/// @param contractAddress The contract address that should be deactivated
function deactivateSupportedContract(address contractAddress) external onlyOwnerOrAdmin {
require(_supportedContractIds[contractAddress] > 0, "Unsupported contract");
supportedContracts[_supportedContractIds[contractAddress]-1].Active = false;
supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = 0;
_supportedContractIds[contractAddress] = 0;
_activeSupportedContractCount--;
}
/// @notice Allows the owner or an admin to set the base accrual rate for a support contract
/// @param contractAddress The address of the supported contract
/// @param baseRate The new base accrual rate in wei units
function setBaseRate(address contractAddress, uint256 baseRate) external onlyOwnerOrAdmin isValidBaseRate(baseRate) {
require(_supportedContractIds[contractAddress] > 0, "Unsupported contract");
supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = baseRate/_baseRateDivisor;
}
/// @notice Allows the owner or an admin to activate/deactivate claiming ability
/// @param active The value specifiying whether or not claiming should be allowed
function setClaimingActive(bool active) external onlyOwnerOrAdmin {
claimingActive = active;
emit ClaimingStatusChanged(active, _msgSender());
}
/// @dev To minimize the amount of unit conversion we have to do for comparing $AWOO (ERC-20) to virtual AWOO, we store
/// virtual AWOO with 18 implied decimal places, so this modifier prevents us from accidentally using the wrong unit
/// for base rates. For example, if holders of FangGang NFTs accrue at a rate of 1000 AWOO per fang, pre day, then
/// the base rate should be 1000000000000000000000
modifier isValidBaseRate(uint256 baseRate) {
require(baseRate >= 1 ether, "Base rate must be in wei units");
_;
}
}
// File: contracts/AwooClaimingV3.sol
pragma solidity 0.8.12;
contract AwooClaimingV3 is IAwooClaimingV2, AuthorizedCallerGuard, ReentrancyGuard {
uint256 public accrualStart;
uint256 public accrualEnd;
bool public claimingActive = false;
/// @dev A collection of supported contracts. These are typically ERC-721, with the addition of the tokensOfOwner function.
/// @dev These contracts can be deactivated but cannot be re-activated. Reactivating can be done by adding the same
/// contract through addSupportedContract
SupportedContractDetails[] public supportedContracts;
/// @dev Keeps track of the last time a claim was made for each tokenId within the supported contract collection
// contractAddress => (tokenId, lastClaimTimestamp)
mapping(address => mapping(uint256 => uint48)) public lastClaims;
/// @dev Allows the base accrual rates to be overridden on a per-tokenId level to support things like upgrades
mapping(address => mapping(uint256 => uint256)) public baseRateTokenOverrides;
// contractAddress => (tokenId, accruedAmount)
mapping(address => mapping(uint256 => uint256)) public unclaimedSnapshot;
AwooClaiming public v1ClaimingContract;
AwooClaimingV2 public v2ClaimingContract;
AwooToken public awooContract;
/// @dev Base accrual rates are set a per-day rate so we change them to per-minute to allow for more frequent claiming
uint64 private _baseRateDivisor = 1440;
/// @dev Faciliates the maintence and functionality related to supportedContracts
uint8 private _activeSupportedContractCount;
mapping(address => uint8) private _supportedContractIds;
event TokensClaimed(address indexed claimedBy, uint256 qty);
event ClaimingStatusChanged(bool newStatus, address changedBy);
constructor(AwooToken awooTokenContract, AwooClaimingV2 v2Contract, AwooClaiming v1Contract) {
awooContract = awooTokenContract;
v2ClaimingContract = v2Contract;
accrualStart = v2ClaimingContract.accrualStart();
v1ClaimingContract = v1Contract;
}
/// @notice Sets the previous versions of the claiming contracts, which have been replaced with this one
function setContracts(AwooClaimingV2 v2Contract, AwooClaiming v1Contract) external onlyOwnerOrAdmin {
v2ClaimingContract = v2Contract;
accrualStart = v2ClaimingContract.accrualStart();
v1ClaimingContract = v1Contract;
}
/// @notice Determines the amount of accrued virtual AWOO for the specified address, based on the
/// base accural rates for each supported contract and how long has elapsed (in minutes) since the
/// last claim was made for a give supported contract tokenId
/// @param owner The address of the owner/holder of tokens for a supported contract
/// @return A collection of accrued virtual AWOO and the tokens it was accrued on for each supported contract, and the total AWOO accrued
function getTotalAccruals(address owner) public view returns (AccrualDetails[] memory, uint256) {
// Initialize the array length based on the number of _active_ supported contracts
AccrualDetails[] memory totalAccruals = new AccrualDetails[](_activeSupportedContractCount);
uint256 totalAccrued;
uint8 contractCount; // Helps us keep track of the index to use when setting the values for totalAccruals
for(uint8 i = 0; i < supportedContracts.length; i++) {
SupportedContractDetails memory contractDetails = supportedContracts[i];
if(contractDetails.Active){
contractCount++;
// Get an array of tokenIds held by the owner for the supported contract
uint256[] memory tokenIds = ISupportedContract(contractDetails.ContractAddress).tokensOfOwner(owner);
uint256[] memory accruals = new uint256[](tokenIds.length);
uint256 totalAccruedByContract;
for (uint16 x = 0; x < tokenIds.length; x++) {
uint256 tokenId = tokenIds[x];
uint256 accrued = getContractTokenAccruals(contractDetails.ContractAddress, tokenId);
totalAccruedByContract+=accrued;
totalAccrued+=accrued;
tokenIds[x] = tokenId;
accruals[x] = accrued;
}
AccrualDetails memory accrual = AccrualDetails(contractDetails.ContractAddress, tokenIds, accruals, totalAccruedByContract);
totalAccruals[contractCount-1] = accrual;
}
}
return (totalAccruals, totalAccrued);
}
/// @notice Claims all virtual AWOO accrued by the message sender, assuming the sender holds any supported contracts tokenIds
function claimAll(address holder) external nonReentrant {
require(claimingActive, "Claiming is inactive");
require(_isAuthorizedContract(_msgSender()) || holder == _msgSender(), "Unauthorized claim attempt");
(AccrualDetails[] memory accruals, uint256 totalAccrued) = getTotalAccruals(holder);
require(totalAccrued > 0, "No tokens have been accrued");
for(uint8 i = 0; i < accruals.length; i++){
AccrualDetails memory accrual = accruals[i];
if(accrual.TotalAccrued > 0){
for(uint16 x = 0; x < accrual.TokenIds.length;x++){
// Update the time that this token was last claimed
lastClaims[accrual.ContractAddress][accrual.TokenIds[x]] = uint48(block.timestamp);
// Any amount from the unclaimed snapshot are now claimed because they were returned by getContractTokenAccruals
// so dump it
delete unclaimedSnapshot[accrual.ContractAddress][accrual.TokenIds[x]];
}
}
}
// A holder's virtual AWOO balance is stored in the $AWOO ERC-20 contract
awooContract.increaseVirtualBalance(holder, totalAccrued);
emit TokensClaimed(holder, totalAccrued);
}
/// @notice Claims the accrued virtual AWOO from the specified supported contract tokenIds
/// @param requestedClaims A collection of supported contract addresses and the specific tokenIds to claim from
function claim(address holder, ClaimDetails[] calldata requestedClaims) external nonReentrant {
require(claimingActive, "Claiming is inactive");
require(_isAuthorizedContract(_msgSender()) || holder == _msgSender(), "Unauthorized claim attempt");
uint256 totalClaimed;
for(uint8 i = 0; i < requestedClaims.length; i++){
ClaimDetails calldata requestedClaim = requestedClaims[i];
uint8 contractId = _supportedContractIds[requestedClaim.ContractAddress];
if(contractId == 0) revert("Unsupported contract");
SupportedContractDetails memory contractDetails = supportedContracts[contractId-1];
if(!contractDetails.Active) revert("Inactive contract");
for(uint16 x = 0; x < requestedClaim.TokenIds.length; x++){
uint32 tokenId = requestedClaim.TokenIds[x];
address tokenOwner = ISupportedContract(address(contractDetails.ContractAddress)).ownerOf(tokenId);
if(tokenOwner != holder) revert("Invalid owner claim attempt");
uint256 claimableAmount = getContractTokenAccruals(contractDetails.ContractAddress, tokenId);
if(claimableAmount > 0){
totalClaimed+=claimableAmount;
// Update the time that this token was last claimed
lastClaims[contractDetails.ContractAddress][tokenId] = uint48(block.timestamp);
// Any amount from the unclaimed snapshot are now claimed because they were returned by getContractTokenAccruals
// so dump it
delete unclaimedSnapshot[contractDetails.ContractAddress][tokenId];
}
}
}
if(totalClaimed > 0){
awooContract.increaseVirtualBalance(holder, totalClaimed);
emit TokensClaimed(holder, totalClaimed);
}
}
/// @notice Calculates the accrued amount of virtual AWOO for the specified supported contract and tokenId
/// @dev To save gas, we don't validate the existence of the token within the specified collection as this is done
/// within the claiming functions
/// @dev The first time a claim is made in this contract, we use the v1 contract's last claim time so we don't
/// accrue based on accruals that were claimed through the v1 contract
/// @param contractAddress The contract address of the supported collection
/// @param tokenId The id of the token/NFT
/// @return The amount of virtual AWOO accrued for the specified token and collection
function getContractTokenAccruals(address contractAddress, uint256 tokenId) public view returns(uint256){
uint8 contractId = _supportedContractIds[contractAddress];
if(contractId == 0) revert("Unsupported contract");
SupportedContractDetails memory contractDetails = supportedContracts[contractId-1];
if(!contractDetails.Active) revert("Inactive contract");
return getContractTokenAccruals(contractDetails, tokenId, uint48(block.timestamp));
}
/// @notice Calculates the accrued amount of virtual AWOO for the specified supported contract and tokenId, at the point in time specified
/// @dev To save gas, we don't validate the existence of the token within the specified collection as this is done
/// within the claiming functions
/// @dev The first time a claim is made in this contract, we use the v1 contract's last claim time so we don't
/// accrue based on accruals that were claimed through the v1 contract
/// @param contractDetails The contract details of the supported collection
/// @param tokenId The id of the token/NFT
/// @param accruedUntilTimestamp The timestamp to calculate accruals from
/// @return The amount of virtual AWOO accrued for the specified token and collection
function getContractTokenAccruals(SupportedContractDetails memory contractDetails,
uint256 tokenId, uint48 accruedUntilTimestamp
) private view returns(uint256){
uint48 lastClaimTime = getLastClaimTime(contractDetails.ContractAddress, tokenId);
uint256 accruedUntil = accrualEnd == 0 || accruedUntilTimestamp < accrualEnd
? accruedUntilTimestamp
: accrualEnd;
uint256 existingSnapshotAmount = unclaimedSnapshot[contractDetails.ContractAddress][tokenId];
uint256 baseRate = getContractTokenBaseAccrualRate(contractDetails, tokenId);
if (lastClaimTime > 0){
return existingSnapshotAmount + ((baseRate*(accruedUntil-lastClaimTime))/60);
} else {
return existingSnapshotAmount + ((baseRate*(accruedUntil-accrualStart))/60);
}
}
function getLastClaimTime(address contractAddress, uint256 tokenId) public view returns(uint48){
uint48 lastClaim = lastClaims[contractAddress][tokenId];
// If a claim has already been made through this contract, return the time of that claim
if(lastClaim > 0) {
return lastClaim;
}
// If not claims have been made through this contract, check V2
lastClaim = uint48(v2ClaimingContract.lastClaims(contractAddress, tokenId));
if(lastClaim > 0) {
return lastClaim;
}
// If not claims have been made through the V2 contract, check the OG
return uint48(v1ClaimingContract.lastClaims(contractAddress, tokenId));
}
/// @notice Returns the current base accrual rate for the specified token, taking overrides into account
/// @dev This is mostly to support testing
/// @param contractDetails The details of the supported contract
/// @param tokenId The id of the token/NFT
/// @return The base accrual rate
function getContractTokenBaseAccrualRate(SupportedContractDetails memory contractDetails, uint256 tokenId
) public view returns(uint256){
return baseRateTokenOverrides[contractDetails.ContractAddress][tokenId] > 0
? baseRateTokenOverrides[contractDetails.ContractAddress][tokenId]
: contractDetails.BaseRate;
}
/// @notice Allows an authorized contract to increase the base accrual rate for particular NFTs
/// when, for example, upgrades for that NFT were purchased
/// @param contractAddress The address of the supported contract
/// @param tokenId The id of the token from the supported contract whose base accrual rate will be updated
/// @param newBaseRate The new accrual base rate
function overrideTokenAccrualBaseRate(address contractAddress, uint32 tokenId, uint256 newBaseRate
) external onlyAuthorizedContract isValidBaseRate(newBaseRate) {
require(tokenId > 0, "Invalid tokenId");
uint8 contractId = _supportedContractIds[contractAddress];
require(contractId > 0, "Unsupported contract");
require(supportedContracts[contractId-1].Active, "Inactive contract");
// Before overriding the accrual rate, take a snapshot of what the current unclaimed amount is
// so that when `claim` or `claimAll` is called, the snapshot amount will be included so
// it doesn't get lost
// @dev IMPORTANT: The snapshot must be taken _before_ baseRateTokenOverrides is set
unclaimedSnapshot[contractAddress][tokenId] = getContractTokenAccruals(contractAddress, tokenId);
lastClaims[contractAddress][tokenId] = uint48(block.timestamp);
baseRateTokenOverrides[contractAddress][tokenId] = (newBaseRate/_baseRateDivisor);
}
/// @notice Allows an authorized individual to manually create point-in-time snapshots of AWOO that
/// was accrued up until a particular point in time. This is only necessary to correct a bug in the
/// V2 claiming contract that caused unclaimed AWOO to double when the base rates were overridden,
/// rather than accruing with the new rate from that point in time
function fixPreAccrualOverrideSnapshot(address contractAddress, uint256[] calldata tokenIds,
uint48[] calldata accruedUntilTimestamps
) external onlyOwnerOrAdmin {
require(tokenIds.length == accruedUntilTimestamps.length, "Array length mismatch");
uint8 contractId = _supportedContractIds[contractAddress];
SupportedContractDetails memory contractDetails = supportedContracts[contractId-1];
for(uint16 i; i < tokenIds.length; i++) {
if(getLastClaimTime(contractAddress, tokenIds[i]) < accruedUntilTimestamps[i]) {
unclaimedSnapshot[contractAddress][tokenIds[i]] = getContractTokenAccruals(contractDetails, tokenIds[i], accruedUntilTimestamps[i]);
lastClaims[contractAddress][tokenIds[i]] = accruedUntilTimestamps[i];
}
}
}
/// @notice Allows the owner or an admin to set a reference to the $AWOO ERC-20 contract
/// @param awooToken An instance of IAwooToken
function setAwooTokenContract(AwooToken awooToken) external onlyOwnerOrAdmin {
awooContract = awooToken;
}
/// @notice Allows the owner or an admin to set the date and time at which virtual AWOO accruing will stop
/// @notice This will only be used if absolutely necessary and any AWOO that accrued before the end date will still be claimable
/// @param timestamp The Epoch time at which accrual should end
function setAccrualEndTimestamp(uint256 timestamp) external onlyOwnerOrAdmin {
accrualEnd = timestamp;
}
/// @notice Allows the owner or an admin to add a contract whose tokens are eligible to accrue virtual AWOO
/// @param contractAddress The contract address of the collection (typically ERC-721, with the addition of the tokensOfOwner function)
/// @param baseRate The base accrual rate in wei units
function addSupportedContract(address contractAddress, uint256 baseRate) public onlyOwnerOrAdmin isValidBaseRate(baseRate) {
require(_isContract(contractAddress), "Invalid contractAddress");
require(_supportedContractIds[contractAddress] == 0, "Contract already supported");
supportedContracts.push(SupportedContractDetails(contractAddress, baseRate/_baseRateDivisor, true));
_supportedContractIds[contractAddress] = uint8(supportedContracts.length);
_activeSupportedContractCount++;
}
/// @notice Allows the owner or an admin to deactivate a supported contract so it no longer accrues virtual AWOO
/// @param contractAddress The contract address that should be deactivated
function deactivateSupportedContract(address contractAddress) external onlyOwnerOrAdmin {
require(_supportedContractIds[contractAddress] > 0, "Unsupported contract");
supportedContracts[_supportedContractIds[contractAddress]-1].Active = false;
supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = 0;
_supportedContractIds[contractAddress] = 0;
_activeSupportedContractCount--;
}
/// @notice Allows the owner or an admin to set the base accrual rate for a support contract
/// @param contractAddress The address of the supported contract
/// @param baseRate The new base accrual rate in wei units
function setBaseRate(address contractAddress, uint256 baseRate) external onlyOwnerOrAdmin isValidBaseRate(baseRate) {
require(_supportedContractIds[contractAddress] > 0, "Unsupported contract");
supportedContracts[_supportedContractIds[contractAddress]-1].BaseRate = baseRate/_baseRateDivisor;
}
/// @notice Allows the owner or an admin to activate/deactivate claiming ability
/// @param active The value specifiying whether or not claiming should be allowed
function setClaimingActive(bool active) external onlyOwnerOrAdmin {
claimingActive = active;
emit ClaimingStatusChanged(active, _msgSender());
}
/// @dev To minimize the amount of unit conversion we have to do for comparing $AWOO (ERC-20) to virtual AWOO, we store
/// virtual AWOO with 18 implied decimal places, so this modifier prevents us from accidentally using the wrong unit
/// for base rates. For example, if holders of FangGang NFTs accrue at a rate of 1000 AWOO per fang, pre day, then
/// the base rate should be 1000000000000000000000
modifier isValidBaseRate(uint256 baseRate) {
require(baseRate >= 1 ether, "Base rate must be in wei units");
_;
}
} | Allows the owner or an admin to set a reference to the $AWOO ERC-20 contract awooToken An instance of IAwooToken | function setAwooTokenContract(AwooToken awooToken) external onlyOwnerOrAdmin {
awooContract = awooToken;
}
| 10,771,942 |
./full_match/1/0x61Ab01Ce58D1dFf3562bb25870020d555e39D849/sources/contracts/RelayerV2Radar.sol | dstConfigLookup[_chainId][_outboundProofType] = DstConfig(_dstNativeAmtCap, _baseGas, _gasPerByte); emit SetDstConfig(_chainId, _outboundProofType, _dstNativeAmtCap, _baseGas, _gasPerByte); | function setDstConfig(uint16 _chainId, uint16 _outboundProofType, uint128 _dstNativeAmtCap, uint64 _baseGas, uint64 _gasPerByte) external onlyApproved {
}
| 9,780,342 |
pragma solidity ^0.4.24;
contract ERC20Interface {
function name() public view returns(bytes32);
function symbol() public view returns(bytes32);
function balanceOf (address _owner) public view returns(uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (uint);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract AppCoins is ERC20Interface{
// Public variables of the token
address public owner;
bytes32 private token_name;
bytes32 private token_symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function AppCoins() public {
owner = msg.sender;
token_name = "AppCoins";
token_symbol = "APPC";
uint256 _totalSupply = 1000000;
totalSupply = _totalSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balances[owner] = totalSupply; // Give the creator all initial tokens
}
function name() public view returns(bytes32) {
return token_name;
}
function symbol() public view returns(bytes32) {
return token_symbol;
}
function balanceOf (address _owner) public view returns(uint256 balance) {
return balances[_owner];
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal returns (bool) {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value > balances[_to]);
// Save this for an assertion in the future
uint previousBalances = balances[_from] + balances[_to];
// Subtract from the sender
balances[_from] -= _value;
// Add the same to the recipient
balances[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balances[_from] + balances[_to] == previousBalances);
}
// /**
// * Transfer tokens
// *
// * Send `_value` tokens to `_to` from your account
// *
// * @param _to The address of the recipient
// * @param _value the amount to send
// */
// function transfer(address _to, uint256 _value) public {
// _transfer(msg.sender, _to, _value);
// }
function transfer (address _to, uint256 _amount) public returns (bool success) {
if( balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
emit Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (uint) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return allowance[_from][msg.sender];
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balances[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balances[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
library CampaignLibrary {
struct Campaign {
bytes32 bidId;
uint price;
uint budget;
uint startDate;
uint endDate;
bool valid;
address owner;
}
/**
@notice Set campaign id
@param _bidId Id of the campaign
*/
function setBidId(Campaign storage _campaign, bytes32 _bidId) internal {
_campaign.bidId = _bidId;
}
/**
@notice Get campaign id
@return {'_bidId' : 'Id of the campaign'}
*/
function getBidId(Campaign storage _campaign) internal view returns(bytes32 _bidId){
return _campaign.bidId;
}
/**
@notice Set campaing price per proof of attention
@param _price Price of the campaign
*/
function setPrice(Campaign storage _campaign, uint _price) internal {
_campaign.price = _price;
}
/**
@notice Get campaign price per proof of attention
@return {'_price' : 'Price of the campaign'}
*/
function getPrice(Campaign storage _campaign) internal view returns(uint _price){
return _campaign.price;
}
/**
@notice Set campaign total budget
@param _budget Total budget of the campaign
*/
function setBudget(Campaign storage _campaign, uint _budget) internal {
_campaign.budget = _budget;
}
/**
@notice Get campaign total budget
@return {'_budget' : 'Total budget of the campaign'}
*/
function getBudget(Campaign storage _campaign) internal view returns(uint _budget){
return _campaign.budget;
}
/**
@notice Set campaign start date
@param _startDate Start date of the campaign (in milisecounds)
*/
function setStartDate(Campaign storage _campaign, uint _startDate) internal{
_campaign.startDate = _startDate;
}
/**
@notice Get campaign start date
@return {'_startDate' : 'Start date of the campaign (in milisecounds)'}
*/
function getStartDate(Campaign storage _campaign) internal view returns(uint _startDate){
return _campaign.startDate;
}
/**
@notice Set campaign end date
@param _endDate End date of the campaign (in milisecounds)
*/
function setEndDate(Campaign storage _campaign, uint _endDate) internal {
_campaign.endDate = _endDate;
}
/**
@notice Get campaign end date
@return {'_endDate' : 'End date of the campaign (in milisecounds)'}
*/
function getEndDate(Campaign storage _campaign) internal view returns(uint _endDate){
return _campaign.endDate;
}
/**
@notice Set campaign validity
@param _valid Validity of the campaign
*/
function setValidity(Campaign storage _campaign, bool _valid) internal {
_campaign.valid = _valid;
}
/**
@notice Get campaign validity
@return {'_valid' : 'Boolean stating campaign validity'}
*/
function getValidity(Campaign storage _campaign) internal view returns(bool _valid){
return _campaign.valid;
}
/**
@notice Set campaign owner
@param _owner Owner of the campaign
*/
function setOwner(Campaign storage _campaign, address _owner) internal {
_campaign.owner = _owner;
}
/**
@notice Get campaign owner
@return {'_owner' : 'Address of the owner of the campaign'}
*/
function getOwner(Campaign storage _campaign) internal view returns(address _owner){
return _campaign.owner;
}
/**
@notice Converts country index list into 3 uints
Expects a list of country indexes such that the 2 digit country code is converted to an
index. Countries are expected to be indexed so a "AA" country code is mapped to index 0 and
"ZZ" country is mapped to index 675.
@param countries List of country indexes
@return {
"countries1" : "First third of the byte array converted in a 256 bytes uint",
"countries2" : "Second third of the byte array converted in a 256 bytes uint",
"countries3" : "Third third of the byte array converted in a 256 bytes uint"
}
*/
function convertCountryIndexToBytes(uint[] countries) public pure
returns (uint countries1,uint countries2,uint countries3){
countries1 = 0;
countries2 = 0;
countries3 = 0;
for(uint i = 0; i < countries.length; i++){
uint index = countries[i];
if(index<256){
countries1 = countries1 | uint(1) << index;
} else if (index<512) {
countries2 = countries2 | uint(1) << (index - 256);
} else {
countries3 = countries3 | uint(1) << (index - 512);
}
}
return (countries1,countries2,countries3);
}
}
interface StorageUser {
function getStorageAddress() external view returns(address _storage);
}
interface ErrorThrower {
event Error(string func, string message);
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
}
contract Ownable is ErrorThrower {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
modifier onlyOwner(string _funcName) {
if(msg.sender != owner){
emit Error(_funcName,"Operation can only be performed by contract owner");
return;
}
_;
}
/**
* 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("renounceOwnership") {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* 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") {
_transferOwnership(_newOwner);
}
/**
* Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
if(_newOwner == address(0)){
emit Error("transferOwnership","New owner's address needs to be different than 0x0");
return;
}
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract SingleAllowance is Ownable {
address allowedAddress;
modifier onlyAllowed() {
require(allowedAddress == msg.sender);
_;
}
modifier onlyOwnerOrAllowed() {
require(owner == msg.sender || allowedAddress == msg.sender);
_;
}
function setAllowedAddress(address _addr) public onlyOwner("setAllowedAddress"){
allowedAddress = _addr;
}
}
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* Throws Error event if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(string _funcname, address _operator) {
if(!hasRole(_operator, ROLE_WHITELISTED)){
emit Error(_funcname, "Operation can only be performed by Whitelisted Addresses");
return;
}
_;
}
/**
* add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
public
onlyOwner("addAddressToWhitelist")
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators)
public
onlyOwner("addAddressesToWhitelist")
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator)
public
onlyOwner("removeAddressFromWhitelist")
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators)
public
onlyOwner("removeAddressesFromWhitelist")
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
contract BaseAdvertisementStorage is Whitelist {
using CampaignLibrary for CampaignLibrary.Campaign;
mapping (bytes32 => CampaignLibrary.Campaign) campaigns;
bytes32 lastBidId = 0x0;
modifier onlyIfCampaignExists(string _funcName, bytes32 _bidId) {
if(campaigns[_bidId].owner == 0x0){
emit Error(_funcName,"Campaign does not exist");
return;
}
_;
}
event CampaignCreated
(
bytes32 bidId,
uint price,
uint budget,
uint startDate,
uint endDate,
bool valid,
address owner
);
event CampaignUpdated
(
bytes32 bidId,
uint price,
uint budget,
uint startDate,
uint endDate,
bool valid,
address owner
);
/**
@notice Get a Campaign information
Based on a camapaign Id (bidId), returns all stored information for that campaign.
@param campaignId Id of the campaign
@return {
"bidId" : "Id of the campaign",
"price" : "Value to pay for each proof-of-attention",
"budget" : "Total value avaliable to be spent on the campaign",
"startDate" : "Start date of the campaign (in miliseconds)",
"endDate" : "End date of the campaign (in miliseconds)"
"valid" : "Boolean informing if the campaign is valid",
"campOwner" : "Address of the campaing's owner"
}
*/
function _getCampaign(bytes32 campaignId)
internal
returns (CampaignLibrary.Campaign storage _campaign) {
return campaigns[campaignId];
}
/**
@notice Add or update a campaign information
Based on a campaign Id (bidId), a campaign can be created (if non existent) or updated.
This function can only be called by the set of allowed addresses registered earlier.
An event will be emited during this function's execution, a CampaignCreated event if the
campaign does not exist yet or a CampaignUpdated if the campaign id is already registered.
@param bidId Id of the campaign
@param price Value to pay for each proof-of-attention
@param budget Total value avaliable to be spent on the campaign
@param startDate Start date of the campaign (in miliseconds)
@param endDate End date of the campaign (in miliseconds)
@param valid Boolean informing if the campaign is valid
@param owner Address of the campaing's owner
*/
function _setCampaign (
bytes32 bidId,
uint price,
uint budget,
uint startDate,
uint endDate,
bool valid,
address owner
)
public
onlyIfWhitelisted("setCampaign",msg.sender) {
CampaignLibrary.Campaign storage campaign = campaigns[bidId];
campaign.setBidId(bidId);
campaign.setPrice(price);
campaign.setBudget(budget);
campaign.setStartDate(startDate);
campaign.setEndDate(endDate);
campaign.setValidity(valid);
bool newCampaign = (campaigns[bidId].getOwner() == 0x0);
campaign.setOwner(owner);
if(newCampaign){
emitCampaignCreated(campaign);
setLastBidId(bidId);
} else {
emitCampaignUpdated(campaign);
}
}
/**
@notice Constructor function
Initializes contract and updates allowed addresses to interact with contract functions.
*/
constructor() public {
addAddressToWhitelist(msg.sender);
}
/**
@notice Get the price of a campaign
Based on the Campaign id, return the value paid for each proof of attention registered.
@param bidId Campaign id to which the query refers
@return { "price" : "Reward (in wei) for each proof of attention registered"}
*/
function getCampaignPriceById(bytes32 bidId)
public
view
returns (uint price) {
return campaigns[bidId].getPrice();
}
/**
@notice Set a new price for a campaign
Based on the Campaign id, updates the value paid for each proof of attention registered.
This function can only be executed by allowed addresses and emits a CampaingUpdate event.
@param bidId Campaing id to which the update refers
@param price New price for each proof of attention
*/
function setCampaignPriceById(bytes32 bidId, uint price)
public
onlyIfWhitelisted("setCampaignPriceById",msg.sender)
onlyIfCampaignExists("setCampaignPriceById",bidId)
{
campaigns[bidId].setPrice(price);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Get the budget avaliable of a campaign
Based on the Campaign id, return the total value avaliable to pay for proofs of attention.
@param bidId Campaign id to which the query refers
@return { "budget" : "Total value (in wei) spendable in proof of attention rewards"}
*/
function getCampaignBudgetById(bytes32 bidId)
public
view
returns (uint budget) {
return campaigns[bidId].getBudget();
}
/**
@notice Set a new campaign budget
Based on the Campaign id, updates the total value avaliable for proof of attention
registrations. This function can only be executed by allowed addresses and emits a
CampaignUpdated event. This function does not transfer any funds as this contract only works
as a data repository, every logic needed will be processed in the Advertisement contract.
@param bidId Campaign id to which the query refers
@param newBudget New value for the total budget of the campaign
*/
function setCampaignBudgetById(bytes32 bidId, uint newBudget)
public
onlyIfCampaignExists("setCampaignBudgetById",bidId)
onlyIfWhitelisted("setCampaignBudgetById",msg.sender)
{
campaigns[bidId].setBudget(newBudget);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Get the start date of a campaign
Based on the Campaign id, return the value (in miliseconds) corresponding to the start Date
of the campaign.
@param bidId Campaign id to which the query refers
@return { "startDate" : "Start date (in miliseconds) of the campaign"}
*/
function getCampaignStartDateById(bytes32 bidId)
public
view
returns (uint startDate) {
return campaigns[bidId].getStartDate();
}
/**
@notice Set a new start date for a campaign
Based of the Campaign id, updates the start date of a campaign. This function can only be
executed by allowed addresses and emits a CampaignUpdated event.
@param bidId Campaign id to which the query refers
@param newStartDate New value (in miliseconds) for the start date of the campaign
*/
function setCampaignStartDateById(bytes32 bidId, uint newStartDate)
public
onlyIfCampaignExists("setCampaignStartDateById",bidId)
onlyIfWhitelisted("setCampaignStartDateById",msg.sender)
{
campaigns[bidId].setStartDate(newStartDate);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Get the end date of a campaign
Based on the Campaign id, return the value (in miliseconds) corresponding to the end Date
of the campaign.
@param bidId Campaign id to which the query refers
@return { "endDate" : "End date (in miliseconds) of the campaign"}
*/
function getCampaignEndDateById(bytes32 bidId)
public
view
returns (uint endDate) {
return campaigns[bidId].getEndDate();
}
/**
@notice Set a new end date for a campaign
Based of the Campaign id, updates the end date of a campaign. This function can only be
executed by allowed addresses and emits a CampaignUpdated event.
@param bidId Campaign id to which the query refers
@param newEndDate New value (in miliseconds) for the end date of the campaign
*/
function setCampaignEndDateById(bytes32 bidId, uint newEndDate)
public
onlyIfCampaignExists("setCampaignEndDateById",bidId)
onlyIfWhitelisted("setCampaignEndDateById",msg.sender)
{
campaigns[bidId].setEndDate(newEndDate);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Get information regarding validity of a campaign.
Based on the Campaign id, return a boolean which represents a valid campaign if it has
the value of True else has the value of False.
@param bidId Campaign id to which the query refers
@return { "valid" : "Validity of the campaign"}
*/
function getCampaignValidById(bytes32 bidId)
public
view
returns (bool valid) {
return campaigns[bidId].getValidity();
}
/**
@notice Set a new campaign validity state.
Updates the validity of a campaign based on a campaign Id. This function can only be
executed by allowed addresses and emits a CampaignUpdated event.
@param bidId Campaign id to which the query refers
@param isValid New value for the campaign validity
*/
function setCampaignValidById(bytes32 bidId, bool isValid)
public
onlyIfCampaignExists("setCampaignValidById",bidId)
onlyIfWhitelisted("setCampaignValidById",msg.sender)
{
campaigns[bidId].setValidity(isValid);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Get the owner of a campaign
Based on the Campaign id, return the address of the campaign owner.
@param bidId Campaign id to which the query refers
@return { "campOwner" : "Address of the campaign owner" }
*/
function getCampaignOwnerById(bytes32 bidId)
public
view
returns (address campOwner) {
return campaigns[bidId].getOwner();
}
/**
@notice Set a new campaign owner
Based on the Campaign id, update the owner of the refered campaign. This function can only
be executed by allowed addresses and emits a CampaignUpdated event.
@param bidId Campaign id to which the query refers
@param newOwner New address to be the owner of the campaign
*/
function setCampaignOwnerById(bytes32 bidId, address newOwner)
public
onlyIfCampaignExists("setCampaignOwnerById",bidId)
onlyIfWhitelisted("setCampaignOwnerById",msg.sender)
{
campaigns[bidId].setOwner(newOwner);
emitCampaignUpdated(campaigns[bidId]);
}
/**
@notice Function to emit campaign updates
It emits a CampaignUpdated event with the new campaign information.
*/
function emitCampaignUpdated(CampaignLibrary.Campaign storage campaign) private {
emit CampaignUpdated(
campaign.getBidId(),
campaign.getPrice(),
campaign.getBudget(),
campaign.getStartDate(),
campaign.getEndDate(),
campaign.getValidity(),
campaign.getOwner()
);
}
/**
@notice Function to emit campaign creations
It emits a CampaignCreated event with the new campaign created.
*/
function emitCampaignCreated(CampaignLibrary.Campaign storage campaign) private {
emit CampaignCreated(
campaign.getBidId(),
campaign.getPrice(),
campaign.getBudget(),
campaign.getStartDate(),
campaign.getEndDate(),
campaign.getValidity(),
campaign.getOwner()
);
}
/**
@notice Internal function to set most recent bidId
This value is stored to avoid conflicts between
Advertisement contract upgrades.
@param _newBidId Newer bidId
*/
function setLastBidId(bytes32 _newBidId) internal {
lastBidId = _newBidId;
}
/**
@notice Returns the greatest BidId ever registered to the contract
@return { '_lastBidId' : 'Greatest bidId registered to the contract'}
*/
function getLastBidId()
external
returns (bytes32 _lastBidId){
return lastBidId;
}
}
contract ExtendedAdvertisementStorage is BaseAdvertisementStorage {
mapping (bytes32 => string) campaignEndPoints;
event ExtendedCampaignEndPointCreated(
bytes32 bidId,
string endPoint
);
event ExtendedCampaignEndPointUpdated(
bytes32 bidId,
string endPoint
);
/**
@notice Get a Campaign information
Based on a camapaign Id (bidId), returns all stored information for that campaign.
@param _campaignId Id of the campaign
@return {
"_bidId" : "Id of the campaign",
"_price" : "Value to pay for each proof-of-attention",
"_budget" : "Total value avaliable to be spent on the campaign",
"_startDate" : "Start date of the campaign (in miliseconds)",
"_endDate" : "End date of the campaign (in miliseconds)"
"_valid" : "Boolean informing if the campaign is valid",
"_campOwner" : "Address of the campaing's owner",
}
*/
function getCampaign(bytes32 _campaignId)
public
view
returns (
bytes32 _bidId,
uint _price,
uint _budget,
uint _startDate,
uint _endDate,
bool _valid,
address _campOwner
) {
CampaignLibrary.Campaign storage campaign = _getCampaign(_campaignId);
return (
campaign.getBidId(),
campaign.getPrice(),
campaign.getBudget(),
campaign.getStartDate(),
campaign.getEndDate(),
campaign.getValidity(),
campaign.getOwner()
);
}
/**
@notice Add or update a campaign information
Based on a campaign Id (bidId), a campaign can be created (if non existent) or updated.
This function can only be called by the set of allowed addresses registered earlier.
An event will be emited during this function's execution, a CampaignCreated and a
ExtendedCampaignEndPointCreated event if the campaign does not exist yet or a
CampaignUpdated and a ExtendedCampaignEndPointUpdated event if the campaign id is already
registered.
@param _bidId Id of the campaign
@param _price Value to pay for each proof-of-attention
@param _budget Total value avaliable to be spent on the campaign
@param _startDate Start date of the campaign (in miliseconds)
@param _endDate End date of the campaign (in miliseconds)
@param _valid Boolean informing if the campaign is valid
@param _owner Address of the campaing's owner
@param _endPoint URL of the signing serivce
*/
function setCampaign (
bytes32 _bidId,
uint _price,
uint _budget,
uint _startDate,
uint _endDate,
bool _valid,
address _owner,
string _endPoint
)
public
onlyIfWhitelisted("setCampaign",msg.sender) {
bool newCampaign = (getCampaignOwnerById(_bidId) == 0x0);
_setCampaign(_bidId, _price, _budget, _startDate, _endDate, _valid, _owner);
campaignEndPoints[_bidId] = _endPoint;
if(newCampaign){
emit ExtendedCampaignEndPointCreated(_bidId,_endPoint);
} else {
emit ExtendedCampaignEndPointUpdated(_bidId,_endPoint);
}
}
/**
@notice Get campaign signing web service endpoint
Get the end point to which the user should submit the proof of attention to be signed
@param _bidId Id of the campaign
@return { "_endPoint": "URL for the signing web service"}
*/
function getCampaignEndPointById(bytes32 _bidId) public returns (string _endPoint){
return campaignEndPoints[_bidId];
}
/**
@notice Set campaign signing web service endpoint
Sets the webservice's endpoint to which the user should submit the proof of attention
@param _bidId Id of the campaign
@param _endPoint URL for the signing web service
*/
function setCampaignEndPointById(bytes32 _bidId, string _endPoint)
public
onlyIfCampaignExists("setCampaignEndPointById",_bidId)
onlyIfWhitelisted("setCampaignEndPointById",msg.sender)
{
campaignEndPoints[_bidId] = _endPoint;
emit ExtendedCampaignEndPointUpdated(_bidId,_endPoint);
}
}
contract BaseAdvertisement is StorageUser,Ownable {
AppCoins appc;
BaseFinance advertisementFinance;
BaseAdvertisementStorage advertisementStorage;
mapping( bytes32 => mapping(address => uint256)) userAttributions;
bytes32[] bidIdList;
bytes32 lastBidId = 0x0;
/**
@notice Constructor function
Initializes contract with default validation rules
@param _addrAppc Address of the AppCoins (ERC-20) contract
@param _addrAdverStorage Address of the Advertisement Storage contract to be used
@param _addrAdverFinance Address of the Advertisement Finance contract to be used
*/
constructor(address _addrAppc, address _addrAdverStorage, address _addrAdverFinance) public {
appc = AppCoins(_addrAppc);
advertisementStorage = BaseAdvertisementStorage(_addrAdverStorage);
advertisementFinance = BaseFinance(_addrAdverFinance);
lastBidId = advertisementStorage.getLastBidId();
}
/**
@notice Upgrade finance contract used by this contract
This function is part of the upgrade mechanism avaliable to the advertisement contracts.
Using this function it is possible to update to a new Advertisement Finance contract without
the need to cancel avaliable campaigns.
Upgrade finance function can only be called by the Advertisement contract owner.
@param addrAdverFinance Address of the new Advertisement Finance contract
*/
function upgradeFinance (address addrAdverFinance) public onlyOwner("upgradeFinance") {
BaseFinance newAdvFinance = BaseFinance(addrAdverFinance);
address[] memory devList = advertisementFinance.getUserList();
for(uint i = 0; i < devList.length; i++){
uint balance = advertisementFinance.getUserBalance(devList[i]);
newAdvFinance.increaseBalance(devList[i],balance);
}
uint256 initBalance = appc.balanceOf(address(advertisementFinance));
advertisementFinance.transferAllFunds(address(newAdvFinance));
uint256 oldBalance = appc.balanceOf(address(advertisementFinance));
uint256 newBalance = appc.balanceOf(address(newAdvFinance));
require(initBalance == newBalance);
require(oldBalance == 0);
advertisementFinance = newAdvFinance;
}
/**
@notice Upgrade storage contract used by this contract
Upgrades Advertisement Storage contract addres with no need to redeploy
Advertisement contract. However every campaign in the old contract will
be canceled.
This function can only be called by the Advertisement contract owner.
@param addrAdverStorage Address of the new Advertisement Storage contract
*/
function upgradeStorage (address addrAdverStorage) public onlyOwner("upgradeStorage") {
for(uint i = 0; i < bidIdList.length; i++) {
cancelCampaign(bidIdList[i]);
}
delete bidIdList;
lastBidId = advertisementStorage.getLastBidId();
advertisementFinance.setAdsStorageAddress(addrAdverStorage);
advertisementStorage = BaseAdvertisementStorage(addrAdverStorage);
}
/**
@notice Get Advertisement Storage Address used by this contract
This function is required to upgrade Advertisement contract address on Advertisement
Finance contract. This function can only be called by the Advertisement Finance
contract registered in this contract.
@return {
"storageContract" : "Address of the Advertisement Storage contract used by this contract"
}
*/
function getStorageAddress() public view returns(address storageContract) {
require (msg.sender == address(advertisementFinance));
return address(advertisementStorage);
}
/**
@notice Creates a campaign
Method to create a campaign of user aquisition for a certain application.
This method will emit a Campaign Information event with every information
provided in the arguments of this method.
@param packageName Package name of the appication subject to the user aquisition campaign
@param countries Encoded list of 3 integers intended to include every
county where this campaign will be avaliable.
For more detain on this encoding refer to wiki documentation.
@param vercodes List of version codes to which the user aquisition campaign is applied.
@param price Value (in wei) the campaign owner pays for each proof-of-attention.
@param budget Total budget (in wei) the campaign owner will deposit
to pay for the proof-of-attention.
@param startDate Date (in miliseconds) on which the campaign will start to be
avaliable to users.
@param endDate Date (in miliseconds) on which the campaign will no longer be avaliable to users.
*/
function _generateCampaign (
string packageName,
uint[3] countries,
uint[] vercodes,
uint price,
uint budget,
uint startDate,
uint endDate)
internal returns (CampaignLibrary.Campaign memory) {
require(budget >= price);
require(endDate >= startDate);
//Transfers the budget to contract address
if(appc.allowance(msg.sender, address(this)) >= budget){
appc.transferFrom(msg.sender, address(advertisementFinance), budget);
advertisementFinance.increaseBalance(msg.sender,budget);
uint newBidId = bytesToUint(lastBidId);
lastBidId = uintToBytes(++newBidId);
CampaignLibrary.Campaign memory newCampaign;
newCampaign.price = price;
newCampaign.startDate = startDate;
newCampaign.endDate = endDate;
newCampaign.budget = budget;
newCampaign.owner = msg.sender;
newCampaign.valid = true;
newCampaign.bidId = lastBidId;
} else {
emit Error("createCampaign","Not enough allowance");
}
return newCampaign;
}
function _getStorage() internal returns (BaseAdvertisementStorage) {
return advertisementStorage;
}
function _getFinance() internal returns (BaseFinance) {
return advertisementFinance;
}
function _setUserAttribution(bytes32 _bidId,address _user,uint256 _attributions) internal{
userAttributions[_bidId][_user] = _attributions;
}
function getUserAttribution(bytes32 _bidId,address _user) internal returns (uint256) {
return userAttributions[_bidId][_user];
}
/**
@notice Cancel a campaign and give the remaining budget to the campaign owner
When a campaing owner wants to cancel a campaign, the campaign owner needs
to call this function. This function can only be called either by the campaign owner or by
the Advertisement contract owner. This function results in campaign cancelation and
retreival of the remaining budget to the respective campaign owner.
@param bidId Campaign id to which the cancelation referes to
*/
function cancelCampaign (bytes32 bidId) public {
address campaignOwner = getOwnerOfCampaign(bidId);
// Only contract owner or campaign owner can cancel a campaign
require(owner == msg.sender || campaignOwner == msg.sender);
uint budget = getBudgetOfCampaign(bidId);
advertisementFinance.withdraw(campaignOwner, budget);
advertisementStorage.setCampaignBudgetById(bidId, 0);
advertisementStorage.setCampaignValidById(bidId, false);
}
/**
@notice Get a campaign validity state
@param bidId Campaign id to which the query refers
@return { "state" : "Validity of the campaign"}
*/
function getCampaignValidity(bytes32 bidId) public view returns(bool state){
return advertisementStorage.getCampaignValidById(bidId);
}
/**
@notice Get the price of a campaign
Based on the Campaign id return the value paid for each proof of attention registered.
@param bidId Campaign id to which the query refers
@return { "price" : "Reward (in wei) for each proof of attention registered"}
*/
function getPriceOfCampaign (bytes32 bidId) public view returns(uint price) {
return advertisementStorage.getCampaignPriceById(bidId);
}
/**
@notice Get the start date of a campaign
Based on the Campaign id return the value (in miliseconds) corresponding to the start Date
of the campaign.
@param bidId Campaign id to which the query refers
@return { "startDate" : "Start date (in miliseconds) of the campaign"}
*/
function getStartDateOfCampaign (bytes32 bidId) public view returns(uint startDate) {
return advertisementStorage.getCampaignStartDateById(bidId);
}
/**
@notice Get the end date of a campaign
Based on the Campaign id return the value (in miliseconds) corresponding to the end Date
of the campaign.
@param bidId Campaign id to which the query refers
@return { "endDate" : "End date (in miliseconds) of the campaign"}
*/
function getEndDateOfCampaign (bytes32 bidId) public view returns(uint endDate) {
return advertisementStorage.getCampaignEndDateById(bidId);
}
/**
@notice Get the budget avaliable of a campaign
Based on the Campaign id return the total value avaliable to pay for proofs of attention.
@param bidId Campaign id to which the query refers
@return { "budget" : "Total value (in wei) spendable in proof of attention rewards"}
*/
function getBudgetOfCampaign (bytes32 bidId) public view returns(uint budget) {
return advertisementStorage.getCampaignBudgetById(bidId);
}
/**
@notice Get the owner of a campaign
Based on the Campaign id return the address of the campaign owner
@param bidId Campaign id to which the query refers
@return { "campaignOwner" : "Address of the campaign owner" }
*/
function getOwnerOfCampaign (bytes32 bidId) public view returns(address campaignOwner) {
return advertisementStorage.getCampaignOwnerById(bidId);
}
/**
@notice Get the list of Campaign BidIds registered in the contract
Returns the list of BidIds of the campaigns ever registered in the contract
@return { "bidIds" : "List of BidIds registered in the contract" }
*/
function getBidIdList() public view returns(bytes32[] bidIds) {
return bidIdList;
}
function _getBidIdList() internal returns(bytes32[] storage bidIds){
return bidIdList;
}
/**
@notice Check if a certain campaign is still valid
Returns a boolean representing the validity of the campaign
Has value of True if the campaign is still valid else has value of False
@param bidId Campaign id to which the query refers
@return { "valid" : "validity of the campaign" }
*/
function isCampaignValid(bytes32 bidId) public view returns(bool valid) {
uint startDate = advertisementStorage.getCampaignStartDateById(bidId);
uint endDate = advertisementStorage.getCampaignEndDateById(bidId);
bool validity = advertisementStorage.getCampaignValidById(bidId);
uint nowInMilliseconds = now * 1000;
return validity && startDate < nowInMilliseconds && endDate > nowInMilliseconds;
}
/**
@notice Returns the division of two numbers
Function used for division operations inside the smartcontract
@param numerator Numerator part of the division
@param denominator Denominator part of the division
@return { "result" : "Result of the division"}
*/
function division(uint numerator, uint denominator) public view returns (uint result) {
uint _quotient = numerator / denominator;
return _quotient;
}
/**
@notice Converts a uint256 type variable to a byte32 type variable
Mostly used internaly
@param i number to be converted
@return { "b" : "Input number converted to bytes"}
*/
function uintToBytes (uint256 i) public view returns(bytes32 b) {
b = bytes32(i);
}
function bytesToUint(bytes32 b) public view returns (uint)
{
return uint(b) & 0xfff;
}
}
contract Signature {
/**
@notice splitSignature
Based on a signature Sig (bytes32), returns the r, s, v
@param sig Signature
@return {
"uint8" : "recover Id",
"bytes32" : "Output of the ECDSA signature",
"bytes32" : "Output of the ECDSA signature",
}
*/
function splitSignature(bytes sig)
internal
pure
returns (uint8, bytes32, bytes32)
{
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
/**
@notice recoverSigner
Based on a message and signature returns the address
@param message Message
@param sig Signature
@return {
"address" : "Address of the private key that signed",
}
*/
function recoverSigner(bytes32 message, bytes sig)
public
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
}
contract BaseFinance is SingleAllowance {
mapping (address => uint256) balanceUsers;
mapping (address => bool) userExists;
address[] users;
address advStorageContract;
AppCoins appc;
/**
@notice Constructor function
Initializes contract with the AppCoins contract address
@param _addrAppc Address of the AppCoins (ERC-20) contract
*/
constructor (address _addrAppc)
public {
appc = AppCoins(_addrAppc);
advStorageContract = 0x0;
}
/**
@notice Sets the Storage contract address used by the allowed contract
The Storage contract address is mostly used as part of a failsafe mechanism to
ensure contract upgrades are executed using the same Storage
contract. This function returns every value of AppCoins stored in this contract to their
owners. This function can only be called by the
Finance contract owner or by the allowed contract registered earlier in
this contract.
@param _addrStorage Address of the new Storage contract
*/
function setAdsStorageAddress (address _addrStorage) external onlyOwnerOrAllowed {
reset();
advStorageContract = _addrStorage;
}
/**
@notice Sets the Advertisement contract address to allow calls from Advertisement contract
This function is used for upgrading the Advertisement contract without need to redeploy
Advertisement Finance and Advertisement Storage contracts. The function can only be called
by this contract's owner. During the update of the Advertisement contract address, the
contract for Advertisement Storage used by the new Advertisement contract is checked.
This function reverts if the new Advertisement contract does not use the same Advertisement
Storage contract earlier registered in this Advertisement Finance contract.
@param _addr Address of the newly allowed contract
*/
function setAllowedAddress (address _addr) public onlyOwner("setAllowedAddress") {
// Verify if the new Ads contract is using the same storage as before
if (allowedAddress != 0x0){
StorageUser storageUser = StorageUser(_addr);
address storageContract = storageUser.getStorageAddress();
require (storageContract == advStorageContract);
}
//Update contract
super.setAllowedAddress(_addr);
}
/**
@notice Increases balance of a user
This function can only be called by the registered Advertisement contract and increases the
balance of a specific user on this contract. This function does not transfer funds,
this step need to be done earlier by the Advertisement contract. This function can only be
called by the registered Advertisement contract.
@param _user Address of the user who will receive a balance increase
@param _value Value of coins to increase the user's balance
*/
function increaseBalance(address _user, uint256 _value)
public onlyAllowed{
if(userExists[_user] == false){
users.push(_user);
userExists[_user] = true;
}
balanceUsers[_user] += _value;
}
/**
@notice Transfers coins from a certain user to a destination address
Used to release a certain value of coins from a certain user to a destination address.
This function updates the user's balance in the contract. It can only be called by the
Advertisement contract registered.
@param _user Address of the user from which the value will be subtracted
@param _destination Address receiving the value transfered
@param _value Value to be transfered in AppCoins
*/
function pay(address _user, address _destination, uint256 _value) public onlyAllowed;
/**
@notice Withdraws a certain value from a user's balance back to the user's account
Can be called from the Advertisement contract registered or by this contract's owner.
@param _user Address of the user
@param _value Value to be transfered in AppCoins
*/
function withdraw(address _user, uint256 _value) public onlyOwnerOrAllowed;
/**
@notice Resets this contract and returns every amount deposited to each user registered
This function is used in case a contract reset is needed or the contract needs to be
deactivated. Thus returns every fund deposited to it's respective owner.
*/
function reset() public onlyOwnerOrAllowed {
for(uint i = 0; i < users.length; i++){
withdraw(users[i],balanceUsers[users[i]]);
}
}
/**
@notice Transfers all funds of the contract to a single address
This function is used for finance contract upgrades in order to be more cost efficient.
@param _destination Address receiving the funds
*/
function transferAllFunds(address _destination) public onlyAllowed {
uint256 balance = appc.balanceOf(address(this));
appc.transfer(_destination,balance);
}
/**
@notice Get balance of coins stored in the contract by a specific user
This function can only be called by the Advertisement contract
@param _user Developer's address
@return { '_balance' : 'Balance of coins deposited in the contract by the address' }
*/
function getUserBalance(address _user) public view onlyAllowed returns(uint256 _balance){
return balanceUsers[_user];
}
/**
@notice Get list of users with coins stored in the contract
This function can only be called by the Advertisement contract
@return { '_userList' : ' List of users registered in the contract'}
*/
function getUserList() public view onlyAllowed returns(address[] _userList){
return users;
}
}
contract ExtendedFinance is BaseFinance {
mapping ( address => uint256 ) rewardedBalance;
constructor(address _appc) public BaseFinance(_appc){
}
function pay(address _user, address _destination, uint256 _value)
public onlyAllowed{
require(balanceUsers[_user] >= _value);
balanceUsers[_user] -= _value;
rewardedBalance[_destination] += _value;
}
function withdraw(address _user, uint256 _value) public onlyOwnerOrAllowed {
require(balanceUsers[_user] >= _value);
balanceUsers[_user] -= _value;
appc.transfer(_user, _value);
}
/**
@notice Withdraws user's rewards
Function to transfer a certain user's rewards to his address
@param _user Address who's rewards will be withdrawn
@param _value Value of the withdraws which will be transfered to the user
*/
function withdrawRewards(address _user, uint256 _value) public onlyOwnerOrAllowed {
require(rewardedBalance[_user] >= _value);
rewardedBalance[_user] -= _value;
appc.transfer(_user, _value);
}
/**
@notice Get user's rewards balance
Function returning a user's rewards balance not yet withdrawn
@param _user Address of the user
@return { "_balance" : "Rewards balance of the user" }
*/
function getRewardsBalance(address _user) public onlyOwnerOrAllowed returns (uint256 _balance) {
return rewardedBalance[_user];
}
}
contract ExtendedAdvertisement is BaseAdvertisement, Whitelist, Signature {
event BulkPoARegistered(bytes32 bidId, bytes32 rootHash, bytes signedrootHash, uint256 newPoAs, uint256 convertedPoAs);
event CampaignInformation
(
bytes32 bidId,
address owner,
string ipValidator,
string packageName,
uint[3] countries,
uint[] vercodes,
string endpoint
);
constructor(address _addrAppc, address _addrAdverStorage, address _addrAdverFinance) public
BaseAdvertisement(_addrAppc,_addrAdverStorage,_addrAdverFinance) {
addAddressToWhitelist(msg.sender);
}
/**
@notice Creates an extebded campaign
Method to create an extended campaign of user aquisition for a certain application.
This method will emit a Campaign Information event with every information
provided in the arguments of this method.
@param packageName Package name of the appication subject to the user aquisition campaign
@param countries Encoded list of 3 integers intended to include every
county where this campaign will be avaliable.
For more detain on this encoding refer to wiki documentation.
@param vercodes List of version codes to which the user aquisition campaign is applied.
@param price Value (in wei) the campaign owner pays for each proof-of-attention.
@param budget Total budget (in wei) the campaign owner will deposit
to pay for the proof-of-attention.
@param startDate Date (in miliseconds) on which the campaign will start to be
avaliable to users.
@param endDate Date (in miliseconds) on which the campaign will no longer be avaliable to users.
@param endPoint URL of the signing serivce
*/
function createCampaign (
string packageName,
uint[3] countries,
uint[] vercodes,
uint price,
uint budget,
uint startDate,
uint endDate,
string endPoint)
external
{
CampaignLibrary.Campaign memory newCampaign = _generateCampaign(packageName, countries, vercodes, price, budget, startDate, endDate);
if(newCampaign.owner == 0x0){
// campaign was not generated correctly (revert)
return;
}
_getBidIdList().push(newCampaign.bidId);
ExtendedAdvertisementStorage(address(_getStorage())).setCampaign(
newCampaign.bidId,
newCampaign.price,
newCampaign.budget,
newCampaign.startDate,
newCampaign.endDate,
newCampaign.valid,
newCampaign.owner,
endPoint);
emit CampaignInformation(
newCampaign.bidId,
newCampaign.owner,
"", // ipValidator field
packageName,
countries,
vercodes,
endPoint);
}
/**
@notice Function to submit in bulk PoAs
This function can only be called by whitelisted addresses and provides a cost efficient
method to submit a batch of validates PoAs at once. This function emits a PoaRegistered
event containing the campaign id, root hash, signed root hash, number of new hashes since
the last submission and the effective number of conversions.
@param bidId Campaign id for which the Proof of attention root hash refferes to
@param rootHash Root hash of all submitted proof of attention to a given campaign
@param signedRootHash Root hash signed by the signing service of the campaign
@param newHashes Number of new proof of attention hashes since last submission
*/
function bulkRegisterPoA(bytes32 bidId, bytes32 rootHash, bytes signedRootHash, uint256 newHashes)
public
onlyIfWhitelisted("createCampaign",msg.sender)
{
address addressSig = recoverSigner(rootHash, signedRootHash);
if (msg.sender != addressSig) {
emit Error("bulkRegisterPoA","Invalid signature");
return;
}
uint price = _getStorage().getCampaignPriceById(bidId);
uint budget = _getStorage().getCampaignBudgetById(bidId);
address owner = _getStorage().getCampaignOwnerById(bidId);
uint maxConversions = division(budget,price);
uint effectiveConversions;
uint totalPay;
uint newBudget;
if (maxConversions >= newHashes){
effectiveConversions = newHashes;
} else {
effectiveConversions = maxConversions;
}
totalPay = price*effectiveConversions;
newBudget = budget - totalPay;
_getFinance().pay(owner,msg.sender,totalPay);
_getStorage().setCampaignBudgetById(bidId,newBudget);
if(newBudget < price){
_getStorage().setCampaignValidById(bidId,false);
}
emit BulkPoARegistered(bidId,rootHash,signedRootHash,newHashes,effectiveConversions);
}
/**
@notice Function to withdraw PoA convertions
This function is restricted to addresses allowed to submit bulk PoAs and enable those
addresses to withdraw funds previously collected by bulk PoA submissions
*/
function withdraw()
public
onlyIfWhitelisted("withdraw",msg.sender)
{
uint256 balance = ExtendedFinance(address(_getFinance())).getRewardsBalance(msg.sender);
ExtendedFinance(address(_getFinance())).withdrawRewards(msg.sender,balance);
}
/**
@notice Get user's balance of funds obtainded by rewards
Anyone can call this function and get the rewards balance of a certain user.
@param _user Address from which the balance refers to
@return { "_balance" : "" } */
function getRewardsBalance(address _user) public view returns (uint256 _balance) {
return ExtendedFinance(address(_getFinance())).getRewardsBalance(_user);
}
/**
@notice Returns the signing Endpoint of a camapign
Function returning the Webservice URL responsible for validating and signing a PoA
@param bidId Campaign id to which the Endpoint is associated
@return { "url" : "Validation and signature endpoint"}
*/
function getEndPointOfCampaign (bytes32 bidId) public view returns (string url){
return ExtendedAdvertisementStorage(address(_getStorage())).getCampaignEndPointById(bidId);
}
} | Allows the current owner to transfer control of the contract to a newOwner. _newOwner The address to transfer ownership to./ | function transferOwnership(address _newOwner) public onlyOwner("transferOwnership") {
_transferOwnership(_newOwner);
}
| 5,522,960 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
//importar interface ierc20
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);
}
contract MaticPayment {
IERC20 public derc20 = IERC20(0xfe4F5145f6e09952a5ba9e956ED0C25e3Fa4c7F1);
address payable public owner; // contract creator's address
constructor() {
owner = payable(msg.sender); // setting the contract creator
}
// Function to deposit Ether into this contract
function deposit(uint amount) public {
derc20.transferFrom(msg.sender,address(this),amount);
}
// Function to withdraw all Ether from this contract.
function withdraw() public {
derc20.transfer(owner,derc20.balanceOf(address(this)));
}
} | Function to withdraw all Ether from this contract. | function withdraw() public {
derc20.transfer(owner,derc20.balanceOf(address(this)));
}
| 12,860,548 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ====================== UniV3LiquidityAMO_V2 ========================
// ====================================================================
// Creates Uni v3 positions between Frax and other stablecoins/assets
// Earns money on swap fees
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Jason Huan: https://github.com/jasonhuan
// Reviewer(s) / Contributor(s)
// Sam Kazemian: https://github.com/samkazemian
// Travis Moore: https://github.com/FortisFortuna
import "../Frax/Frax.sol";
import "../Frax/Pools/FraxPool.sol";
import "../Frax/IFraxAMOMinter.sol";
import "../FXS/FXS.sol";
import "../Math/Math.sol";
import "../Math/SafeMath.sol";
import "../ERC20/ERC20.sol";
import "../ERC20/SafeERC20.sol";
import '../Uniswap/TransferHelper.sol';
import "../Staking/Owned.sol";
import "../Uniswap_V3/IUniswapV3Factory.sol";
import "../Uniswap_V3/libraries/TickMath.sol";
import "../Uniswap_V3/libraries/LiquidityAmounts.sol";
import "../Uniswap_V3/periphery/interfaces/INonfungiblePositionManager.sol";
import "../Uniswap_V3/IUniswapV3Pool.sol";
import "../Uniswap_V3/ISwapRouter.sol";
contract UniV3LiquidityAMO_V2 is Owned {
using SafeMath for uint256;
using SafeERC20 for ERC20;
/* ========== STATE VARIABLES ========== */
// Core
FRAXStablecoin private FRAX;
FRAXShares private FXS;
IFraxAMOMinter private amo_minter;
ERC20 private giveback_collateral;
address public giveback_collateral_address;
uint256 public missing_decimals_giveback_collat;
address public timelock_address;
address public custodian_address;
// Uniswap v3
IUniswapV3Factory public univ3_factory;
INonfungiblePositionManager public univ3_positions;
ISwapRouter public univ3_router;
// Price constants
uint256 private constant PRICE_PRECISION = 1e6;
// Wildcat AMO
// Details about the AMO's uniswap positions
struct Position {
uint256 token_id;
address collateral_address;
uint128 liquidity; // the liquidity of the position
int24 tickLower; // the tick range of the position
int24 tickUpper;
uint24 fee_tier;
}
// Array of all Uni v3 NFT positions held by the AMO
Position[] public positions_array;
// List of all collaterals
address[] public collateral_addresses;
mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification
// Map token_id to Position
mapping(uint256 => Position) public positions_mapping;
/* ========== CONSTRUCTOR ========== */
constructor(
address _creator_address,
address _giveback_collateral_address,
address _amo_minter_address
) Owned(_creator_address) {
FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e);
FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0);
giveback_collateral_address = _giveback_collateral_address;
giveback_collateral = ERC20(_giveback_collateral_address);
missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals());
collateral_addresses.push(_giveback_collateral_address);
allowed_collaterals[_giveback_collateral_address] = true;
univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984);
univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88);
univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564);
// Initialize the minter
amo_minter = IFraxAMOMinter(_amo_minter_address);
// Get the custodian and timelock addresses from the minter
custodian_address = amo_minter.custodian_address();
timelock_address = amo_minter.timelock_address();
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyByOwnGovCust() {
require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd");
_;
}
modifier onlyByMinter() {
require(msg.sender == address(amo_minter), "Not minter");
_;
}
/* ========== VIEWS ========== */
function showAllocations() public view returns (uint256[4] memory allocations) {
// All numbers given are in FRAX unless otherwise stated
// Unallocated FRAX
allocations[0] = FRAX.balanceOf(address(this));
// Unallocated Collateral Dollar Value (E18)
allocations[1] = freeColDolVal();
// Sum of Uni v3 Positions liquidity, if it was all in FRAX
allocations[2] = TotalLiquidityFrax();
// Total Value
allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]);
}
// E18 Collateral dollar value
function freeColDolVal() public view returns (uint256) {
uint256 value_tally_e18 = 0;
for (uint i = 0; i < collateral_addresses.length; i++){
ERC20 thisCollateral = ERC20(collateral_addresses[i]);
uint256 missing_decs = uint256(18).sub(thisCollateral.decimals());
uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs);
value_tally_e18 = value_tally_e18.add(col_bal_e18);
}
return value_tally_e18;
}
// Needed for the Frax contract to function
function collatDollarBalance() public view returns (uint256) {
// Get the allocations
uint256[4] memory allocations = showAllocations();
// Get the collateral and FRAX portions
uint256 collat_portion = allocations[1];
uint256 frax_portion = (allocations[0]).add(allocations[2]);
// Assumes worst case scenario if FRAX slips out of range.
// Otherwise, it would only be half that is multiplied by the CR
frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION);
return (collat_portion).add(frax_portion);
}
function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) {
frax_val_e18 = showAllocations()[3];
collat_val_e18 = collatDollarBalance();
}
function TotalLiquidityFrax() public view returns (uint256) {
uint256 frax_tally = 0;
Position memory thisPosition;
for (uint256 i = 0; i < positions_array.length; i++) {
thisPosition = positions_array[i];
uint128 this_liq = thisPosition.liquidity;
if (this_liq > 0){
uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower);
uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper);
if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0
frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq));
}
else {
frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq));
}
}
}
// Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side
return frax_tally;
}
// Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool
function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) {
IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee));
// goes into the pool's positions mapping, and grabs this address's liquidity
(uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper)));
return liquidity;
}
// Backwards compatibility
function mintedBalance() public view returns (int256) {
return amo_minter.frax_mint_balances(address(this));
}
// Backwards compatibility
function collateralBalance() public view returns (int256) {
return amo_minter.collat_borrowed_balances(address(this));
}
// Only counts non-withdrawn positions
function numPositions() public view returns (uint256) {
return positions_array.length;
}
function allCollateralAddresses() external view returns (address[] memory) {
return collateral_addresses;
}
/* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */
// Iterate through all positions and collect fees accumulated
function collectFees() external onlyByOwnGovCust {
for (uint i = 0; i < positions_array.length; i++){
Position memory current_position = positions_array[i];
INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams(
current_position.token_id,
custodian_address,
type(uint128).max,
type(uint128).max
);
// Send to custodian address
univ3_positions.collect(collect_params);
}
}
/* ---------------------------------------------------- */
/* ---------------------- Uni v3 ---------------------- */
/* ---------------------------------------------------- */
function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov {
if (use_safe_approve) {
// safeApprove needed for USDT and others for the first approval
// You need to approve 0 every time beforehand for USDT: it resets
TransferHelper.safeApprove(_token, _target, _amount);
}
else {
ERC20(_token).approve(_target, _amount);
}
}
IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity()
function addLiquidity(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint128 _amountLiquidity, uint128 _maxToken0, uint128 _maxToken1) public onlyByOwnGov {
// getPool() [token0] or [token1] order doesn't matter
address pool_address = univ3_factory.getPool(address(FRAX), _collateral_address, _fee);
// set pool for callback
current_uni_pool = IUniswapV3Pool(pool_address);
bytes memory data = abi.encode(msg.sender, _maxToken0, _maxToken1);
IUniswapV3Pool uni_v3_pool = IUniswapV3Pool(pool_address);
uni_v3_pool.mint(
address(this),
_tickLower,
_tickUpper,
_amountLiquidity,
data
);
}
/*
** callback from minting uniswap v3 range
*/
function uniswapV3MintCallback(uint256 _amount0, uint256 _amount1, bytes calldata _data) public {
(address minter, uint128 maxToken0, uint128 maxToken1) = abi.decode(_data, (address,uint128,uint128));
require(_amount0 <= maxToken0, "maxToken0 exceeded");
require(_amount1 <= maxToken1, "maxToken1 exceeded");
require(address(current_uni_pool) == msg.sender, "only permissioned UniswapV3 pair can call");
if (_amount0 > 0) require(IERC20(current_uni_pool.token0()).transferFrom(minter, address(msg.sender), _amount0), "token0 transfer failed");
if (_amount1 > 0) require(IERC20(current_uni_pool.token1()).transferFrom(minter, address(msg.sender), _amount1), "token1 transfer failed");
}
/*
** burn tokenAmount from the recipient and send tokens to the receipient
*/
function removeLiquidity(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint128 _amountLiquidity) public onlyByOwnGov {
address pool_address;
if(_collateral_address < address(FRAX)){
pool_address = univ3_factory.getPool(_collateral_address, address(FRAX), _fee);
} else {
pool_address = univ3_factory.getPool(address(FRAX), _collateral_address, _fee);
}
IUniswapV3Pool uni_v3_pool = IUniswapV3Pool(pool_address);
(uint256 amount0, uint256 amount1) = uni_v3_pool.burn(_tickLower, _tickUpper, _amountLiquidity);
uni_v3_pool.collect(address(this), _tickLower, _tickUpper, uint128(amount0), uint128(amount1));
}
// Swap tokenA into tokenB using univ3_router.ExactInputSingle()
// Uni V3 only
function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) {
// Make sure the collateral is allowed
require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed");
require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed");
ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams(
_tokenA,
_tokenB,
_fee_tier,
address(this),
2105300114, // Expiration: a long time from now
_amountAtoB,
_amountOutMinimum,
_sqrtPriceLimitX96
);
// Approval
TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB);
uint256 amountOut = univ3_router.exactInputSingle(swap_params);
return amountOut;
}
/* ========== Burns and givebacks ========== */
// Give USDC profits back. Goes through the minter
function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust {
giveback_collateral.approve(address(amo_minter), collat_amount);
amo_minter.receiveCollatFromAMO(collat_amount);
}
// Burn unneeded or excess FRAX. Goes through the minter
function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust {
FRAX.approve(address(amo_minter), frax_amount);
amo_minter.burnFraxFromAMO(frax_amount);
}
// Burn unneeded FXS. Goes through the minter
function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust {
FXS.approve(address(amo_minter), fxs_amount);
amo_minter.burnFxsFromAMO(fxs_amount);
}
/* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */
// Only owner or timelock can call, to limit risk
// Adds collateral addresses supported. Needed to make sure dollarBalances is correct
function addCollateral(address collat_addr) public onlyByOwnGov {
require(collat_addr != address(0), "Zero address detected");
require(collat_addr != address(FRAX), "FRAX is not collateral");
require(allowed_collaterals[collat_addr] == false, "Address already exists");
allowed_collaterals[collat_addr] = true;
collateral_addresses.push(collat_addr);
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
// Can only be triggered by owner or governance, not custodian
// Tokens are sent to the custodian, as a sort of safeguard
TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount);
emit RecoveredERC20(tokenAddress, tokenAmount);
}
function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov {
// Only the owner address can ever receive the recovery withdrawal
// INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported
INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id);
emit RecoveredERC721(tokenAddress, token_id);
}
// Generic proxy
function execute(
address _to,
uint256 _value,
bytes calldata _data
) external onlyByOwnGov returns (bool, bytes memory) {
(bool success, bytes memory result) = _to.call{value:_value}(_data);
return (success, result);
}
/* ========== EVENTS ========== */
event RecoveredERC20(address token, uint256 amount);
event RecoveredERC721(address token, uint256 id);
} | Iterate through all positions and collect fees accumulated | function collectFees() external onlyByOwnGovCust {
for (uint i = 0; i < positions_array.length; i++){
Position memory current_position = positions_array[i];
INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams(
current_position.token_id,
custodian_address,
type(uint128).max,
type(uint128).max
);
univ3_positions.collect(collect_params);
}
}
| 12,862,081 |
./partial_match/43113/0x5251D3B66fe387019c086b0243b21C75f8AA01fa/sources/contracts/contracts/sapphire/SapphirePassportScores.sol | Sets the merkle root updater/ | function setMerkleRootUpdater(
address _merkleRootUpdater
)
external
override
onlyAdmin
{
require(
_merkleRootUpdater != merkleRootUpdater,
"SapphirePassportScores: cannot set the same merkle root updater"
);
merkleRootUpdater = _merkleRootUpdater;
emit MerkleRootUpdaterUpdated(merkleRootUpdater);
}
| 16,907,219 |
./full_match/137/0xD5B88558a807D5F394e0F22743D4F1C5eAb76B6F/sources/project_/contracts/payment-token/PaymentTokenRegistry.sol | See {IPaymentTokenRegistry-addCollectionPaymentToken}./ | function addCollectionPaymentToken(address collectionAddress, address token)
external
onlyOwner
{
require(
!_collectionPaymentTokens[collectionAddress].contains(token),
"PaymentTokenRegistry: token already exist for this collection"
);
_collectionPaymentTokens[collectionAddress].add(token);
emit CollectionPaymentTokenAdded(
collectionAddress,
token,
_msgSender()
);
}
| 4,694,221 |
/**
*Submitted for verification at Etherscan.io on 2021-08-08
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.4;
////////////////////////////////
///////////// ERC //////////////
////////////////////////////////
/*
* @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 payable(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.
*/
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;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
////////////////////////////////
////////// Dividend ////////////
////////////////////////////////
/*
@title Dividend-Paying Token Interface
@author Roger Wu (https://github.com/roger-wu)
@dev An interface for a dividend-paying token contract.
*/
interface IDividendPayingToken {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/*
@title Dividend-Paying Token Optional Interface
@author Roger Wu (https://github.com/roger-wu)
@dev OPTIONAL functions for a dividend-paying token contract.
*/
interface IDividendPayingTokenOptional {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
}
/*
@title Dividend-Paying Token
@author Roger Wu (https://github.com/roger-wu)
@dev A mintable ERC20 token that allows anyone to pay and distribute ether
to token holders as dividends and allows token holders to withdraw their dividends.
Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
*/
contract DividendPayingToken is ERC20, IDividendPayingToken, IDividendPayingTokenOptional {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
uint256 internal lastAmount;
address public dividendToken = 0x3301Ee63Fb29F863f2333Bd4466acb46CD8323E6;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
uint256 public totalDividendsDistributed;
uint256 public gasForTransfer;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
gasForTransfer = 3000;
}
receive() external payable {
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
function distributeDividends(uint256 amount) public {
require(totalSupply() > 0);
if (amount > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(amount).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, amount);
totalDividendsDistributed = totalDividendsDistributed.add(amount);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(payable(msg.sender));
}
function setDividendTokenAddress(address newToken) public {
dividendToken = newToken;
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
bool success = IERC20(dividendToken).transfer(user, _withdrawableDividend);
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
////////////////////////////////
///////// Interfaces ///////////
////////////////////////////////
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
////////////////////////////////
////////// Libraries ///////////
////////////////////////////////
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
/**
* @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;
}
}
/**
* @title SafeMathInt
* @dev Math operations with safety checks that revert on error
* @dev SafeMath adapted for int256
* Based on code of https://github.com/RequestNetwork/requestNetwork/blob/master/packages/requestNetworkSmartContracts/contracts/base/math/SafeMathInt.sol
*/
library SafeMathInt {
function mul(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when multiplying INT256_MIN with -1
// https://github.com/RequestNetwork/requestNetwork/issues/43
require(!(a == - 2**255 && b == -1) && !(b == - 2**255 && a == -1));
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing INT256_MIN by -1
// https://github.com/RequestNetwork/requestNetwork/issues/43
require(!(a == - 2**255 && b == -1) && (b > 0));
return a / b;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
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;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
////////////////////////////////
/////////// Tokens /////////////
////////////////////////////////
contract KitsuneInu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
bool private liquidating;
KitsuneInuDividendTracker public dividendTracker;
address public liquidityWallet;
uint256 public constant MAX_SELL_TRANSACTION_AMOUNT = 2500000000 * (10**18);
uint256 public constant ETH_REWARDS_FEE = 11;
uint256 public constant LIQUIDITY_FEE = 3;
uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE;
bool _swapEnabled = false;
bool openForPresale = false;
mapping (address => bool) private _isBlackListedBot;
address[] private _blackListedBots;
address private _dividendToken = 0x3301Ee63Fb29F863f2333Bd4466acb46CD8323E6;
address public marketingAddress = 0x61B3e99AfA0925EaF18bDeb8810b01b4ed1C895B;
bool _maxBuyEnabled = true;
// use by default 150,000 gas to process auto-claiming dividends
uint256 public gasForProcessing = 150000;
// liquidate tokens for ETH when the contract reaches 25000k tokens by default
uint256 public liquidateTokensAtAmount = 25000000 * (10**18);
// whether the token can already be traded
bool public tradingEnabled;
function activate() public onlyOwner {
require(!tradingEnabled, "KitsuneInu: Trading is already enabled");
_swapEnabled = true;
tradingEnabled = true;
}
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
// addresses that can make transfers before presale is over
mapping (address => bool) public canTransferBeforeTradingIsEnabled;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Liquified(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapAndSendToDev(
uint256 tokensSwapped,
uint256 ethReceived
);
event SentDividends(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
constructor() ERC20("Kitsune Inu", "KITSU") {
dividendTracker = new KitsuneInuDividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
// exclude from paying fees or having max transaction amount
excludeFromFees(liquidityWallet);
excludeFromFees(address(this));
// enable owner wallet to send tokens before presales are over.
canTransferBeforeTradingIsEnabled[owner()] = true;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 250000000000 * (10**18));
}
receive() external payable {
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "KitsuneInu: The Uniswap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "KitsuneInu: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function excludeFromFees(address account) public onlyOwner {
require(!_isExcludedFromFees[account], "KitsuneInu: Account is already excluded from fees");
_isExcludedFromFees[account] = true;
}
function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner {
dividendTracker.updateGasForTransfer(gasForTransfer);
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
require(newValue != gasForProcessing, "KitsuneInu: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getGasForTransfer() external view returns(uint256) {
return dividendTracker.gasForTransfer();
}
function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){
require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee");
_swapEnabled = _devFeeEnabled;
return(_swapEnabled);
}
function setOpenForPresale(bool open )external onlyOwner {
openForPresale = open;
}
function setMaxBuyEnabled(bool enabled ) external onlyOwner {
_maxBuyEnabled = enabled;
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account) public view returns(uint256) {
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function addBotToBlackList(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.');
require(!_isBlackListedBot[account], "Account is already blacklisted");
_isBlackListedBot[account] = true;
_blackListedBots.push(account);
}
function removeBotFromBlackList(address account) external onlyOwner() {
require(_isBlackListedBot[account], "Account is not blacklisted");
for (uint256 i = 0; i < _blackListedBots.length; i++) {
if (_blackListedBots[i] == account) {
_blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1];
_isBlackListedBot[account] = false;
_blackListedBots.pop();
break;
}
}
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isBlackListedBot[to], "You have no power here!");
require(!_isBlackListedBot[msg.sender], "You have no power here!");
require(!_isBlackListedBot[from], "You have no power here!");
//to prevent bots both buys and sells will have a max on launch after only sells will
if(from != owner() && to != owner() && _maxBuyEnabled)
require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount.");
bool tradingIsEnabled = tradingEnabled;
// only whitelisted addresses can make transfers before the public presale is over.
if (!tradingIsEnabled) {
//turn transfer on to allow for whitelist form/mutlisend presale
if(!openForPresale){
require(canTransferBeforeTradingIsEnabled[from], "KitsuneInu: This account cannot send tokens until trading is enabled");
}
}
if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) {
//require(!antiBot.scanAddress(from, uniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop");
// require(!antiBot.scanAddress(to, uniswair, tx.origin), "Beep Beep Boop, You're a piece of poop");
}
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (!liquidating &&
tradingIsEnabled &&
automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair
from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max
!_isExcludedFromFees[to] //no max for those excluded from fees
) {
require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= liquidateTokensAtAmount;
if (tradingIsEnabled &&
canSwap &&
_swapEnabled &&
!liquidating &&
!automatedMarketMakerPairs[from] &&
from != liquidityWallet &&
to != liquidityWallet
) {
liquidating = true;
uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES);
swapAndSendToDev(swapTokens);
uint256 sellTokens = balanceOf(address(this));
swapAndSendDividends(sellTokens);
liquidating = false;
}
bool takeFee = tradingIsEnabled && !liquidating;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = amount.mul(TOTAL_FEES).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {
}
if (!liquidating) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
} catch {
}
}
}
function swapAndSendToDev(uint256 tokens) private {
uint256 tokenBalance = tokens;
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(tokenBalance); // <- breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
address payable _devAndMarketingAddress = payable(marketingAddress);
_devAndMarketingAddress.transfer(newBalance);
emit SwapAndSendToDev(tokens, newBalance);
}
function swapTokensForDividendToken(uint256 tokenAmount, address recipient) private {
// generate the uniswap pair path of weth -> busd
address[] memory path = new address[](3);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
path[2] = _dividendToken;
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of dividend token
path,
recipient,
block.timestamp
);
}
function swapAndSendDividends(uint256 tokens) private {
swapTokensForDividendToken(tokens, address(this));
uint256 dividends = IERC20(_dividendToken).balanceOf(address(this));
bool success = IERC20(_dividendToken).transfer(address(dividendTracker), dividends);
if (success) {
dividendTracker.distributeDividends(dividends);
emit SentDividends(tokens, dividends);
}
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
}
contract KitsuneInuDividendTracker is DividendPayingToken, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public immutable minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() DividendPayingToken("KitsuneInu_Dividend_Tracker", "KitsuneInu_Dividend_Tracker") {
claimWait = 3600;
minimumTokenBalanceForDividends = 2500000 * (10**18); //must hold 2500000+ tokens
}
function _transfer(address, address, uint256) pure internal override {
require(false, "KitsuneInu_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() pure public override {
require(false, "KitsuneInu_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main KitsuneInu contract.");
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludeFromDividends(account);
}
function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner {
require(newGasForTransfer != gasForTransfer, "KitsuneInu_Dividend_Tracker: Cannot update gasForTransfer to same value");
emit GasForTransferUpdated(newGasForTransfer, gasForTransfer);
gasForTransfer = newGasForTransfer;
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 1800 && newClaimWait <= 86400, "KitsuneInu_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "KitsuneInu_Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
}
else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
} | Create a uniswap pair for this new token exclude from receiving dividends exclude from paying fees or having max transaction amount enable owner wallet to send tokens before presales are over. | constructor() ERC20("Kitsune Inu", "KITSU") {
dividendTracker = new KitsuneInuDividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
excludeFromFees(liquidityWallet);
excludeFromFees(address(this));
canTransferBeforeTradingIsEnabled[owner()] = true;
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(owner(), 250000000000 * (10**18));
| 2,449,097 |
./full_match/42/0xc56Dc76e2f87d3BDb0CF1f2b1A993EC42A1EB247/sources/Users/225153/Projects/ram/contracts/RamVault.sol | Adds additional RAM rewards | function addRAMRewardsOwner(uint256 _amount) public onlyOwner {
require(ram.transferFrom(msg.sender, address(this), _amount));
if (_amount > 0) {
pendingRewards = pendingRewards.add(_amount);
rewardsInThisEpoch = rewardsInThisEpoch.add(_amount);
}
}
| 9,578,694 |
pragma solidity ^0.4.15;
contract SlammerTime {
address public cryptogs;
function SlammerTime(address _cryptogs) public {
//deploy slammertime with cryptogs address coded in so
// only the cryptogs address can mess with it
cryptogs=_cryptogs;
}
function startSlammerTime(address _player1,uint256[5] _id1,address _player2,uint256[5] _id2) public returns (bool) {
//only the cryptogs contract should be able to hit it
require(msg.sender==cryptogs);
Cryptogs cryptogsContract = Cryptogs(cryptogs);
for(uint8 i=0;i<5;i++){
//make sure player1 owns _id1
require(cryptogsContract.tokenIndexToOwner(_id1[i])==_player1);
//transfer id1 in
cryptogsContract.transferFrom(_player1,address(this),_id1[i]);
//make this contract is the owner
require(cryptogsContract.tokenIndexToOwner(_id1[i])==address(this));
}
for(uint8 j=0;j<5;j++){
//make sure player1 owns _id1
require(cryptogsContract.tokenIndexToOwner(_id2[j])==_player2);
//transfer id1 in
cryptogsContract.transferFrom(_player2,address(this),_id2[j]);
//make this contract is the owner
require(cryptogsContract.tokenIndexToOwner(_id2[j])==address(this));
}
return true;
}
function transferBack(address _toWhom, uint256 _id) public returns (bool) {
//only the cryptogs contract should be able to hit it
require(msg.sender==cryptogs);
Cryptogs cryptogsContract = Cryptogs(cryptogs);
require(cryptogsContract.tokenIndexToOwner(_id)==address(this));
cryptogsContract.transfer(_toWhom,_id);
require(cryptogsContract.tokenIndexToOwner(_id)==_toWhom);
return true;
}
}
contract Cryptogs {
mapping (uint256 => address) public tokenIndexToOwner;
function transfer(address _to,uint256 _tokenId) external { }
function transferFrom(address _from,address _to,uint256 _tokenId) external { }
}
| deploy slammertime with cryptogs address coded in so only the cryptogs address can mess with it | function SlammerTime(address _cryptogs) public {
cryptogs=_cryptogs;
}
| 2,521,457 |
pragma solidity ^0.5.0;
/// @title A simulator for trees
/// @author Kenneth Hu
/// @notice You can use this contract to manage users.
/// @dev All function calls are currently implemented without side effects
contract Accounts {
struct Account {
bytes16 firstName;
bytes16 lastName;
string biography;
string email;
uint256[] employerJobs; // All jobs a user has created
uint256[] workerJobs; // All jobs a user has been assigned to
address addr;
}
mapping(address => Account) accounts; // Map contract address to account
address[] public allAccounts;
/// @notice Create an account
/// @param _addr the ethereum wallet address of account
/// @param _firstName the fast name of account
/// @param _lastName the last name of account
/// @param _biography a detailed description of an account.
/// @param _email account's email address
function setAccount(
address _addr,
bytes16 _firstName,
bytes16 _lastName,
string memory _biography,
string memory _email
) public {
Account storage account = accounts[_addr];
account.firstName = _firstName;
account.lastName = _lastName;
account.biography = _biography;
account.email = _email;
account.employerJobs;
account.workerJobs;
account.addr = _addr;
allAccounts.push(_addr);
}
/// @notice Get a list of all accounts
/// @return a list of all accounts
function getAccounts() public view returns (address[] memory) {
return allAccounts;
}
/// @notice Get a single account
/// @param _addr the ethereum wallet address of account
/// @return the detial of a single account
function getAccount(address _addr)
public
view
returns (
bytes16,
bytes16,
uint256[] memory,
uint256[] memory,
address,
string memory,
string memory
)
{
return (
accounts[_addr].firstName,
accounts[_addr].lastName,
accounts[_addr].employerJobs,
accounts[_addr].workerJobs,
accounts[_addr].addr,
accounts[_addr].biography,
accounts[_addr].email
);
}
/// @notice Add a job to an accounts employerJobs list
/// @param _addr the ethereum wallet address of account
/// @param id the ethereum wallet address of account
function addEmployerJob(address _addr, uint256 id) public {
Account storage acc = accounts[_addr];
if (acc.addr == msg.sender) {
acc.employerJobs.push(id);
}
}
/// @notice Add a job to an accounts workerJobs list
/// @param _addr the ethereum wallet address of account
/// @param id the ethereum wallet address of account
function addWorkerJob(address _addr, uint256 id) public {
Account storage acc = accounts[_addr];
acc.workerJobs.push(id);
}
/// @notice get all of an accounts employerJobs
/// @param _addr the ethereum wallet address of account
/// @return all of an accounts employerJobs
function getEmployerJobs(address _addr)
public
view
returns (uint256[] memory)
{
return accounts[_addr].employerJobs;
}
/// @notice get all of an accounts workerJobs
/// @param _addr the ethereum wallet address of account
/// @return all of an accounts workerJobs
function getWorkerJobs(address _addr)
public
view
returns (uint256[] memory)
{
return accounts[_addr].workerJobs;
}
/// @notice get the total number of accounts
/// @return the total number of accounts
function countAccounts() public view returns (uint256) {
return allAccounts.length;
}
}
| Create an account _addr the ethereum wallet address of account _firstName the fast name of account _lastName the last name of account _biography a detailed description of an account. _email account's email address | function setAccount(
address _addr,
bytes16 _firstName,
bytes16 _lastName,
string memory _biography,
string memory _email
) public {
Account storage account = accounts[_addr];
account.firstName = _firstName;
account.lastName = _lastName;
account.biography = _biography;
account.email = _email;
account.employerJobs;
account.workerJobs;
account.addr = _addr;
allAccounts.push(_addr);
}
| 12,879,891 |
/**
*Submitted for verification at Etherscan.io on 2021-04-02
*/
/**
*Submitted for verification at Etherscan.io on 2020-11-11
*/
/**
*Submitted for verification at Etherscan.io on 2020-02-28
*/
/**
*Submitted for verification at Etherscan.io on 2020-01-11
*/
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev 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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
using SafeMath for uint256;
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return one ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return one wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/**
* @return half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/**
* @dev multiplies two wad, rounding half up to the nearest wad
* @param a wad
* @param b wad
* @return the result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
return halfWAD.add(a.mul(b)).div(WAD);
}
/**
* @dev divides two wad, rounding half up to the nearest wad
* @param a wad
* @param b wad
* @return the result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(WAD)).div(b);
}
/**
* @dev multiplies two ray, rounding half up to the nearest ray
* @param a ray
* @param b ray
* @return the result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
return halfRAY.add(a.mul(b)).div(RAY);
}
/**
* @dev divides two ray, rounding half up to the nearest ray
* @param a ray
* @param b ray
* @return the result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(RAY)).div(b);
}
/**
* @dev casts ray down to wad
* @param a ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
return halfRatio.add(a).div(WAD_RAY_RATIO);
}
/**
* @dev convert wad up to ray
* @param a wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
return a.mul(WAD_RAY_RATIO);
}
/**
* @dev calculates base^exp. The code uses the ModExp precompile
* @return base^exp, in ray
*/
//solium-disable-next-line
function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rayMul(x, x);
if (n % 2 != 0) {
z = rayMul(z, x);
}
}
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied 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.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that 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;
}
}
/**
* @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);
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");
}
}
}
/**
* @title VersionedInitializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*
* @author Aave, inspired by the OpenZeppelin Initializable contract
*/
contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 private lastInitializedRevision = 0;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(initializing || isConstructor() || revision > lastInitializedRevision, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
lastInitializedRevision = revision;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure returns(uint256);
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
//solium-disable-next-line
assembly {
cs := extcodesize(address)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address 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 Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function() external payable {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
//solium-disable-next-line
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize)
}
default {
return(0, returndatasize)
}
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
"Cannot set a proxy implementation to a non-contract address"
);
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
//solium-disable-next-line
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
//solium-disable-next-line
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin, bytes memory _data) public payable UpgradeabilityProxy(_logic, _data) {
assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(_admin);
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
contract AddressStorage {
mapping(bytes32 => address) private addresses;
function getAddress(bytes32 _key) public view returns (address) {
return addresses[_key];
}
function _setAddress(bytes32 _key, address _value) internal {
addresses[_key] = _value;
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(_admin);
}
}
/**
@title ILendingPoolAddressesProvider interface
@notice provides the interface to fetch the LendingPoolCore address
*/
contract ILendingPoolAddressesProvider {
function getLendingPool() public view returns (address);
function setLendingPoolImpl(address _pool) public;
function getLendingPoolCore() public view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public;
function getLendingPoolConfigurator() public view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public;
function getLendingPoolDataProvider() public view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public;
function getLendingPoolParametersProvider() public view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public;
function getTokenDistributor() public view returns (address);
function setTokenDistributor(address _tokenDistributor) public;
function getFeeProvider() public view returns (address);
function setFeeProviderImpl(address _feeProvider) public;
function getLendingPoolLiquidationManager() public view returns (address);
function setLendingPoolLiquidationManager(address _manager) public;
function getLendingPoolManager() public view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public;
function getPriceOracle() public view returns (address);
function setPriceOracle(address _priceOracle) public;
function getLendingRateOracle() public view returns (address);
function setLendingRateOracle(address _lendingRateOracle) public;
}
/**
* @title LendingPoolAddressesProvider contract
* @notice Is the main registry of the protocol. All the different components of the protocol are accessible
* through the addresses provider.
* @author Aave
**/
contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider, AddressStorage {
//events
event LendingPoolUpdated(address indexed newAddress);
event LendingPoolCoreUpdated(address indexed newAddress);
event LendingPoolParametersProviderUpdated(address indexed newAddress);
event LendingPoolManagerUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolLiquidationManagerUpdated(address indexed newAddress);
event LendingPoolDataProviderUpdated(address indexed newAddress);
event EthereumAddressUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event FeeProviderUpdated(address indexed newAddress);
event TokenDistributorUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
bytes32 private constant LENDING_POOL = "LENDING_POOL";
bytes32 private constant LENDING_POOL_CORE = "LENDING_POOL_CORE";
bytes32 private constant LENDING_POOL_CONFIGURATOR = "LENDING_POOL_CONFIGURATOR";
bytes32 private constant LENDING_POOL_PARAMETERS_PROVIDER = "PARAMETERS_PROVIDER";
bytes32 private constant LENDING_POOL_MANAGER = "LENDING_POOL_MANAGER";
bytes32 private constant LENDING_POOL_LIQUIDATION_MANAGER = "LIQUIDATION_MANAGER";
bytes32 private constant LENDING_POOL_FLASHLOAN_PROVIDER = "FLASHLOAN_PROVIDER";
bytes32 private constant DATA_PROVIDER = "DATA_PROVIDER";
bytes32 private constant ETHEREUM_ADDRESS = "ETHEREUM_ADDRESS";
bytes32 private constant PRICE_ORACLE = "PRICE_ORACLE";
bytes32 private constant LENDING_RATE_ORACLE = "LENDING_RATE_ORACLE";
bytes32 private constant FEE_PROVIDER = "FEE_PROVIDER";
bytes32 private constant WALLET_BALANCE_PROVIDER = "WALLET_BALANCE_PROVIDER";
bytes32 private constant TOKEN_DISTRIBUTOR = "TOKEN_DISTRIBUTOR";
/**
* @dev returns the address of the LendingPool proxy
* @return the lending pool proxy address
**/
function getLendingPool() public view returns (address) {
return getAddress(LENDING_POOL);
}
/**
* @dev updates the implementation of the lending pool
* @param _pool the new lending pool implementation
**/
function setLendingPoolImpl(address _pool) public onlyOwner {
updateImplInternal(LENDING_POOL, _pool);
emit LendingPoolUpdated(_pool);
}
/**
* @dev returns the address of the LendingPoolCore proxy
* @return the lending pool core proxy address
*/
function getLendingPoolCore() public view returns (address payable) {
address payable core = address(uint160(getAddress(LENDING_POOL_CORE)));
return core;
}
/**
* @dev updates the implementation of the lending pool core
* @param _lendingPoolCore the new lending pool core implementation
**/
function setLendingPoolCoreImpl(address _lendingPoolCore) public onlyOwner {
updateImplInternal(LENDING_POOL_CORE, _lendingPoolCore);
emit LendingPoolCoreUpdated(_lendingPoolCore);
}
/**
* @dev returns the address of the LendingPoolConfigurator proxy
* @return the lending pool configurator proxy address
**/
function getLendingPoolConfigurator() public view returns (address) {
return getAddress(LENDING_POOL_CONFIGURATOR);
}
/**
* @dev updates the implementation of the lending pool configurator
* @param _configurator the new lending pool configurator implementation
**/
function setLendingPoolConfiguratorImpl(address _configurator) public onlyOwner {
updateImplInternal(LENDING_POOL_CONFIGURATOR, _configurator);
emit LendingPoolConfiguratorUpdated(_configurator);
}
/**
* @dev returns the address of the LendingPoolDataProvider proxy
* @return the lending pool data provider proxy address
*/
function getLendingPoolDataProvider() public view returns (address) {
return getAddress(DATA_PROVIDER);
}
/**
* @dev updates the implementation of the lending pool data provider
* @param _provider the new lending pool data provider implementation
**/
function setLendingPoolDataProviderImpl(address _provider) public onlyOwner {
updateImplInternal(DATA_PROVIDER, _provider);
emit LendingPoolDataProviderUpdated(_provider);
}
/**
* @dev returns the address of the LendingPoolParametersProvider proxy
* @return the address of the Lending pool parameters provider proxy
**/
function getLendingPoolParametersProvider() public view returns (address) {
return getAddress(LENDING_POOL_PARAMETERS_PROVIDER);
}
/**
* @dev updates the implementation of the lending pool parameters provider
* @param _parametersProvider the new lending pool parameters provider implementation
**/
function setLendingPoolParametersProviderImpl(address _parametersProvider) public onlyOwner {
updateImplInternal(LENDING_POOL_PARAMETERS_PROVIDER, _parametersProvider);
emit LendingPoolParametersProviderUpdated(_parametersProvider);
}
/**
* @dev returns the address of the FeeProvider proxy
* @return the address of the Fee provider proxy
**/
function getFeeProvider() public view returns (address) {
return getAddress(FEE_PROVIDER);
}
/**
* @dev updates the implementation of the FeeProvider proxy
* @param _feeProvider the new lending pool fee provider implementation
**/
function setFeeProviderImpl(address _feeProvider) public onlyOwner {
updateImplInternal(FEE_PROVIDER, _feeProvider);
emit FeeProviderUpdated(_feeProvider);
}
/**
* @dev returns the address of the LendingPoolLiquidationManager. Since the manager is used
* through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence
* the addresses are changed directly.
* @return the address of the Lending pool liquidation manager
**/
function getLendingPoolLiquidationManager() public view returns (address) {
return getAddress(LENDING_POOL_LIQUIDATION_MANAGER);
}
/**
* @dev updates the address of the Lending pool liquidation manager
* @param _manager the new lending pool liquidation manager address
**/
function setLendingPoolLiquidationManager(address _manager) public onlyOwner {
_setAddress(LENDING_POOL_LIQUIDATION_MANAGER, _manager);
emit LendingPoolLiquidationManagerUpdated(_manager);
}
/**
* @dev the functions below are storing specific addresses that are outside the context of the protocol
* hence the upgradable proxy pattern is not used
**/
function getLendingPoolManager() public view returns (address) {
return getAddress(LENDING_POOL_MANAGER);
}
function setLendingPoolManager(address _lendingPoolManager) public onlyOwner {
_setAddress(LENDING_POOL_MANAGER, _lendingPoolManager);
emit LendingPoolManagerUpdated(_lendingPoolManager);
}
function getPriceOracle() public view returns (address) {
return getAddress(PRICE_ORACLE);
}
function setPriceOracle(address _priceOracle) public onlyOwner {
_setAddress(PRICE_ORACLE, _priceOracle);
emit PriceOracleUpdated(_priceOracle);
}
function getLendingRateOracle() public view returns (address) {
return getAddress(LENDING_RATE_ORACLE);
}
function setLendingRateOracle(address _lendingRateOracle) public onlyOwner {
_setAddress(LENDING_RATE_ORACLE, _lendingRateOracle);
emit LendingRateOracleUpdated(_lendingRateOracle);
}
function getTokenDistributor() public view returns (address) {
return getAddress(TOKEN_DISTRIBUTOR);
}
function setTokenDistributor(address _tokenDistributor) public onlyOwner {
_setAddress(TOKEN_DISTRIBUTOR, _tokenDistributor);
emit TokenDistributorUpdated(_tokenDistributor);
}
/**
* @dev internal function to update the implementation of a specific component of the protocol
* @param _id the id of the contract to be updated
* @param _newAddress the address of the new implementation
**/
function updateImplInternal(bytes32 _id, address _newAddress) internal {
address payable proxyAddress = address(uint160(getAddress(_id)));
InitializableAdminUpgradeabilityProxy proxy = InitializableAdminUpgradeabilityProxy(proxyAddress);
bytes memory params = abi.encodeWithSignature("initialize(address)", address(this));
if (proxyAddress == address(0)) {
proxy = new InitializableAdminUpgradeabilityProxy();
proxy.initialize(_newAddress, address(this), params);
_setAddress(_id, address(proxy));
emit ProxyCreated(_id, address(proxy));
} else {
proxy.upgradeToAndCall(_newAddress, params);
}
}
}
contract UintStorage {
mapping(bytes32 => uint256) private uints;
function getUint(bytes32 _key) public view returns (uint256) {
return uints[_key];
}
function _setUint(bytes32 _key, uint256 _value) internal {
uints[_key] = _value;
}
}
/**
* @title LendingPoolParametersProvider
* @author Aave
* @notice stores the configuration parameters of the Lending Pool contract
**/
contract LendingPoolParametersProvider is VersionedInitializable {
uint256 private constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25;
uint256 private constant REBALANCE_DOWN_RATE_DELTA = (1e27)/5;
uint256 private constant FLASHLOAN_FEE_TOTAL = 35;
uint256 private constant FLASHLOAN_FEE_PROTOCOL = 3000;
uint256 constant private DATA_PROVIDER_REVISION = 0x1;
function getRevision() internal pure returns(uint256) {
return DATA_PROVIDER_REVISION;
}
/**
* @dev initializes the LendingPoolParametersProvider after it's added to the proxy
* @param _addressesProvider the address of the LendingPoolAddressesProvider
*/
function initialize(address _addressesProvider) public initializer {
}
/**
* @dev returns the maximum stable rate borrow size, in percentage of the available liquidity.
**/
function getMaxStableRateBorrowSizePercent() external pure returns (uint256) {
return MAX_STABLE_RATE_BORROW_SIZE_PERCENT;
}
/**
* @dev returns the delta between the current stable rate and the user stable rate at
* which the borrow position of the user will be rebalanced (scaled down)
**/
function getRebalanceDownRateDelta() external pure returns (uint256) {
return REBALANCE_DOWN_RATE_DELTA;
}
/**
* @dev returns the fee applied to a flashloan and the portion to redirect to the protocol, in basis points.
**/
function getFlashLoanFeesInBips() external pure returns (uint256, uint256) {
return (FLASHLOAN_FEE_TOTAL, FLASHLOAN_FEE_PROTOCOL);
}
}
/**
* @title CoreLibrary library
* @author Aave
* @notice Defines the data structures of the reserves and the user data
**/
library CoreLibrary {
using SafeMath for uint256;
using WadRayMath for uint256;
enum InterestRateMode {NONE, STABLE, VARIABLE}
uint256 internal constant SECONDS_PER_YEAR = 365 days;
struct UserReserveData {
//principal amount borrowed by the user.
uint256 principalBorrowBalance;
//cumulated variable borrow index for the user. Expressed in ray
uint256 lastVariableBorrowCumulativeIndex;
//origination fee cumulated by the user
uint256 originationFee;
// stable borrow rate at which the user has borrowed. Expressed in ray
uint256 stableBorrowRate;
uint40 lastUpdateTimestamp;
//defines if a specific deposit should or not be used as a collateral in borrows
bool useAsCollateral;
}
struct ReserveData {
/**
* @dev refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
**/
//the liquidity index. Expressed in ray
uint256 lastLiquidityCumulativeIndex;
//the current supply rate. Expressed in ray
uint256 currentLiquidityRate;
//the total borrows of the reserve at a stable rate. Expressed in the currency decimals
uint256 totalBorrowsStable;
//the total borrows of the reserve at a variable rate. Expressed in the currency decimals
uint256 totalBorrowsVariable;
//the current variable borrow rate. Expressed in ray
uint256 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint256 currentStableBorrowRate;
//the current average stable borrow rate (weighted average of all the different stable rate loans). Expressed in ray
uint256 currentAverageStableBorrowRate;
//variable borrow index. Expressed in ray
uint256 lastVariableBorrowCumulativeIndex;
//the ltv of the reserve. Expressed in percentage (0-100)
uint256 baseLTVasCollateral;
//the liquidation threshold of the reserve. Expressed in percentage (0-100)
uint256 liquidationThreshold;
//the liquidation bonus of the reserve. Expressed in percentage
uint256 liquidationBonus;
//the decimals of the reserve asset
uint256 decimals;
/**
* @dev address of the aToken representing the asset
**/
address aTokenAddress;
/**
* @dev address of the interest rate strategy contract
**/
address interestRateStrategyAddress;
uint40 lastUpdateTimestamp;
// borrowingEnabled = true means users can borrow from this reserve
bool borrowingEnabled;
// usageAsCollateralEnabled = true means users can use this reserve as collateral
bool usageAsCollateralEnabled;
// isStableBorrowRateEnabled = true means users can borrow at a stable rate
bool isStableBorrowRateEnabled;
// isActive = true means the reserve has been activated and properly configured
bool isActive;
// isFreezed = true means the reserve only allows repays and redeems, but not deposits, new borrowings or rate swap
bool isFreezed;
}
/**
* @dev returns the ongoing normalized income for the reserve.
* a value of 1e27 means there is no income. As time passes, the income is accrued.
* A value of 2*1e27 means that the income of the reserve is double the initial amount.
* @param _reserve the reserve object
* @return the normalized income. expressed in ray
**/
function getNormalizedIncome(CoreLibrary.ReserveData storage _reserve)
internal
view
returns (uint256)
{
uint256 cumulated = calculateLinearInterest(
_reserve
.currentLiquidityRate,
_reserve
.lastUpdateTimestamp
)
.rayMul(_reserve.lastLiquidityCumulativeIndex);
return cumulated;
}
/**
* @dev Updates the liquidity cumulative index Ci and variable borrow cumulative index Bvc. Refer to the whitepaper for
* a formal specification.
* @param _self the reserve object
**/
function updateCumulativeIndexes(ReserveData storage _self) internal {
uint256 totalBorrows = getTotalBorrows(_self);
if (totalBorrows > 0) {
//only cumulating if there is any income being produced
uint256 cumulatedLiquidityInterest = calculateLinearInterest(
_self.currentLiquidityRate,
_self.lastUpdateTimestamp
);
_self.lastLiquidityCumulativeIndex = cumulatedLiquidityInterest.rayMul(
_self.lastLiquidityCumulativeIndex
);
uint256 cumulatedVariableBorrowInterest = calculateCompoundedInterest(
_self.currentVariableBorrowRate,
_self.lastUpdateTimestamp
);
_self.lastVariableBorrowCumulativeIndex = cumulatedVariableBorrowInterest.rayMul(
_self.lastVariableBorrowCumulativeIndex
);
}
}
/**
* @dev accumulates a predefined amount of asset to the reserve as a fixed, one time income. Used for example to accumulate
* the flashloan fee to the reserve, and spread it through the depositors.
* @param _self the reserve object
* @param _totalLiquidity the total liquidity available in the reserve
* @param _amount the amount to accomulate
**/
function cumulateToLiquidityIndex(
ReserveData storage _self,
uint256 _totalLiquidity,
uint256 _amount
) internal {
uint256 amountToLiquidityRatio = _amount.wadToRay().rayDiv(_totalLiquidity.wadToRay());
uint256 cumulatedLiquidity = amountToLiquidityRatio.add(WadRayMath.ray());
_self.lastLiquidityCumulativeIndex = cumulatedLiquidity.rayMul(
_self.lastLiquidityCumulativeIndex
);
}
/**
* @dev initializes a reserve
* @param _self the reserve object
* @param _aTokenAddress the address of the overlying atoken contract
* @param _decimals the number of decimals of the underlying asset
* @param _interestRateStrategyAddress the address of the interest rate strategy contract
**/
function init(
ReserveData storage _self,
address _aTokenAddress,
uint256 _decimals,
address _interestRateStrategyAddress
) external {
require(_self.aTokenAddress == address(0), "Reserve has already been initialized");
if (_self.lastLiquidityCumulativeIndex == 0) {
//if the reserve has not been initialized yet
_self.lastLiquidityCumulativeIndex = WadRayMath.ray();
}
if (_self.lastVariableBorrowCumulativeIndex == 0) {
_self.lastVariableBorrowCumulativeIndex = WadRayMath.ray();
}
_self.aTokenAddress = _aTokenAddress;
_self.decimals = _decimals;
_self.interestRateStrategyAddress = _interestRateStrategyAddress;
_self.isActive = true;
_self.isFreezed = false;
}
/**
* @dev enables borrowing on a reserve
* @param _self the reserve object
* @param _stableBorrowRateEnabled true if the stable borrow rate must be enabled by default, false otherwise
**/
function enableBorrowing(ReserveData storage _self, bool _stableBorrowRateEnabled) external {
require(_self.borrowingEnabled == false, "Reserve is already enabled");
_self.borrowingEnabled = true;
_self.isStableBorrowRateEnabled = _stableBorrowRateEnabled;
}
/**
* @dev disables borrowing on a reserve
* @param _self the reserve object
**/
function disableBorrowing(ReserveData storage _self) external {
_self.borrowingEnabled = false;
}
/**
* @dev enables a reserve to be used as collateral
* @param _self the reserve object
* @param _baseLTVasCollateral the loan to value of the asset when used as collateral
* @param _liquidationThreshold the threshold at which loans using this asset as collateral will be considered undercollateralized
* @param _liquidationBonus the bonus liquidators receive to liquidate this asset
**/
function enableAsCollateral(
ReserveData storage _self,
uint256 _baseLTVasCollateral,
uint256 _liquidationThreshold,
uint256 _liquidationBonus
) external {
require(
_self.usageAsCollateralEnabled == false,
"Reserve is already enabled as collateral"
);
_self.usageAsCollateralEnabled = true;
_self.baseLTVasCollateral = _baseLTVasCollateral;
_self.liquidationThreshold = _liquidationThreshold;
_self.liquidationBonus = _liquidationBonus;
if (_self.lastLiquidityCumulativeIndex == 0)
_self.lastLiquidityCumulativeIndex = WadRayMath.ray();
}
/**
* @dev disables a reserve as collateral
* @param _self the reserve object
**/
function disableAsCollateral(ReserveData storage _self) external {
_self.usageAsCollateralEnabled = false;
}
/**
* @dev calculates the compounded borrow balance of a user
* @param _self the userReserve object
* @param _reserve the reserve object
* @return the user compounded borrow balance
**/
function getCompoundedBorrowBalance(
CoreLibrary.UserReserveData storage _self,
CoreLibrary.ReserveData storage _reserve
) internal view returns (uint256) {
if (_self.principalBorrowBalance == 0) return 0;
uint256 principalBorrowBalanceRay = _self.principalBorrowBalance.wadToRay();
uint256 compoundedBalance = 0;
uint256 cumulatedInterest = 0;
if (_self.stableBorrowRate > 0) {
cumulatedInterest = calculateCompoundedInterest(
_self.stableBorrowRate,
_self.lastUpdateTimestamp
);
} else {
//variable interest
cumulatedInterest = calculateCompoundedInterest(
_reserve
.currentVariableBorrowRate,
_reserve
.lastUpdateTimestamp
)
.rayMul(_reserve.lastVariableBorrowCumulativeIndex)
.rayDiv(_self.lastVariableBorrowCumulativeIndex);
}
compoundedBalance = principalBorrowBalanceRay.rayMul(cumulatedInterest).rayToWad();
if (compoundedBalance == _self.principalBorrowBalance) {
//solium-disable-next-line
if (_self.lastUpdateTimestamp != block.timestamp) {
//no interest cumulation because of the rounding - we add 1 wei
//as symbolic cumulated interest to avoid interest free loans.
return _self.principalBorrowBalance.add(1 wei);
}
}
return compoundedBalance;
}
/**
* @dev increases the total borrows at a stable rate on a specific reserve and updates the
* average stable rate consequently
* @param _reserve the reserve object
* @param _amount the amount to add to the total borrows stable
* @param _rate the rate at which the amount has been borrowed
**/
function increaseTotalBorrowsStableAndUpdateAverageRate(
ReserveData storage _reserve,
uint256 _amount,
uint256 _rate
) internal {
if(_amount == 0) {
return;
}
uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable;
//updating reserve borrows stable
_reserve.totalBorrowsStable = _reserve.totalBorrowsStable.add(_amount);
//update the average stable rate
//weighted average of all the borrows
uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate);
uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul(
_reserve.currentAverageStableBorrowRate
);
_reserve.currentAverageStableBorrowRate = weightedLastBorrow
.add(weightedPreviousTotalBorrows)
.rayDiv(_reserve.totalBorrowsStable.wadToRay());
}
/**
* @dev decreases the total borrows at a stable rate on a specific reserve and updates the
* average stable rate consequently
* @param _reserve the reserve object
* @param _amount the amount to substract to the total borrows stable
* @param _rate the rate at which the amount has been repaid
**/
function decreaseTotalBorrowsStableAndUpdateAverageRate(
ReserveData storage _reserve,
uint256 _amount,
uint256 _rate
) internal {
uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable;
if (previousTotalBorrowStable == 0 || _amount >= previousTotalBorrowStable) {
_reserve.totalBorrowsStable = 0;
_reserve.currentAverageStableBorrowRate = 0; // no income if there are no stable rate borrows
return;
}
//updating reserve borrows stable
_reserve.totalBorrowsStable = _reserve.totalBorrowsStable.sub(_amount);
//update the average stable rate
//weighted average of all the borrows
uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate);
uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul(
_reserve.currentAverageStableBorrowRate
);
if(
weightedPreviousTotalBorrows <= weightedLastBorrow
) {
_reserve.totalBorrowsStable = 0;
_reserve.currentAverageStableBorrowRate = 0; // no income if there are no stable rate borrows
return;
}
_reserve.currentAverageStableBorrowRate = weightedPreviousTotalBorrows
.sub(weightedLastBorrow)
.rayDiv(_reserve.totalBorrowsStable.wadToRay());
}
/**
* @dev increases the total borrows at a variable rate
* @param _reserve the reserve object
* @param _amount the amount to add to the total borrows variable
**/
function increaseTotalBorrowsVariable(ReserveData storage _reserve, uint256 _amount) internal {
_reserve.totalBorrowsVariable = _reserve.totalBorrowsVariable.add(_amount);
}
/**
* @dev decreases the total borrows at a variable rate
* @param _reserve the reserve object
* @param _amount the amount to substract to the total borrows variable
**/
function decreaseTotalBorrowsVariable(ReserveData storage _reserve, uint256 _amount) internal {
require(
_reserve.totalBorrowsVariable >= _amount,
"The amount that is being subtracted from the variable total borrows is incorrect"
);
_reserve.totalBorrowsVariable = _reserve.totalBorrowsVariable.sub(_amount);
}
/**
* @dev function to calculate the interest using a linear interest rate formula
* @param _rate the interest rate, in ray
* @param _lastUpdateTimestamp the timestamp of the last update of the interest
* @return the interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 _rate, uint40 _lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp));
uint256 timeDelta = timeDifference.wadToRay().rayDiv(SECONDS_PER_YEAR.wadToRay());
return _rate.rayMul(timeDelta).add(WadRayMath.ray());
}
/**
* @dev function to calculate the interest using a compounded interest rate formula
* @param _rate the interest rate, in ray
* @param _lastUpdateTimestamp the timestamp of the last update of the interest
* @return the interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(uint256 _rate, uint40 _lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp));
uint256 ratePerSecond = _rate.div(SECONDS_PER_YEAR);
return ratePerSecond.add(WadRayMath.ray()).rayPow(timeDifference);
}
/**
* @dev returns the total borrows on the reserve
* @param _reserve the reserve object
* @return the total borrows (stable + variable)
**/
function getTotalBorrows(CoreLibrary.ReserveData storage _reserve)
internal
view
returns (uint256)
{
return _reserve.totalBorrowsStable.add(_reserve.totalBorrowsVariable);
}
}
/**
* @title IPriceOracleGetter interface
* @notice Interface for the Aave price oracle.
**/
interface IPriceOracleGetter {
/**
* @dev returns the asset price in ETH
* @param _asset the address of the asset
* @return the ETH price of the asset
**/
function getAssetPrice(address _asset) external view returns (uint256);
}
/**
* @title IFeeProvider interface
* @notice Interface for the Aave fee provider.
**/
interface IFeeProvider {
function calculateLoanOriginationFee(address _user, uint256 _amount) external view returns (uint256);
function getLoanOriginationFeePercentage() external view returns (uint256);
}
/**
* @title LendingPoolDataProvider contract
* @author Aave
* @notice Implements functions to fetch data from the core, and aggregate them in order to allow computation
* on the compounded balances and the account balances in ETH
**/
contract LendingPoolDataProvider is VersionedInitializable {
using SafeMath for uint256;
using WadRayMath for uint256;
LendingPoolCore public core;
LendingPoolAddressesProvider public addressesProvider;
/**
* @dev specifies the health factor threshold at which the user position is liquidated.
* 1e18 by default, if the health factor drops below 1e18, the loan can be liquidated.
**/
uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;
uint256 public constant DATA_PROVIDER_REVISION = 0x1;
function getRevision() internal pure returns (uint256) {
return DATA_PROVIDER_REVISION;
}
function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {
addressesProvider = _addressesProvider;
core = LendingPoolCore(_addressesProvider.getLendingPoolCore());
}
/**
* @dev struct to hold calculateUserGlobalData() local computations
**/
struct UserGlobalDataLocalVars {
uint256 reserveUnitPrice;
uint256 tokenUnit;
uint256 compoundedLiquidityBalance;
uint256 compoundedBorrowBalance;
uint256 reserveDecimals;
uint256 baseLtv;
uint256 liquidationThreshold;
uint256 originationFee;
bool usageAsCollateralEnabled;
bool userUsesReserveAsCollateral;
address currentReserve;
}
/**
* @dev calculates the user data across the reserves.
* this includes the total liquidity/collateral/borrow balances in ETH,
* the average Loan To Value, the average Liquidation Ratio, and the Health factor.
* @param _user the address of the user
* @return the total liquidity, total collateral, total borrow balances of the user in ETH.
* also the average Ltv, liquidation threshold, and the health factor
**/
function calculateUserGlobalData(address _user)
public
view
returns (
uint256 totalLiquidityBalanceETH,
uint256 totalCollateralBalanceETH,
uint256 totalBorrowBalanceETH,
uint256 totalFeesETH,
uint256 currentLtv,
uint256 currentLiquidationThreshold,
uint256 healthFactor,
bool healthFactorBelowThreshold
)
{
IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
UserGlobalDataLocalVars memory vars;
address[] memory reserves = core.getReserves();
for (uint256 i = 0; i < reserves.length; i++) {
vars.currentReserve = reserves[i];
(
vars.compoundedLiquidityBalance,
vars.compoundedBorrowBalance,
vars.originationFee,
vars.userUsesReserveAsCollateral
) = core.getUserBasicReserveData(vars.currentReserve, _user);
if (vars.compoundedLiquidityBalance == 0 && vars.compoundedBorrowBalance == 0) {
continue;
}
//fetch reserve data
(
vars.reserveDecimals,
vars.baseLtv,
vars.liquidationThreshold,
vars.usageAsCollateralEnabled
) = core.getReserveConfiguration(vars.currentReserve);
vars.tokenUnit = 10 ** vars.reserveDecimals;
vars.reserveUnitPrice = oracle.getAssetPrice(vars.currentReserve);
//liquidity and collateral balance
if (vars.compoundedLiquidityBalance > 0) {
uint256 liquidityBalanceETH = vars
.reserveUnitPrice
.mul(vars.compoundedLiquidityBalance)
.div(vars.tokenUnit);
totalLiquidityBalanceETH = totalLiquidityBalanceETH.add(liquidityBalanceETH);
if (vars.usageAsCollateralEnabled && vars.userUsesReserveAsCollateral) {
totalCollateralBalanceETH = totalCollateralBalanceETH.add(liquidityBalanceETH);
currentLtv = currentLtv.add(liquidityBalanceETH.mul(vars.baseLtv));
currentLiquidationThreshold = currentLiquidationThreshold.add(
liquidityBalanceETH.mul(vars.liquidationThreshold)
);
}
}
if (vars.compoundedBorrowBalance > 0) {
totalBorrowBalanceETH = totalBorrowBalanceETH.add(
vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit)
);
totalFeesETH = totalFeesETH.add(
vars.originationFee.mul(vars.reserveUnitPrice).div(vars.tokenUnit)
);
}
}
currentLtv = totalCollateralBalanceETH > 0 ? currentLtv.div(totalCollateralBalanceETH) : 0;
currentLiquidationThreshold = totalCollateralBalanceETH > 0
? currentLiquidationThreshold.div(totalCollateralBalanceETH)
: 0;
healthFactor = calculateHealthFactorFromBalancesInternal(
totalCollateralBalanceETH,
totalBorrowBalanceETH,
totalFeesETH,
currentLiquidationThreshold
);
healthFactorBelowThreshold = healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
struct balanceDecreaseAllowedLocalVars {
uint256 decimals;
uint256 collateralBalanceETH;
uint256 borrowBalanceETH;
uint256 totalFeesETH;
uint256 currentLiquidationThreshold;
uint256 reserveLiquidationThreshold;
uint256 amountToDecreaseETH;
uint256 collateralBalancefterDecrease;
uint256 liquidationThresholdAfterDecrease;
uint256 healthFactorAfterDecrease;
bool reserveUsageAsCollateralEnabled;
}
/**
* @dev check if a specific balance decrease is allowed (i.e. doesn't bring the user borrow position health factor under 1e18)
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to decrease
* @return true if the decrease of the balance is allowed
**/
function balanceDecreaseAllowed(address _reserve, address _user, uint256 _amount)
external
view
returns (bool)
{
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
balanceDecreaseAllowedLocalVars memory vars;
(
vars.decimals,
,
vars.reserveLiquidationThreshold,
vars.reserveUsageAsCollateralEnabled
) = core.getReserveConfiguration(_reserve);
if (
!vars.reserveUsageAsCollateralEnabled ||
!core.isUserUseReserveAsCollateralEnabled(_reserve, _user)
) {
return true; //if reserve is not used as collateral, no reasons to block the transfer
}
(
,
vars.collateralBalanceETH,
vars.borrowBalanceETH,
vars.totalFeesETH,
,
vars.currentLiquidationThreshold,
,
) = calculateUserGlobalData(_user);
if (vars.borrowBalanceETH == 0) {
return true; //no borrows - no reasons to block the transfer
}
IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());
vars.amountToDecreaseETH = oracle.getAssetPrice(_reserve).mul(_amount).div(
10 ** vars.decimals
);
vars.collateralBalancefterDecrease = vars.collateralBalanceETH.sub(
vars.amountToDecreaseETH
);
//if there is a borrow, there can't be 0 collateral
if (vars.collateralBalancefterDecrease == 0) {
return false;
}
vars.liquidationThresholdAfterDecrease = vars
.collateralBalanceETH
.mul(vars.currentLiquidationThreshold)
.sub(vars.amountToDecreaseETH.mul(vars.reserveLiquidationThreshold))
.div(vars.collateralBalancefterDecrease);
uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalancesInternal(
vars.collateralBalancefterDecrease,
vars.borrowBalanceETH,
vars.totalFeesETH,
vars.liquidationThresholdAfterDecrease
);
return healthFactorAfterDecrease > HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
/**
* @notice calculates the amount of collateral needed in ETH to cover a new borrow.
* @param _reserve the reserve from which the user wants to borrow
* @param _amount the amount the user wants to borrow
* @param _fee the fee for the amount that the user needs to cover
* @param _userCurrentBorrowBalanceTH the current borrow balance of the user (before the borrow)
* @param _userCurrentLtv the average ltv of the user given his current collateral
* @return the total amount of collateral in ETH to cover the current borrow balance + the new amount + fee
**/
function calculateCollateralNeededInETH(
address _reserve,
uint256 _amount,
uint256 _fee,
uint256 _userCurrentBorrowBalanceTH,
uint256 _userCurrentFeesETH,
uint256 _userCurrentLtv
) external view returns (uint256) {
uint256 reserveDecimals = core.getReserveDecimals(_reserve);
IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());
uint256 requestedBorrowAmountETH = oracle
.getAssetPrice(_reserve)
.mul(_amount.add(_fee))
.div(10 ** reserveDecimals); //price is in ether
//add the current already borrowed amount to the amount requested to calculate the total collateral needed.
uint256 collateralNeededInETH = _userCurrentBorrowBalanceTH
.add(_userCurrentFeesETH)
.add(requestedBorrowAmountETH)
.mul(100)
.div(_userCurrentLtv); //LTV is calculated in percentage
return collateralNeededInETH;
}
/**
* @dev calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the
* average Loan To Value.
* @param collateralBalanceETH the total collateral balance
* @param borrowBalanceETH the total borrow balance
* @param totalFeesETH the total fees
* @param ltv the average loan to value
* @return the amount available to borrow in ETH for the user
**/
function calculateAvailableBorrowsETHInternal(
uint256 collateralBalanceETH,
uint256 borrowBalanceETH,
uint256 totalFeesETH,
uint256 ltv
) internal view returns (uint256) {
uint256 availableBorrowsETH = collateralBalanceETH.mul(ltv).div(100); //ltv is in percentage
if (availableBorrowsETH < borrowBalanceETH) {
return 0;
}
availableBorrowsETH = availableBorrowsETH.sub(borrowBalanceETH.add(totalFeesETH));
//calculate fee
uint256 borrowFee = IFeeProvider(addressesProvider.getFeeProvider())
.calculateLoanOriginationFee(msg.sender, availableBorrowsETH);
return availableBorrowsETH.sub(borrowFee);
}
/**
* @dev calculates the health factor from the corresponding balances
* @param collateralBalanceETH the total collateral balance in ETH
* @param borrowBalanceETH the total borrow balance in ETH
* @param totalFeesETH the total fees in ETH
* @param liquidationThreshold the avg liquidation threshold
**/
function calculateHealthFactorFromBalancesInternal(
uint256 collateralBalanceETH,
uint256 borrowBalanceETH,
uint256 totalFeesETH,
uint256 liquidationThreshold
) internal pure returns (uint256) {
if (borrowBalanceETH == 0) return uint256(-1);
return
(collateralBalanceETH.mul(liquidationThreshold).div(100)).wadDiv(
borrowBalanceETH.add(totalFeesETH)
);
}
/**
* @dev returns the health factor liquidation threshold
**/
function getHealthFactorLiquidationThreshold() public pure returns (uint256) {
return HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
/**
* @dev accessory functions to fetch data from the lendingPoolCore
**/
function getReserveConfigurationData(address _reserve)
external
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address rateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
)
{
(, ltv, liquidationThreshold, usageAsCollateralEnabled) = core.getReserveConfiguration(
_reserve
);
stableBorrowRateEnabled = core.getReserveIsStableBorrowRateEnabled(_reserve);
borrowingEnabled = core.isReserveBorrowingEnabled(_reserve);
isActive = core.getReserveIsActive(_reserve);
liquidationBonus = core.getReserveLiquidationBonus(_reserve);
rateStrategyAddress = core.getReserveInterestRateStrategyAddress(_reserve);
}
function getReserveData(address _reserve)
external
view
returns (
uint256 totalLiquidity,
uint256 availableLiquidity,
uint256 totalBorrowsStable,
uint256 totalBorrowsVariable,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 utilizationRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
address aTokenAddress,
uint40 lastUpdateTimestamp
)
{
totalLiquidity = core.getReserveTotalLiquidity(_reserve);
availableLiquidity = core.getReserveAvailableLiquidity(_reserve);
totalBorrowsStable = core.getReserveTotalBorrowsStable(_reserve);
totalBorrowsVariable = core.getReserveTotalBorrowsVariable(_reserve);
liquidityRate = core.getReserveCurrentLiquidityRate(_reserve);
variableBorrowRate = core.getReserveCurrentVariableBorrowRate(_reserve);
stableBorrowRate = core.getReserveCurrentStableBorrowRate(_reserve);
averageStableBorrowRate = core.getReserveCurrentAverageStableBorrowRate(_reserve);
utilizationRate = core.getReserveUtilizationRate(_reserve);
liquidityIndex = core.getReserveLiquidityCumulativeIndex(_reserve);
variableBorrowIndex = core.getReserveVariableBorrowsCumulativeIndex(_reserve);
aTokenAddress = core.getReserveATokenAddress(_reserve);
lastUpdateTimestamp = core.getReserveLastUpdate(_reserve);
}
function getUserAccountData(address _user)
external
view
returns (
uint256 totalLiquidityETH,
uint256 totalCollateralETH,
uint256 totalBorrowsETH,
uint256 totalFeesETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
)
{
(
totalLiquidityETH,
totalCollateralETH,
totalBorrowsETH,
totalFeesETH,
ltv,
currentLiquidationThreshold,
healthFactor,
) = calculateUserGlobalData(_user);
availableBorrowsETH = calculateAvailableBorrowsETHInternal(
totalCollateralETH,
totalBorrowsETH,
totalFeesETH,
ltv
);
}
function getUserReserveData(address _reserve, address _user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentBorrowBalance,
uint256 principalBorrowBalance,
uint256 borrowRateMode,
uint256 borrowRate,
uint256 liquidityRate,
uint256 originationFee,
uint256 variableBorrowIndex,
uint256 lastUpdateTimestamp,
bool usageAsCollateralEnabled
)
{
currentATokenBalance = AToken(core.getReserveATokenAddress(_reserve)).balanceOf(_user);
CoreLibrary.InterestRateMode mode = core.getUserCurrentBorrowRateMode(_reserve, _user);
(principalBorrowBalance, currentBorrowBalance, ) = core.getUserBorrowBalances(
_reserve,
_user
);
//default is 0, if mode == CoreLibrary.InterestRateMode.NONE
if (mode == CoreLibrary.InterestRateMode.STABLE) {
borrowRate = core.getUserCurrentStableBorrowRate(_reserve, _user);
} else if (mode == CoreLibrary.InterestRateMode.VARIABLE) {
borrowRate = core.getReserveCurrentVariableBorrowRate(_reserve);
}
borrowRateMode = uint256(mode);
liquidityRate = core.getReserveCurrentLiquidityRate(_reserve);
originationFee = core.getUserOriginationFee(_reserve, _user);
variableBorrowIndex = core.getUserVariableBorrowCumulativeIndex(_reserve, _user);
lastUpdateTimestamp = core.getUserLastUpdate(_reserve, _user);
usageAsCollateralEnabled = core.isUserUseReserveAsCollateralEnabled(_reserve, _user);
}
}
/**
* @title Aave ERC20 AToken
*
* @dev Implementation of the interest bearing token for the DLP protocol.
* @author Aave
*/
contract AToken is ERC20, ERC20Detailed {
using WadRayMath for uint256;
uint256 public constant UINT_MAX_VALUE = uint256(-1);
/**
* @dev emitted after the redeem action
* @param _from the address performing the redeem
* @param _value the amount to be redeemed
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event Redeem(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted after the mint action
* @param _from the address performing the mint
* @param _value the amount to be minted
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event MintOnDeposit(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted during the liquidation action, when the liquidator reclaims the underlying
* asset
* @param _from the address from which the tokens are being burned
* @param _value the amount to be burned
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event BurnOnLiquidation(
address indexed _from,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted during the transfer action
* @param _from the address from which the tokens are being transferred
* @param _to the adress of the destination
* @param _value the amount to be minted
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _toBalanceIncrease the cumulated balance since the last update of the destination
* @param _fromIndex the last index of the user
* @param _toIndex the last index of the liquidator
**/
event BalanceTransfer(
address indexed _from,
address indexed _to,
uint256 _value,
uint256 _fromBalanceIncrease,
uint256 _toBalanceIncrease,
uint256 _fromIndex,
uint256 _toIndex
);
/**
* @dev emitted when the accumulation of the interest
* by an user is redirected to another user
* @param _from the address from which the interest is being redirected
* @param _to the adress of the destination
* @param _fromBalanceIncrease the cumulated balance since the last update of the user
* @param _fromIndex the last index of the user
**/
event InterestStreamRedirected(
address indexed _from,
address indexed _to,
uint256 _redirectedBalance,
uint256 _fromBalanceIncrease,
uint256 _fromIndex
);
/**
* @dev emitted when the redirected balance of an user is being updated
* @param _targetAddress the address of which the balance is being updated
* @param _targetBalanceIncrease the cumulated balance since the last update of the target
* @param _targetIndex the last index of the user
* @param _redirectedBalanceAdded the redirected balance being added
* @param _redirectedBalanceRemoved the redirected balance being removed
**/
event RedirectedBalanceUpdated(
address indexed _targetAddress,
uint256 _targetBalanceIncrease,
uint256 _targetIndex,
uint256 _redirectedBalanceAdded,
uint256 _redirectedBalanceRemoved
);
event InterestRedirectionAllowanceChanged(
address indexed _from,
address indexed _to
);
address public underlyingAssetAddress;
mapping (address => uint256) private userIndexes;
mapping (address => address) private interestRedirectionAddresses;
mapping (address => uint256) private redirectedBalances;
mapping (address => address) private interestRedirectionAllowances;
LendingPoolAddressesProvider private addressesProvider;
LendingPoolCore private core;
LendingPool private pool;
LendingPoolDataProvider private dataProvider;
modifier onlyLendingPool {
require(
msg.sender == address(pool),
"The caller of this function must be a lending pool"
);
_;
}
modifier whenTransferAllowed(address _from, uint256 _amount) {
require(isTransferAllowed(_from, _amount), "Transfer cannot be allowed.");
_;
}
constructor(
LendingPoolAddressesProvider _addressesProvider,
address _underlyingAsset,
uint8 _underlyingAssetDecimals,
string memory _name,
string memory _symbol
) public ERC20Detailed(_name, _symbol, _underlyingAssetDecimals) {
addressesProvider = _addressesProvider;
core = LendingPoolCore(addressesProvider.getLendingPoolCore());
pool = LendingPool(addressesProvider.getLendingPool());
dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider());
underlyingAssetAddress = _underlyingAsset;
}
/**
* @notice ERC20 implementation internal function backing transfer() and transferFrom()
* @dev validates the transfer before allowing it. NOTE: This is not standard ERC20 behavior
**/
function _transfer(address _from, address _to, uint256 _amount) internal whenTransferAllowed(_from, _amount) {
executeTransferInternal(_from, _to, _amount);
}
/**
* @dev redirects the interest generated to a target address.
* when the interest is redirected, the user balance is added to
* the recepient redirected balance.
* @param _to the address to which the interest will be redirected
**/
function redirectInterestStream(address _to) external {
redirectInterestStreamInternal(msg.sender, _to);
}
/**
* @dev redirects the interest generated by _from to a target address.
* when the interest is redirected, the user balance is added to
* the recepient redirected balance. The caller needs to have allowance on
* the interest redirection to be able to execute the function.
* @param _from the address of the user whom interest is being redirected
* @param _to the address to which the interest will be redirected
**/
function redirectInterestStreamOf(address _from, address _to) external {
require(
msg.sender == interestRedirectionAllowances[_from],
"Caller is not allowed to redirect the interest of the user"
);
redirectInterestStreamInternal(_from,_to);
}
/**
* @dev gives allowance to an address to execute the interest redirection
* on behalf of the caller.
* @param _to the address to which the interest will be redirected. Pass address(0) to reset
* the allowance.
**/
function allowInterestRedirectionTo(address _to) external {
require(_to != msg.sender, "User cannot give allowance to himself");
interestRedirectionAllowances[msg.sender] = _to;
emit InterestRedirectionAllowanceChanged(
msg.sender,
_to
);
}
/**
* @dev redeems aToken for the underlying asset
* @param _amount the amount being redeemed
**/
function redeem(uint256 _amount) external {
require(_amount > 0, "Amount to redeem needs to be > 0");
//cumulates the balance of the user
(,
uint256 currentBalance,
uint256 balanceIncrease,
uint256 index) = cumulateBalanceInternal(msg.sender);
uint256 amountToRedeem = _amount;
//if amount is equal to uint(-1), the user wants to redeem everything
if(_amount == UINT_MAX_VALUE){
amountToRedeem = currentBalance;
}
require(amountToRedeem <= currentBalance, "User cannot redeem more than the available balance");
//check that the user is allowed to redeem the amount
require(isTransferAllowed(msg.sender, amountToRedeem), "Transfer cannot be allowed.");
//if the user is redirecting his interest towards someone else,
//we update the redirected balance of the redirection address by adding the accrued interest,
//and removing the amount to redeem
updateRedirectedBalanceOfRedirectionAddressInternal(msg.sender, balanceIncrease, amountToRedeem);
// burns tokens equivalent to the amount requested
_burn(msg.sender, amountToRedeem);
bool userIndexReset = false;
//reset the user data if the remaining balance is 0
if(currentBalance.sub(amountToRedeem) == 0){
userIndexReset = resetDataOnZeroBalanceInternal(msg.sender);
}
// executes redeem of the underlying asset
pool.redeemUnderlying(
underlyingAssetAddress,
msg.sender,
amountToRedeem,
currentBalance.sub(amountToRedeem)
);
emit Redeem(msg.sender, amountToRedeem, balanceIncrease, userIndexReset ? 0 : index);
}
/**
* @dev mints token in the event of users depositing the underlying asset into the lending pool
* only lending pools can call this function
* @param _account the address receiving the minted tokens
* @param _amount the amount of tokens to mint
*/
function mintOnDeposit(address _account, uint256 _amount) external onlyLendingPool {
//cumulates the balance of the user
(,
,
uint256 balanceIncrease,
uint256 index) = cumulateBalanceInternal(_account);
//if the user is redirecting his interest towards someone else,
//we update the redirected balance of the redirection address by adding the accrued interest
//and the amount deposited
updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease.add(_amount), 0);
//mint an equivalent amount of tokens to cover the new deposit
_mint(_account, _amount);
emit MintOnDeposit(_account, _amount, balanceIncrease, index);
}
/**
* @dev burns token in the event of a borrow being liquidated, in case the liquidators reclaims the underlying asset
* Transfer of the liquidated asset is executed by the lending pool contract.
* only lending pools can call this function
* @param _account the address from which burn the aTokens
* @param _value the amount to burn
**/
function burnOnLiquidation(address _account, uint256 _value) external onlyLendingPool {
//cumulates the balance of the user being liquidated
(,uint256 accountBalance,uint256 balanceIncrease,uint256 index) = cumulateBalanceInternal(_account);
//adds the accrued interest and substracts the burned amount to
//the redirected balance
updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease, _value);
//burns the requested amount of tokens
_burn(_account, _value);
bool userIndexReset = false;
//reset the user data if the remaining balance is 0
if(accountBalance.sub(_value) == 0){
userIndexReset = resetDataOnZeroBalanceInternal(_account);
}
emit BurnOnLiquidation(_account, _value, balanceIncrease, userIndexReset ? 0 : index);
}
/**
* @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* only lending pools can call this function
* @param _from the address from which transfer the aTokens
* @param _to the destination address
* @param _value the amount to transfer
**/
function transferOnLiquidation(address _from, address _to, uint256 _value) external onlyLendingPool {
//being a normal transfer, the Transfer() and BalanceTransfer() are emitted
//so no need to emit a specific event here
executeTransferInternal(_from, _to, _value);
}
/**
* @dev calculates the balance of the user, which is the
* principal balance + interest generated by the principal balance + interest generated by the redirected balance
* @param _user the user for which the balance is being calculated
* @return the total balance of the user
**/
function balanceOf(address _user) public view returns(uint256) {
//current principal balance of the user
uint256 currentPrincipalBalance = super.balanceOf(_user);
//balance redirected by other users to _user for interest rate accrual
uint256 redirectedBalance = redirectedBalances[_user];
if(currentPrincipalBalance == 0 && redirectedBalance == 0){
return 0;
}
//if the _user is not redirecting the interest to anybody, accrues
//the interest for himself
if(interestRedirectionAddresses[_user] == address(0)){
//accruing for himself means that both the principal balance and
//the redirected balance partecipate in the interest
return calculateCumulatedBalanceInternal(
_user,
currentPrincipalBalance.add(redirectedBalance)
)
.sub(redirectedBalance);
}
else {
//if the user redirected the interest, then only the redirected
//balance generates interest. In that case, the interest generated
//by the redirected balance is added to the current principal balance.
return currentPrincipalBalance.add(
calculateCumulatedBalanceInternal(
_user,
redirectedBalance
)
.sub(redirectedBalance)
);
}
}
/**
* @dev returns the principal balance of the user. The principal balance is the last
* updated stored balance, which does not consider the perpetually accruing interest.
* @param _user the address of the user
* @return the principal balance of the user
**/
function principalBalanceOf(address _user) external view returns(uint256) {
return super.balanceOf(_user);
}
/**
* @dev calculates the total supply of the specific aToken
* since the balance of every single user increases over time, the total supply
* does that too.
* @return the current total supply
**/
function totalSupply() public view returns(uint256) {
uint256 currentSupplyPrincipal = super.totalSupply();
if(currentSupplyPrincipal == 0){
return 0;
}
return currentSupplyPrincipal
.wadToRay()
.rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress))
.rayToWad();
}
/**
* @dev Used to validate transfers before actually executing them.
* @param _user address of the user to check
* @param _amount the amount to check
* @return true if the _user can transfer _amount, false otherwise
**/
function isTransferAllowed(address _user, uint256 _amount) public view returns (bool) {
return dataProvider.balanceDecreaseAllowed(underlyingAssetAddress, _user, _amount);
}
/**
* @dev returns the last index of the user, used to calculate the balance of the user
* @param _user address of the user
* @return the last user index
**/
function getUserIndex(address _user) external view returns(uint256) {
return userIndexes[_user];
}
/**
* @dev returns the address to which the interest is redirected
* @param _user address of the user
* @return 0 if there is no redirection, an address otherwise
**/
function getInterestRedirectionAddress(address _user) external view returns(address) {
return interestRedirectionAddresses[_user];
}
/**
* @dev returns the redirected balance of the user. The redirected balance is the balance
* redirected by other accounts to the user, that is accrueing interest for him.
* @param _user address of the user
* @return the total redirected balance
**/
function getRedirectedBalance(address _user) external view returns(uint256) {
return redirectedBalances[_user];
}
/**
* @dev accumulates the accrued interest of the user to the principal balance
* @param _user the address of the user for which the interest is being accumulated
* @return the previous principal balance, the new principal balance, the balance increase
* and the new user index
**/
function cumulateBalanceInternal(address _user)
internal
returns(uint256, uint256, uint256, uint256) {
uint256 previousPrincipalBalance = super.balanceOf(_user);
//calculate the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance);
//mints an amount of tokens equivalent to the amount accumulated
_mint(_user, balanceIncrease);
//updates the user index
uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease,
index
);
}
/**
* @dev updates the redirected balance of the user. If the user is not redirecting his
* interest, nothing is executed.
* @param _user the address of the user for which the interest is being accumulated
* @param _balanceToAdd the amount to add to the redirected balance
* @param _balanceToRemove the amount to remove from the redirected balance
**/
function updateRedirectedBalanceOfRedirectionAddressInternal(
address _user,
uint256 _balanceToAdd,
uint256 _balanceToRemove
) internal {
address redirectionAddress = interestRedirectionAddresses[_user];
//if there isn't any redirection, nothing to be done
if(redirectionAddress == address(0)){
return;
}
//compound balances of the redirected address
(,,uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(redirectionAddress);
//updating the redirected balance
redirectedBalances[redirectionAddress] = redirectedBalances[redirectionAddress]
.add(_balanceToAdd)
.sub(_balanceToRemove);
//if the interest of redirectionAddress is also being redirected, we need to update
//the redirected balance of the redirection target by adding the balance increase
address targetOfRedirectionAddress = interestRedirectionAddresses[redirectionAddress];
if(targetOfRedirectionAddress != address(0)){
redirectedBalances[targetOfRedirectionAddress] = redirectedBalances[targetOfRedirectionAddress].add(balanceIncrease);
}
emit RedirectedBalanceUpdated(
redirectionAddress,
balanceIncrease,
index,
_balanceToAdd,
_balanceToRemove
);
}
/**
* @dev calculate the interest accrued by _user on a specific balance
* @param _user the address of the user for which the interest is being accumulated
* @param _balance the balance on which the interest is calculated
* @return the interest rate accrued
**/
function calculateCumulatedBalanceInternal(
address _user,
uint256 _balance
) internal view returns (uint256) {
return _balance
.wadToRay()
.rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress))
.rayDiv(userIndexes[_user])
.rayToWad();
}
/**
* @dev executes the transfer of aTokens, invoked by both _transfer() and
* transferOnLiquidation()
* @param _from the address from which transfer the aTokens
* @param _to the destination address
* @param _value the amount to transfer
**/
function executeTransferInternal(
address _from,
address _to,
uint256 _value
) internal {
require(_value > 0, "Transferred amount needs to be greater than zero");
//cumulate the balance of the sender
(,
uint256 fromBalance,
uint256 fromBalanceIncrease,
uint256 fromIndex
) = cumulateBalanceInternal(_from);
//cumulate the balance of the receiver
(,
,
uint256 toBalanceIncrease,
uint256 toIndex
) = cumulateBalanceInternal(_to);
//if the sender is redirecting his interest towards someone else,
//adds to the redirected balance the accrued interest and removes the amount
//being transferred
updateRedirectedBalanceOfRedirectionAddressInternal(_from, fromBalanceIncrease, _value);
//if the receiver is redirecting his interest towards someone else,
//adds to the redirected balance the accrued interest and the amount
//being transferred
updateRedirectedBalanceOfRedirectionAddressInternal(_to, toBalanceIncrease.add(_value), 0);
//performs the transfer
super._transfer(_from, _to, _value);
bool fromIndexReset = false;
//reset the user data if the remaining balance is 0
if(fromBalance.sub(_value) == 0){
fromIndexReset = resetDataOnZeroBalanceInternal(_from);
}
emit BalanceTransfer(
_from,
_to,
_value,
fromBalanceIncrease,
toBalanceIncrease,
fromIndexReset ? 0 : fromIndex,
toIndex
);
}
/**
* @dev executes the redirection of the interest from one address to another.
* immediately after redirection, the destination address will start to accrue interest.
* @param _from the address from which transfer the aTokens
* @param _to the destination address
**/
function redirectInterestStreamInternal(
address _from,
address _to
) internal {
address currentRedirectionAddress = interestRedirectionAddresses[_from];
require(_to != currentRedirectionAddress, "Interest is already redirected to the user");
//accumulates the accrued interest to the principal
(uint256 previousPrincipalBalance,
uint256 fromBalance,
uint256 balanceIncrease,
uint256 fromIndex) = cumulateBalanceInternal(_from);
require(fromBalance > 0, "Interest stream can only be redirected if there is a valid balance");
//if the user is already redirecting the interest to someone, before changing
//the redirection address we substract the redirected balance of the previous
//recipient
if(currentRedirectionAddress != address(0)){
updateRedirectedBalanceOfRedirectionAddressInternal(_from,0, previousPrincipalBalance);
}
//if the user is redirecting the interest back to himself,
//we simply set to 0 the interest redirection address
if(_to == _from) {
interestRedirectionAddresses[_from] = address(0);
emit InterestStreamRedirected(
_from,
address(0),
fromBalance,
balanceIncrease,
fromIndex
);
return;
}
//first set the redirection address to the new recipient
interestRedirectionAddresses[_from] = _to;
//adds the user balance to the redirected balance of the destination
updateRedirectedBalanceOfRedirectionAddressInternal(_from,fromBalance,0);
emit InterestStreamRedirected(
_from,
_to,
fromBalance,
balanceIncrease,
fromIndex
);
}
/**
* @dev function to reset the interest stream redirection and the user index, if the
* user has no balance left.
* @param _user the address of the user
* @return true if the user index has also been reset, false otherwise. useful to emit the proper user index value
**/
function resetDataOnZeroBalanceInternal(address _user) internal returns(bool) {
//if the user has 0 principal balance, the interest stream redirection gets reset
interestRedirectionAddresses[_user] = address(0);
//emits a InterestStreamRedirected event to notify that the redirection has been reset
emit InterestStreamRedirected(_user, address(0),0,0,0);
//if the redirected balance is also 0, we clear up the user index
if(redirectedBalances[_user] == 0){
userIndexes[_user] = 0;
return true;
}
else{
return false;
}
}
}
/**
* @title IFlashLoanReceiver interface
* @notice Interface for the Aave fee IFlashLoanReceiver.
* @author Aave
* @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract
**/
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
/**
* @title ILendingRateOracle interface
* @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations
**/
interface ILendingRateOracle {
/**
@dev returns the market borrow rate in ray
**/
function getMarketBorrowRate(address _asset) external view returns (uint256);
/**
@dev sets the market borrow rate. Rate value must be in ray
**/
function setMarketBorrowRate(address _asset, uint256 _rate) external;
}
/**
@title IReserveInterestRateStrategyInterface interface
@notice Interface for the calculation of the interest rates.
*/
interface IReserveInterestRateStrategy {
/**
* @dev returns the base variable borrow rate, in rays
*/
function getBaseVariableBorrowRate() external view returns (uint256);
/**
* @dev calculates the liquidity, stable, and variable rates depending on the current utilization rate
* and the base parameters
*
*/
function calculateInterestRates(
address _reserve,
uint256 _utilizationRate,
uint256 _totalBorrowsStable,
uint256 _totalBorrowsVariable,
uint256 _averageStableBorrowRate)
external
view
returns (uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate);
}
library EthAddressLib {
/**
* @dev returns the address used within the protocol to identify ETH
* @return the address assigned to ETH
*/
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
/**
* @title LendingPool contract
* @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data
* @author Aave
**/
contract LendingPool is ReentrancyGuard, VersionedInitializable {
using SafeMath for uint256;
using WadRayMath for uint256;
using Address for address;
LendingPoolAddressesProvider public addressesProvider;
LendingPoolCore public core;
LendingPoolDataProvider public dataProvider;
LendingPoolParametersProvider public parametersProvider;
IFeeProvider feeProvider;
/**
* @dev emitted on deposit
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _referral the referral number of the action
* @param _timestamp the timestamp of the action
**/
event Deposit(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint16 indexed _referral,
uint256 _timestamp
);
/**
* @dev emitted during a redeem action.
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _timestamp the timestamp of the action
**/
event RedeemUnderlying(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint256 _timestamp
);
/**
* @dev emitted on borrow
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _borrowRateMode the rate mode, can be either 1-stable or 2-variable
* @param _borrowRate the rate at which the user has borrowed
* @param _originationFee the origination fee to be paid by the user
* @param _borrowBalanceIncrease the balance increase since the last borrow, 0 if it's the first time borrowing
* @param _referral the referral number of the action
* @param _timestamp the timestamp of the action
**/
event Borrow(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint256 _borrowRateMode,
uint256 _borrowRate,
uint256 _originationFee,
uint256 _borrowBalanceIncrease,
uint16 indexed _referral,
uint256 _timestamp
);
/**
* @dev emitted on repay
* @param _reserve the address of the reserve
* @param _user the address of the user for which the repay has been executed
* @param _repayer the address of the user that has performed the repay action
* @param _amountMinusFees the amount repaid minus fees
* @param _fees the fees repaid
* @param _borrowBalanceIncrease the balance increase since the last action
* @param _timestamp the timestamp of the action
**/
event Repay(
address indexed _reserve,
address indexed _user,
address indexed _repayer,
uint256 _amountMinusFees,
uint256 _fees,
uint256 _borrowBalanceIncrease,
uint256 _timestamp
);
/**
* @dev emitted when a user performs a rate swap
* @param _reserve the address of the reserve
* @param _user the address of the user executing the swap
* @param _newRateMode the new interest rate mode
* @param _newRate the new borrow rate
* @param _borrowBalanceIncrease the balance increase since the last action
* @param _timestamp the timestamp of the action
**/
event Swap(
address indexed _reserve,
address indexed _user,
uint256 _newRateMode,
uint256 _newRate,
uint256 _borrowBalanceIncrease,
uint256 _timestamp
);
/**
* @dev emitted when a user enables a reserve as collateral
* @param _reserve the address of the reserve
* @param _user the address of the user
**/
event ReserveUsedAsCollateralEnabled(address indexed _reserve, address indexed _user);
/**
* @dev emitted when a user disables a reserve as collateral
* @param _reserve the address of the reserve
* @param _user the address of the user
**/
event ReserveUsedAsCollateralDisabled(address indexed _reserve, address indexed _user);
/**
* @dev emitted when the stable rate of a user gets rebalanced
* @param _reserve the address of the reserve
* @param _user the address of the user for which the rebalance has been executed
* @param _newStableRate the new stable borrow rate after the rebalance
* @param _borrowBalanceIncrease the balance increase since the last action
* @param _timestamp the timestamp of the action
**/
event RebalanceStableBorrowRate(
address indexed _reserve,
address indexed _user,
uint256 _newStableRate,
uint256 _borrowBalanceIncrease,
uint256 _timestamp
);
/**
* @dev emitted when a flashloan is executed
* @param _target the address of the flashLoanReceiver
* @param _reserve the address of the reserve
* @param _amount the amount requested
* @param _totalFee the total fee on the amount
* @param _protocolFee the part of the fee for the protocol
* @param _timestamp the timestamp of the action
**/
event FlashLoan(
address indexed _target,
address indexed _reserve,
uint256 _amount,
uint256 _totalFee,
uint256 _protocolFee,
uint256 _timestamp
);
/**
* @dev these events are not emitted directly by the LendingPool
* but they are declared here as the LendingPoolLiquidationManager
* is executed using a delegateCall().
* This allows to have the events in the generated ABI for LendingPool.
**/
/**
* @dev emitted when a borrow fee is liquidated
* @param _collateral the address of the collateral being liquidated
* @param _reserve the address of the reserve
* @param _user the address of the user being liquidated
* @param _feeLiquidated the total fee liquidated
* @param _liquidatedCollateralForFee the amount of collateral received by the protocol in exchange for the fee
* @param _timestamp the timestamp of the action
**/
event OriginationFeeLiquidated(
address indexed _collateral,
address indexed _reserve,
address indexed _user,
uint256 _feeLiquidated,
uint256 _liquidatedCollateralForFee,
uint256 _timestamp
);
/**
* @dev emitted when a borrower is liquidated
* @param _collateral the address of the collateral being liquidated
* @param _reserve the address of the reserve
* @param _user the address of the user being liquidated
* @param _purchaseAmount the total amount liquidated
* @param _liquidatedCollateralAmount the amount of collateral being liquidated
* @param _accruedBorrowInterest the amount of interest accrued by the borrower since the last action
* @param _liquidator the address of the liquidator
* @param _receiveAToken true if the liquidator wants to receive aTokens, false otherwise
* @param _timestamp the timestamp of the action
**/
event LiquidationCall(
address indexed _collateral,
address indexed _reserve,
address indexed _user,
uint256 _purchaseAmount,
uint256 _liquidatedCollateralAmount,
uint256 _accruedBorrowInterest,
address _liquidator,
bool _receiveAToken,
uint256 _timestamp
);
/**
* @dev functions affected by this modifier can only be invoked by the
* aToken.sol contract
* @param _reserve the address of the reserve
**/
modifier onlyOverlyingAToken(address _reserve) {
require(
msg.sender == core.getReserveATokenAddress(_reserve),
"The caller of this function can only be the aToken contract of this reserve"
);
_;
}
/**
* @dev functions affected by this modifier can only be invoked if the reserve is active
* @param _reserve the address of the reserve
**/
modifier onlyActiveReserve(address _reserve) {
requireReserveActiveInternal(_reserve);
_;
}
/**
* @dev functions affected by this modifier can only be invoked if the reserve is not freezed.
* A freezed reserve only allows redeems, repays, rebalances and liquidations.
* @param _reserve the address of the reserve
**/
modifier onlyUnfreezedReserve(address _reserve) {
requireReserveNotFreezedInternal(_reserve);
_;
}
/**
* @dev functions affected by this modifier can only be invoked if the provided _amount input parameter
* is not zero.
* @param _amount the amount provided
**/
modifier onlyAmountGreaterThanZero(uint256 _amount) {
requireAmountGreaterThanZeroInternal(_amount);
_;
}
uint256 public constant UINT_MAX_VALUE = uint256(-1);
uint256 public constant LENDINGPOOL_REVISION = 0x3;
function getRevision() internal pure returns (uint256) {
return LENDINGPOOL_REVISION;
}
/**
* @dev this function is invoked by the proxy contract when the LendingPool contract is added to the
* AddressesProvider.
* @param _addressesProvider the address of the LendingPoolAddressesProvider registry
**/
function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {
addressesProvider = _addressesProvider;
core = LendingPoolCore(addressesProvider.getLendingPoolCore());
dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider());
parametersProvider = LendingPoolParametersProvider(
addressesProvider.getLendingPoolParametersProvider()
);
feeProvider = IFeeProvider(addressesProvider.getFeeProvider());
}
/**
* @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens)
* is minted.
* @param _reserve the address of the reserve
* @param _amount the amount to be deposited
* @param _referralCode integrators are assigned a referral code and can potentially receive rewards.
**/
function deposit(address _reserve, uint256 _amount, uint16 _referralCode)
external
payable
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
AToken aToken = AToken(core.getReserveATokenAddress(_reserve));
bool isFirstDeposit = aToken.balanceOf(msg.sender) == 0;
core.updateStateOnDeposit(_reserve, msg.sender, _amount, isFirstDeposit);
//minting AToken to user 1:1 with the specific exchange rate
aToken.mintOnDeposit(msg.sender, _amount);
//transfer to the core contract
core.transferToReserve.value(msg.value)(_reserve, msg.sender, _amount);
//solium-disable-next-line
emit Deposit(_reserve, msg.sender, _amount, _referralCode, block.timestamp);
}
/**
* @dev Redeems the underlying amount of assets requested by _user.
* This function is executed by the overlying aToken contract in response to a redeem action.
* @param _reserve the address of the reserve
* @param _user the address of the user performing the action
* @param _amount the underlying amount to be redeemed
**/
function redeemUnderlying(
address _reserve,
address payable _user,
uint256 _amount,
uint256 _aTokenBalanceAfterRedeem
)
external
nonReentrant
onlyOverlyingAToken(_reserve)
onlyActiveReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
uint256 currentAvailableLiquidity = core.getReserveAvailableLiquidity(_reserve);
require(
currentAvailableLiquidity >= _amount,
"There is not enough liquidity available to redeem"
);
core.updateStateOnRedeem(_reserve, _user, _amount, _aTokenBalanceAfterRedeem == 0);
core.transferToUser(_reserve, _user, _amount);
//solium-disable-next-line
emit RedeemUnderlying(_reserve, _user, _amount, block.timestamp);
}
/**
* @dev data structures for local computations in the borrow() method.
*/
struct BorrowLocalVars {
uint256 principalBorrowBalance;
uint256 currentLtv;
uint256 currentLiquidationThreshold;
uint256 borrowFee;
uint256 requestedBorrowAmountETH;
uint256 amountOfCollateralNeededETH;
uint256 userCollateralBalanceETH;
uint256 userBorrowBalanceETH;
uint256 userTotalFeesETH;
uint256 borrowBalanceIncrease;
uint256 currentReserveStableRate;
uint256 availableLiquidity;
uint256 reserveDecimals;
uint256 finalUserBorrowRate;
CoreLibrary.InterestRateMode rateMode;
bool healthFactorBelowThreshold;
}
/**
* @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower
* already deposited enough collateral.
* @param _reserve the address of the reserve
* @param _amount the amount to be borrowed
* @param _interestRateMode the interest rate mode at which the user wants to borrow. Can be 0 (STABLE) or 1 (VARIABLE)
**/
function borrow(
address _reserve,
uint256 _amount,
uint256 _interestRateMode,
uint16 _referralCode
)
external
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
BorrowLocalVars memory vars;
//check that the reserve is enabled for borrowing
require(core.isReserveBorrowingEnabled(_reserve), "Reserve is not enabled for borrowing");
//validate interest rate mode
require(
uint256(CoreLibrary.InterestRateMode.VARIABLE) == _interestRateMode ||
uint256(CoreLibrary.InterestRateMode.STABLE) == _interestRateMode,
"Invalid interest rate mode selected"
);
//cast the rateMode to coreLibrary.interestRateMode
vars.rateMode = CoreLibrary.InterestRateMode(_interestRateMode);
//check that the amount is available in the reserve
vars.availableLiquidity = core.getReserveAvailableLiquidity(_reserve);
require(
vars.availableLiquidity >= _amount,
"There is not enough liquidity available in the reserve"
);
(
,
vars.userCollateralBalanceETH,
vars.userBorrowBalanceETH,
vars.userTotalFeesETH,
vars.currentLtv,
vars.currentLiquidationThreshold,
,
vars.healthFactorBelowThreshold
) = dataProvider.calculateUserGlobalData(msg.sender);
require(vars.userCollateralBalanceETH > 0, "The collateral balance is 0");
require(
!vars.healthFactorBelowThreshold,
"The borrower can already be liquidated so he cannot borrow more"
);
//calculating fees
vars.borrowFee = feeProvider.calculateLoanOriginationFee(msg.sender, _amount);
require(vars.borrowFee > 0, "The amount to borrow is too small");
vars.amountOfCollateralNeededETH = dataProvider.calculateCollateralNeededInETH(
_reserve,
_amount,
vars.borrowFee,
vars.userBorrowBalanceETH,
vars.userTotalFeesETH,
vars.currentLtv
);
require(
vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH,
"There is not enough collateral to cover a new borrow"
);
/**
* Following conditions need to be met if the user is borrowing at a stable rate:
* 1. Reserve must be enabled for stable rate borrowing
* 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency
* they are borrowing, to prevent abuses.
* 3. Users will be able to borrow only a relatively small, configurable amount of the total
* liquidity
**/
if (vars.rateMode == CoreLibrary.InterestRateMode.STABLE) {
//check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve
require(
core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, _amount),
"User cannot borrow the selected amount with a stable rate"
);
//calculate the max available loan size in stable rate mode as a percentage of the
//available liquidity
uint256 maxLoanPercent = parametersProvider.getMaxStableRateBorrowSizePercent();
uint256 maxLoanSizeStable = vars.availableLiquidity.mul(maxLoanPercent).div(100);
require(
_amount <= maxLoanSizeStable,
"User is trying to borrow too much liquidity at a stable rate"
);
}
//all conditions passed - borrow is accepted
(vars.finalUserBorrowRate, vars.borrowBalanceIncrease) = core.updateStateOnBorrow(
_reserve,
msg.sender,
_amount,
vars.borrowFee,
vars.rateMode
);
//if we reached this point, we can transfer
core.transferToUser(_reserve, msg.sender, _amount);
emit Borrow(
_reserve,
msg.sender,
_amount,
_interestRateMode,
vars.finalUserBorrowRate,
vars.borrowFee,
vars.borrowBalanceIncrease,
_referralCode,
//solium-disable-next-line
block.timestamp
);
}
/**
* @notice repays a borrow on the specific reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified).
* @dev the target user is defined by _onBehalfOf. If there is no repayment on behalf of another account,
* _onBehalfOf must be equal to msg.sender.
* @param _reserve the address of the reserve on which the user borrowed
* @param _amount the amount to repay, or uint256(-1) if the user wants to repay everything
* @param _onBehalfOf the address for which msg.sender is repaying.
**/
struct RepayLocalVars {
uint256 principalBorrowBalance;
uint256 compoundedBorrowBalance;
uint256 borrowBalanceIncrease;
bool isETH;
uint256 paybackAmount;
uint256 paybackAmountMinusFees;
uint256 currentStableRate;
uint256 originationFee;
}
function repay(address _reserve, uint256 _amount, address payable _onBehalfOf)
external
payable
nonReentrant
onlyActiveReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
RepayLocalVars memory vars;
(
vars.principalBorrowBalance,
vars.compoundedBorrowBalance,
vars.borrowBalanceIncrease
) = core.getUserBorrowBalances(_reserve, _onBehalfOf);
vars.originationFee = core.getUserOriginationFee(_reserve, _onBehalfOf);
vars.isETH = EthAddressLib.ethAddress() == _reserve;
require(vars.compoundedBorrowBalance > 0, "The user does not have any borrow pending");
require(
_amount != UINT_MAX_VALUE || msg.sender == _onBehalfOf,
"To repay on behalf of an user an explicit amount to repay is needed."
);
//default to max amount
vars.paybackAmount = vars.compoundedBorrowBalance.add(vars.originationFee);
if (_amount != UINT_MAX_VALUE && _amount < vars.paybackAmount) {
vars.paybackAmount = _amount;
}
require(
!vars.isETH || msg.value >= vars.paybackAmount,
"Invalid msg.value sent for the repayment"
);
//if the amount is smaller than the origination fee, just transfer the amount to the fee destination address
if (vars.paybackAmount <= vars.originationFee) {
core.updateStateOnRepay(
_reserve,
_onBehalfOf,
0,
vars.paybackAmount,
vars.borrowBalanceIncrease,
false
);
core.transferToFeeCollectionAddress.value(vars.isETH ? vars.paybackAmount : 0)(
_reserve,
_onBehalfOf,
vars.paybackAmount,
addressesProvider.getTokenDistributor()
);
emit Repay(
_reserve,
_onBehalfOf,
msg.sender,
0,
vars.paybackAmount,
vars.borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
return;
}
vars.paybackAmountMinusFees = vars.paybackAmount.sub(vars.originationFee);
core.updateStateOnRepay(
_reserve,
_onBehalfOf,
vars.paybackAmountMinusFees,
vars.originationFee,
vars.borrowBalanceIncrease,
vars.compoundedBorrowBalance == vars.paybackAmountMinusFees
);
//if the user didn't repay the origination fee, transfer the fee to the fee collection address
if(vars.originationFee > 0) {
core.transferToFeeCollectionAddress.value(vars.isETH ? vars.originationFee : 0)(
_reserve,
_onBehalfOf,
vars.originationFee,
addressesProvider.getTokenDistributor()
);
}
//sending the total msg.value if the transfer is ETH.
//the transferToReserve() function will take care of sending the
//excess ETH back to the caller
core.transferToReserve.value(vars.isETH ? msg.value.sub(vars.originationFee) : 0)(
_reserve,
msg.sender,
vars.paybackAmountMinusFees
);
emit Repay(
_reserve,
_onBehalfOf,
msg.sender,
vars.paybackAmountMinusFees,
vars.originationFee,
vars.borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
}
/**
* @dev borrowers can user this function to swap between stable and variable borrow rate modes.
* @param _reserve the address of the reserve on which the user borrowed
**/
function swapBorrowRateMode(address _reserve)
external
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
{
(uint256 principalBorrowBalance, uint256 compoundedBorrowBalance, uint256 borrowBalanceIncrease) = core
.getUserBorrowBalances(_reserve, msg.sender);
require(
compoundedBorrowBalance > 0,
"User does not have a borrow in progress on this reserve"
);
CoreLibrary.InterestRateMode currentRateMode = core.getUserCurrentBorrowRateMode(
_reserve,
msg.sender
);
if (currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
/**
* user wants to swap to stable, before swapping we need to ensure that
* 1. stable borrow rate is enabled on the reserve
* 2. user is not trying to abuse the reserve by depositing
* more collateral than he is borrowing, artificially lowering
* the interest rate, borrowing at variable, and switching to stable
**/
require(
core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, compoundedBorrowBalance),
"User cannot borrow the selected amount at stable"
);
}
(CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core
.updateStateOnSwapRate(
_reserve,
msg.sender,
principalBorrowBalance,
compoundedBorrowBalance,
borrowBalanceIncrease,
currentRateMode
);
emit Swap(
_reserve,
msg.sender,
uint256(newRateMode),
newBorrowRate,
borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
}
/**
* @dev rebalances the stable interest rate of a user if current liquidity rate > user stable rate.
* this is regulated by Aave to ensure that the protocol is not abused, and the user is paying a fair
* rate. The rebalance mechanism is updated in the context of the V1 -> V2 transition to automatically switch the user to variable.
* @param _reserve the address of the reserve
* @param _user the address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address _reserve, address _user)
external
nonReentrant
onlyActiveReserve(_reserve)
{
(uint256 principalBalance, uint256 compoundedBalance, uint256 borrowBalanceIncrease) = core.getUserBorrowBalances(
_reserve,
_user
);
//step 1: user must be borrowing on _reserve at a stable rate
require(compoundedBalance > 0, "User does not have any borrow for this reserve");
CoreLibrary.InterestRateMode rateMode = core.getUserCurrentBorrowRateMode(_reserve, _user);
require(
rateMode ==
CoreLibrary.InterestRateMode.STABLE,
"The user borrow is variable and cannot be rebalanced"
);
uint256 userCurrentStableRate = core.getUserCurrentStableBorrowRate(_reserve, _user);
uint256 liquidityRate = core.getReserveCurrentLiquidityRate(_reserve);
if (userCurrentStableRate < liquidityRate) {
(CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core
.updateStateOnSwapRate(
_reserve,
_user,
principalBalance,
compoundedBalance,
borrowBalanceIncrease,
rateMode
);
emit Swap(
_reserve,
_user,
uint256(newRateMode),
newBorrowRate,
borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
}
revert("Interest rate rebalance conditions were not met");
}
/**
* @dev allows depositors to enable or disable a specific deposit as collateral.
* @param _reserve the address of the reserve
* @param _useAsCollateral true if the user wants to user the deposit as collateral, false otherwise.
**/
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral)
external
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
{
uint256 underlyingBalance = core.getUserUnderlyingAssetBalance(_reserve, msg.sender);
require(underlyingBalance > 0, "User does not have any liquidity deposited");
require(
dataProvider.balanceDecreaseAllowed(_reserve, msg.sender, underlyingBalance),
"User deposit is already being used as collateral"
);
core.setUserUseReserveAsCollateral(_reserve, msg.sender, _useAsCollateral);
if (_useAsCollateral) {
emit ReserveUsedAsCollateralEnabled(_reserve, msg.sender);
} else {
emit ReserveUsedAsCollateralDisabled(_reserve, msg.sender);
}
}
/**
* @dev users can invoke this function to liquidate an undercollateralized position.
* @param _reserve the address of the collateral to liquidated
* @param _reserve the address of the principal reserve
* @param _user the address of the borrower
* @param _purchaseAmount the amount of principal that the liquidator wants to repay
* @param _receiveAToken true if the liquidators wants to receive the aTokens, false if
* he wants to receive the underlying asset directly
**/
function liquidationCall(
address _collateral,
address _reserve,
address _user,
uint256 _purchaseAmount,
bool _receiveAToken
) external payable nonReentrant onlyActiveReserve(_reserve) onlyActiveReserve(_collateral) {
address liquidationManager = addressesProvider.getLendingPoolLiquidationManager();
//solium-disable-next-line
(bool success, bytes memory result) = liquidationManager.delegatecall(
abi.encodeWithSignature(
"liquidationCall(address,address,address,uint256,bool)",
_collateral,
_reserve,
_user,
_purchaseAmount,
_receiveAToken
)
);
require(success, "Liquidation call failed");
(uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string));
if (returnCode != 0) {
//error found
revert(string(abi.encodePacked("Liquidation failed: ", returnMessage)));
}
}
/**
* @dev allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts
* that must be kept into consideration. For further details please visit https://developers.aave.com
* @param _receiver The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface.
* @param _reserve the address of the principal reserve
* @param _amount the amount requested for this flashloan
**/
function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes memory _params)
public
nonReentrant
onlyActiveReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
//check that the reserve has enough available liquidity
//we avoid using the getAvailableLiquidity() function in LendingPoolCore to save gas
uint256 availableLiquidityBefore = _reserve == EthAddressLib.ethAddress()
? address(core).balance
: IERC20(_reserve).balanceOf(address(core));
require(
availableLiquidityBefore >= _amount,
"There is not enough liquidity available to borrow"
);
(uint256 totalFeeBips, uint256 protocolFeeBips) = parametersProvider
.getFlashLoanFeesInBips();
//calculate amount fee
uint256 amountFee = _amount.mul(totalFeeBips).div(10000);
//protocol fee is the part of the amountFee reserved for the protocol - the rest goes to depositors
uint256 protocolFee = amountFee.mul(protocolFeeBips).div(10000);
require(
amountFee > 0 && protocolFee > 0,
"The requested amount is too small for a flashLoan."
);
//get the FlashLoanReceiver instance
IFlashLoanReceiver receiver = IFlashLoanReceiver(_receiver);
address payable userPayable = address(uint160(_receiver));
//transfer funds to the receiver
core.transferToUser(_reserve, userPayable, _amount);
//execute action of the receiver
receiver.executeOperation(_reserve, _amount, amountFee, _params);
//check that the actual balance of the core contract includes the returned amount
uint256 availableLiquidityAfter = _reserve == EthAddressLib.ethAddress()
? address(core).balance
: IERC20(_reserve).balanceOf(address(core));
require(
availableLiquidityAfter == availableLiquidityBefore.add(amountFee),
"The actual balance of the protocol is inconsistent"
);
core.updateStateOnFlashLoan(
_reserve,
availableLiquidityBefore,
amountFee.sub(protocolFee),
protocolFee
);
//solium-disable-next-line
emit FlashLoan(_receiver, _reserve, _amount, amountFee, protocolFee, block.timestamp);
}
/**
* @dev accessory functions to fetch data from the core contract
**/
function getReserveConfigurationData(address _reserve)
external
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address interestRateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
)
{
return dataProvider.getReserveConfigurationData(_reserve);
}
function getReserveData(address _reserve)
external
view
returns (
uint256 totalLiquidity,
uint256 availableLiquidity,
uint256 totalBorrowsStable,
uint256 totalBorrowsVariable,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 utilizationRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
address aTokenAddress,
uint40 lastUpdateTimestamp
)
{
return dataProvider.getReserveData(_reserve);
}
function getUserAccountData(address _user)
external
view
returns (
uint256 totalLiquidityETH,
uint256 totalCollateralETH,
uint256 totalBorrowsETH,
uint256 totalFeesETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
)
{
return dataProvider.getUserAccountData(_user);
}
function getUserReserveData(address _reserve, address _user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentBorrowBalance,
uint256 principalBorrowBalance,
uint256 borrowRateMode,
uint256 borrowRate,
uint256 liquidityRate,
uint256 originationFee,
uint256 variableBorrowIndex,
uint256 lastUpdateTimestamp,
bool usageAsCollateralEnabled
)
{
return dataProvider.getUserReserveData(_reserve, _user);
}
function getReserves() external view returns (address[] memory) {
return core.getReserves();
}
/**
* @dev internal function to save on code size for the onlyActiveReserve modifier
**/
function requireReserveActiveInternal(address _reserve) internal view {
require(core.getReserveIsActive(_reserve), "Action requires an active reserve");
}
/**
* @notice internal function to save on code size for the onlyUnfreezedReserve modifier
**/
function requireReserveNotFreezedInternal(address _reserve) internal view {
require(!core.getReserveIsFreezed(_reserve), "Action requires an unfreezed reserve");
}
/**
* @notice internal function to save on code size for the onlyAmountGreaterThanZero modifier
**/
function requireAmountGreaterThanZeroInternal(uint256 _amount) internal pure {
require(_amount > 0, "Amount must be greater than 0");
}
}
/**
* @title LendingPoolCore contract
* @author Aave
* @notice Holds the state of the lending pool and all the funds deposited
* @dev NOTE: The core does not enforce security checks on the update of the state
* (eg, updateStateOnBorrow() does not enforce that borrowed is enabled on the reserve).
* The check that an action can be performed is a duty of the overlying LendingPool contract.
**/
contract LendingPoolCore is VersionedInitializable {
using SafeMath for uint256;
using WadRayMath for uint256;
using CoreLibrary for CoreLibrary.ReserveData;
using CoreLibrary for CoreLibrary.UserReserveData;
using SafeERC20 for ERC20;
using Address for address payable;
/**
* @dev Emitted when the state of a reserve is updated
* @param reserve the address of the reserve
* @param liquidityRate the new liquidity rate
* @param stableBorrowRate the new stable borrow rate
* @param variableBorrowRate the new variable borrow rate
* @param liquidityIndex the new liquidity index
* @param variableBorrowIndex the new variable borrow index
**/
event ReserveUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
address public lendingPoolAddress;
LendingPoolAddressesProvider public addressesProvider;
/**
* @dev only lending pools can use functions affected by this modifier
**/
modifier onlyLendingPool {
require(lendingPoolAddress == msg.sender, "The caller must be a lending pool contract");
_;
}
/**
* @dev only lending pools configurator can use functions affected by this modifier
**/
modifier onlyLendingPoolConfigurator {
require(
addressesProvider.getLendingPoolConfigurator() == msg.sender,
"The caller must be a lending pool configurator contract"
);
_;
}
mapping(address => CoreLibrary.ReserveData) internal reserves;
mapping(address => mapping(address => CoreLibrary.UserReserveData)) internal usersReserveData;
address[] public reservesList;
uint256 public constant CORE_REVISION = 0x7;
/**
* @dev returns the revision number of the contract
**/
function getRevision() internal pure returns (uint256) {
return CORE_REVISION;
}
/**
* @dev initializes the Core contract, invoked upon registration on the AddressesProvider
* @param _addressesProvider the addressesProvider contract
**/
function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {
addressesProvider = _addressesProvider;
refreshConfigInternal();
}
/**
* @dev updates the state of the core as a result of a deposit action
* @param _reserve the address of the reserve in which the deposit is happening
* @param _user the address of the the user depositing
* @param _amount the amount being deposited
* @param _isFirstDeposit true if the user is depositing for the first time
**/
function updateStateOnDeposit(
address _reserve,
address _user,
uint256 _amount,
bool _isFirstDeposit
) external onlyLendingPool {
reserves[_reserve].updateCumulativeIndexes();
updateReserveInterestRatesAndTimestampInternal(_reserve, _amount, 0);
if (_isFirstDeposit) {
//if this is the first deposit of the user, we configure the deposit as enabled to be used as collateral
setUserUseReserveAsCollateral(_reserve, _user, true);
}
}
/**
* @dev updates the state of the core as a result of a redeem action
* @param _reserve the address of the reserve in which the redeem is happening
* @param _user the address of the the user redeeming
* @param _amountRedeemed the amount being redeemed
* @param _userRedeemedEverything true if the user is redeeming everything
**/
function updateStateOnRedeem(
address _reserve,
address _user,
uint256 _amountRedeemed,
bool _userRedeemedEverything
) external onlyLendingPool {
//compound liquidity and variable borrow interests
reserves[_reserve].updateCumulativeIndexes();
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountRedeemed);
//if user redeemed everything the useReserveAsCollateral flag is reset
if (_userRedeemedEverything) {
setUserUseReserveAsCollateral(_reserve, _user, false);
}
}
/**
* @dev updates the state of the core as a result of a flashloan action
* @param _reserve the address of the reserve in which the flashloan is happening
* @param _income the income of the protocol as a result of the action
**/
function updateStateOnFlashLoan(
address _reserve,
uint256 _availableLiquidityBefore,
uint256 _income,
uint256 _protocolFee
) external onlyLendingPool {
transferFlashLoanProtocolFeeInternal(_reserve, _protocolFee);
//compounding the cumulated interest
reserves[_reserve].updateCumulativeIndexes();
uint256 totalLiquidityBefore = _availableLiquidityBefore.add(
getReserveTotalBorrows(_reserve)
);
//compounding the received fee into the reserve
reserves[_reserve].cumulateToLiquidityIndex(totalLiquidityBefore, _income);
//refresh interest rates
updateReserveInterestRatesAndTimestampInternal(_reserve, _income, 0);
}
/**
* @dev updates the state of the core as a consequence of a borrow action.
* @param _reserve the address of the reserve on which the user is borrowing
* @param _user the address of the borrower
* @param _amountBorrowed the new amount borrowed
* @param _borrowFee the fee on the amount borrowed
* @param _rateMode the borrow rate mode (stable, variable)
* @return the new borrow rate for the user
**/
function updateStateOnBorrow(
address _reserve,
address _user,
uint256 _amountBorrowed,
uint256 _borrowFee,
CoreLibrary.InterestRateMode _rateMode
) external onlyLendingPool returns (uint256, uint256) {
// getting the previous borrow data of the user
(uint256 principalBorrowBalance, , uint256 balanceIncrease) = getUserBorrowBalances(
_reserve,
_user
);
updateReserveStateOnBorrowInternal(
_reserve,
_user,
principalBorrowBalance,
balanceIncrease,
_amountBorrowed,
_rateMode
);
updateUserStateOnBorrowInternal(
_reserve,
_user,
_amountBorrowed,
balanceIncrease,
_borrowFee,
_rateMode
);
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountBorrowed);
return (getUserCurrentBorrowRate(_reserve, _user), balanceIncrease);
}
/**
* @dev updates the state of the core as a consequence of a repay action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _paybackAmountMinusFees the amount being paid back minus fees
* @param _originationFeeRepaid the fee on the amount that is being repaid
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _repaidWholeLoan true if the user is repaying the whole loan
**/
function updateStateOnRepay(
address _reserve,
address _user,
uint256 _paybackAmountMinusFees,
uint256 _originationFeeRepaid,
uint256 _balanceIncrease,
bool _repaidWholeLoan
) external onlyLendingPool {
updateReserveStateOnRepayInternal(
_reserve,
_user,
_paybackAmountMinusFees,
_balanceIncrease
);
updateUserStateOnRepayInternal(
_reserve,
_user,
_paybackAmountMinusFees,
_originationFeeRepaid,
_balanceIncrease,
_repaidWholeLoan
);
updateReserveInterestRatesAndTimestampInternal(_reserve, _paybackAmountMinusFees, 0);
}
/**
* @dev updates the state of the core as a consequence of a swap rate action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _principalBorrowBalance the amount borrowed by the user
* @param _compoundedBorrowBalance the amount borrowed plus accrued interest
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _currentRateMode the current interest rate mode for the user
**/
function updateStateOnSwapRate(
address _reserve,
address _user,
uint256 _principalBorrowBalance,
uint256 _compoundedBorrowBalance,
uint256 _balanceIncrease,
CoreLibrary.InterestRateMode _currentRateMode
) external onlyLendingPool returns (CoreLibrary.InterestRateMode, uint256) {
updateReserveStateOnSwapRateInternal(
_reserve,
_user,
_principalBorrowBalance,
_compoundedBorrowBalance,
_currentRateMode
);
CoreLibrary.InterestRateMode newRateMode = updateUserStateOnSwapRateInternal(
_reserve,
_user,
_balanceIncrease,
_currentRateMode
);
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0);
return (newRateMode, getUserCurrentBorrowRate(_reserve, _user));
}
/**
* @dev updates the state of the core as a consequence of a liquidation action.
* @param _principalReserve the address of the principal reserve that is being repaid
* @param _collateralReserve the address of the collateral reserve that is being liquidated
* @param _user the address of the borrower
* @param _amountToLiquidate the amount being repaid by the liquidator
* @param _collateralToLiquidate the amount of collateral being liquidated
* @param _feeLiquidated the amount of origination fee being liquidated
* @param _liquidatedCollateralForFee the amount of collateral equivalent to the origination fee + bonus
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _liquidatorReceivesAToken true if the liquidator will receive aTokens, false otherwise
**/
function updateStateOnLiquidation(
address _principalReserve,
address _collateralReserve,
address _user,
uint256 _amountToLiquidate,
uint256 _collateralToLiquidate,
uint256 _feeLiquidated,
uint256 _liquidatedCollateralForFee,
uint256 _balanceIncrease,
bool _liquidatorReceivesAToken
) external onlyLendingPool {
updatePrincipalReserveStateOnLiquidationInternal(
_principalReserve,
_user,
_amountToLiquidate,
_balanceIncrease
);
updateCollateralReserveStateOnLiquidationInternal(
_collateralReserve
);
updateUserStateOnLiquidationInternal(
_principalReserve,
_user,
_amountToLiquidate,
_feeLiquidated,
_balanceIncrease
);
updateReserveInterestRatesAndTimestampInternal(_principalReserve, _amountToLiquidate, 0);
if (!_liquidatorReceivesAToken) {
updateReserveInterestRatesAndTimestampInternal(
_collateralReserve,
0,
_collateralToLiquidate.add(_liquidatedCollateralForFee)
);
}
}
/**
* @dev updates the state of the core as a consequence of a stable rate rebalance
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
* @return the new stable rate for the user
**/
function updateStateOnRebalance(address _reserve, address _user, uint256 _balanceIncrease)
external
onlyLendingPool
returns (uint256)
{
updateReserveStateOnRebalanceInternal(_reserve, _user, _balanceIncrease);
//update user data and rebalance the rate
updateUserStateOnRebalanceInternal(_reserve, _user, _balanceIncrease);
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0);
return usersReserveData[_user][_reserve].stableBorrowRate;
}
/**
* @dev enables or disables a reserve as collateral
* @param _reserve the address of the principal reserve where the user deposited
* @param _user the address of the depositor
* @param _useAsCollateral true if the depositor wants to use the reserve as collateral
**/
function setUserUseReserveAsCollateral(address _reserve, address _user, bool _useAsCollateral)
public
onlyLendingPool
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
user.useAsCollateral = _useAsCollateral;
}
/**
* @notice ETH/token transfer functions
**/
/**
* @dev fallback function enforces that the caller is a contract, to support flashloan transfers
**/
function() external payable {
//only contracts can send ETH to the core
require(msg.sender.isContract(), "Only contracts can send ether to the Lending pool core");
}
/**
* @dev transfers to the user a specific amount from the reserve.
* @param _reserve the address of the reserve where the transfer is happening
* @param _user the address of the user receiving the transfer
* @param _amount the amount being transferred
**/
function transferToUser(address _reserve, address payable _user, uint256 _amount)
external
onlyLendingPool
{
if (_reserve != EthAddressLib.ethAddress()) {
ERC20(_reserve).safeTransfer(_user, _amount);
} else {
//solium-disable-next-line
(bool result, ) = _user.call.value(_amount).gas(50000)("");
require(result, "Transfer of ETH failed");
}
}
/**
* @dev transfers the protocol fees to the fees collection address
* @param _token the address of the token being transferred
* @param _user the address of the user from where the transfer is happening
* @param _amount the amount being transferred
* @param _destination the fee receiver address
**/
function transferToFeeCollectionAddress(
address _token,
address _user,
uint256 _amount,
address _destination
) external payable onlyLendingPool {
address payable feeAddress = address(uint160(_destination)); //cast the address to payable
if (_token != EthAddressLib.ethAddress()) {
require(
msg.value == 0,
"User is sending ETH along with the ERC20 transfer. Check the value attribute of the transaction"
);
ERC20(_token).safeTransferFrom(_user, feeAddress, _amount);
} else {
require(msg.value >= _amount, "The amount and the value sent to deposit do not match");
//solium-disable-next-line
(bool result, ) = feeAddress.call.value(_amount).gas(50000)("");
require(result, "Transfer of ETH failed");
}
}
/**
* @dev transfers the fees to the fees collection address in the case of liquidation
* @param _token the address of the token being transferred
* @param _amount the amount being transferred
* @param _destination the fee receiver address
**/
function liquidateFee(
address _token,
uint256 _amount,
address _destination
) external payable onlyLendingPool {
address payable feeAddress = address(uint160(_destination)); //cast the address to payable
require(
msg.value == 0,
"Fee liquidation does not require any transfer of value"
);
if (_token != EthAddressLib.ethAddress()) {
ERC20(_token).safeTransfer(feeAddress, _amount);
} else {
//solium-disable-next-line
(bool result, ) = feeAddress.call.value(_amount).gas(50000)("");
require(result, "Transfer of ETH failed");
}
}
/**
* @dev transfers an amount from a user to the destination reserve
* @param _reserve the address of the reserve where the amount is being transferred
* @param _user the address of the user from where the transfer is happening
* @param _amount the amount being transferred
**/
function transferToReserve(address _reserve, address payable _user, uint256 _amount)
external
payable
onlyLendingPool
{
if (_reserve != EthAddressLib.ethAddress()) {
require(msg.value == 0, "User is sending ETH along with the ERC20 transfer.");
ERC20(_reserve).safeTransferFrom(_user, address(this), _amount);
} else {
require(msg.value >= _amount, "The amount and the value sent to deposit do not match");
if (msg.value > _amount) {
//send back excess ETH
uint256 excessAmount = msg.value.sub(_amount);
//solium-disable-next-line
(bool result, ) = _user.call.value(excessAmount).gas(50000)("");
require(result, "Transfer of ETH failed");
}
}
}
/**
* @notice data access functions
**/
/**
* @dev returns the basic data (balances, fee accrued, reserve enabled/disabled as collateral)
* needed to calculate the global account data in the LendingPoolDataProvider
* @param _reserve the address of the reserve
* @param _user the address of the user
* @return the user deposited balance, the principal borrow balance, the fee, and if the reserve is enabled as collateral or not
**/
function getUserBasicReserveData(address _reserve, address _user)
external
view
returns (uint256, uint256, uint256, bool)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
uint256 underlyingBalance = getUserUnderlyingAssetBalance(_reserve, _user);
if (user.principalBorrowBalance == 0) {
return (underlyingBalance, 0, 0, user.useAsCollateral);
}
return (
underlyingBalance,
user.getCompoundedBorrowBalance(reserve),
user.originationFee,
user.useAsCollateral
);
}
/**
* @dev checks if a user is allowed to borrow at a stable rate
* @param _reserve the reserve address
* @param _user the user
* @param _amount the amount the the user wants to borrow
* @return true if the user is allowed to borrow at a stable rate, false otherwise
**/
function isUserAllowedToBorrowAtStable(address _reserve, address _user, uint256 _amount)
external
view
returns (bool)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (!reserve.isStableBorrowRateEnabled) return false;
return
!user.useAsCollateral ||
!reserve.usageAsCollateralEnabled ||
_amount > getUserUnderlyingAssetBalance(_reserve, _user);
}
/**
* @dev gets the underlying asset balance of a user based on the corresponding aToken balance.
* @param _reserve the reserve address
* @param _user the user address
* @return the underlying deposit balance of the user
**/
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public
view
returns (uint256)
{
AToken aToken = AToken(reserves[_reserve].aTokenAddress);
return aToken.balanceOf(_user);
}
/**
* @dev gets the interest rate strategy contract address for the reserve
* @param _reserve the reserve address
* @return the address of the interest rate strategy contract
**/
function getReserveInterestRateStrategyAddress(address _reserve) public view returns (address) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.interestRateStrategyAddress;
}
/**
* @dev gets the aToken contract address for the reserve
* @param _reserve the reserve address
* @return the address of the aToken contract
**/
function getReserveATokenAddress(address _reserve) public view returns (address) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.aTokenAddress;
}
/**
* @dev gets the available liquidity in the reserve. The available liquidity is the balance of the core contract
* @param _reserve the reserve address
* @return the available liquidity
**/
function getReserveAvailableLiquidity(address _reserve) public view returns (uint256) {
uint256 balance = 0;
if (_reserve == EthAddressLib.ethAddress()) {
balance = address(this).balance;
} else {
balance = IERC20(_reserve).balanceOf(address(this));
}
return balance;
}
/**
* @dev gets the total liquidity in the reserve. The total liquidity is the balance of the core contract + total borrows
* @param _reserve the reserve address
* @return the total liquidity
**/
function getReserveTotalLiquidity(address _reserve) public view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return getReserveAvailableLiquidity(_reserve).add(reserve.getTotalBorrows());
}
/**
* @dev gets the normalized income of the reserve. a value of 1e27 means there is no income. A value of 2e27 means there
* there has been 100% income.
* @param _reserve the reserve address
* @return the reserve normalized income
**/
function getReserveNormalizedIncome(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.getNormalizedIncome();
}
/**
* @dev gets the reserve total borrows
* @param _reserve the reserve address
* @return the total borrows (stable + variable)
**/
function getReserveTotalBorrows(address _reserve) public view returns (uint256) {
return reserves[_reserve].getTotalBorrows();
}
/**
* @dev gets the reserve total borrows stable
* @param _reserve the reserve address
* @return the total borrows stable
**/
function getReserveTotalBorrowsStable(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.totalBorrowsStable;
}
/**
* @dev gets the reserve total borrows variable
* @param _reserve the reserve address
* @return the total borrows variable
**/
function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.totalBorrowsVariable;
}
/**
* @dev gets the reserve liquidation threshold
* @param _reserve the reserve address
* @return the reserve liquidation threshold
**/
function getReserveLiquidationThreshold(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.liquidationThreshold;
}
/**
* @dev gets the reserve liquidation bonus
* @param _reserve the reserve address
* @return the reserve liquidation bonus
**/
function getReserveLiquidationBonus(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.liquidationBonus;
}
/**
* @dev gets the reserve current variable borrow rate. Is the base variable borrow rate if the reserve is empty
* @param _reserve the reserve address
* @return the reserve current variable borrow rate
**/
function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
if (reserve.currentVariableBorrowRate == 0) {
return
IReserveInterestRateStrategy(reserve.interestRateStrategyAddress)
.getBaseVariableBorrowRate();
}
return reserve.currentVariableBorrowRate;
}
/**
* @dev gets the reserve current stable borrow rate. Is the market rate if the reserve is empty
* @param _reserve the reserve address
* @return the reserve current stable borrow rate
**/
function getReserveCurrentStableBorrowRate(address _reserve) public view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
ILendingRateOracle oracle = ILendingRateOracle(addressesProvider.getLendingRateOracle());
if (reserve.currentStableBorrowRate == 0) {
//no stable rate borrows yet
return oracle.getMarketBorrowRate(_reserve);
}
return reserve.currentStableBorrowRate;
}
/**
* @dev gets the reserve average stable borrow rate. The average stable rate is the weighted average
* of all the loans taken at stable rate.
* @param _reserve the reserve address
* @return the reserve current average borrow rate
**/
function getReserveCurrentAverageStableBorrowRate(address _reserve)
external
view
returns (uint256)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.currentAverageStableBorrowRate;
}
/**
* @dev gets the reserve liquidity rate
* @param _reserve the reserve address
* @return the reserve liquidity rate
**/
function getReserveCurrentLiquidityRate(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.currentLiquidityRate;
}
/**
* @dev gets the reserve liquidity cumulative index
* @param _reserve the reserve address
* @return the reserve liquidity cumulative index
**/
function getReserveLiquidityCumulativeIndex(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.lastLiquidityCumulativeIndex;
}
/**
* @dev gets the reserve variable borrow index
* @param _reserve the reserve address
* @return the reserve variable borrow index
**/
function getReserveVariableBorrowsCumulativeIndex(address _reserve)
external
view
returns (uint256)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.lastVariableBorrowCumulativeIndex;
}
/**
* @dev this function aggregates the configuration parameters of the reserve.
* It's used in the LendingPoolDataProvider specifically to save gas, and avoid
* multiple external contract calls to fetch the same data.
* @param _reserve the reserve address
* @return the reserve decimals
* @return the base ltv as collateral
* @return the liquidation threshold
* @return if the reserve is used as collateral or not
**/
function getReserveConfiguration(address _reserve)
external
view
returns (uint256, uint256, uint256, bool)
{
uint256 decimals;
uint256 baseLTVasCollateral;
uint256 liquidationThreshold;
bool usageAsCollateralEnabled;
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
decimals = reserve.decimals;
baseLTVasCollateral = reserve.baseLTVasCollateral;
liquidationThreshold = reserve.liquidationThreshold;
usageAsCollateralEnabled = reserve.usageAsCollateralEnabled;
return (decimals, baseLTVasCollateral, liquidationThreshold, usageAsCollateralEnabled);
}
/**
* @dev returns the decimals of the reserve
* @param _reserve the reserve address
* @return the reserve decimals
**/
function getReserveDecimals(address _reserve) external view returns (uint256) {
return reserves[_reserve].decimals;
}
/**
* @dev returns true if the reserve is enabled for borrowing
* @param _reserve the reserve address
* @return true if the reserve is enabled for borrowing, false otherwise
**/
function isReserveBorrowingEnabled(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.borrowingEnabled;
}
/**
* @dev returns true if the reserve is enabled as collateral
* @param _reserve the reserve address
* @return true if the reserve is enabled as collateral, false otherwise
**/
function isReserveUsageAsCollateralEnabled(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.usageAsCollateralEnabled;
}
/**
* @dev returns true if the stable rate is enabled on reserve
* @param _reserve the reserve address
* @return true if the stable rate is enabled on reserve, false otherwise
**/
function getReserveIsStableBorrowRateEnabled(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.isStableBorrowRateEnabled;
}
/**
* @dev returns true if the reserve is active
* @param _reserve the reserve address
* @return true if the reserve is active, false otherwise
**/
function getReserveIsActive(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.isActive;
}
/**
* @notice returns if a reserve is freezed
* @param _reserve the reserve for which the information is needed
* @return true if the reserve is freezed, false otherwise
**/
function getReserveIsFreezed(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.isFreezed;
}
/**
* @notice returns the timestamp of the last action on the reserve
* @param _reserve the reserve for which the information is needed
* @return the last updated timestamp of the reserve
**/
function getReserveLastUpdate(address _reserve) external view returns (uint40 timestamp) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
timestamp = reserve.lastUpdateTimestamp;
}
/**
* @dev returns the utilization rate U of a specific reserve
* @param _reserve the reserve for which the information is needed
* @return the utilization rate in ray
**/
function getReserveUtilizationRate(address _reserve) public view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
uint256 totalBorrows = reserve.getTotalBorrows();
if (totalBorrows == 0) {
return 0;
}
uint256 availableLiquidity = getReserveAvailableLiquidity(_reserve);
return totalBorrows.rayDiv(availableLiquidity.add(totalBorrows));
}
/**
* @return the array of reserves configured on the core
**/
function getReserves() external view returns (address[] memory) {
return reservesList;
}
/**
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return true if the user has chosen to use the reserve as collateral, false otherwise
**/
function isUserUseReserveAsCollateralEnabled(address _reserve, address _user)
external
view
returns (bool)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.useAsCollateral;
}
/**
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the origination fee for the user
**/
function getUserOriginationFee(address _reserve, address _user)
external
view
returns (uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.originationFee;
}
/**
* @dev users with no loans in progress have NONE as borrow rate mode
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the borrow rate mode for the user,
**/
function getUserCurrentBorrowRateMode(address _reserve, address _user)
public
view
returns (CoreLibrary.InterestRateMode)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (user.principalBorrowBalance == 0) {
return CoreLibrary.InterestRateMode.NONE;
}
return
user.stableBorrowRate > 0
? CoreLibrary.InterestRateMode.STABLE
: CoreLibrary.InterestRateMode.VARIABLE;
}
/**
* @dev gets the current borrow rate of the user
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the borrow rate for the user,
**/
function getUserCurrentBorrowRate(address _reserve, address _user)
internal
view
returns (uint256)
{
CoreLibrary.InterestRateMode rateMode = getUserCurrentBorrowRateMode(_reserve, _user);
if (rateMode == CoreLibrary.InterestRateMode.NONE) {
return 0;
}
return
rateMode == CoreLibrary.InterestRateMode.STABLE
? usersReserveData[_user][_reserve].stableBorrowRate
: reserves[_reserve].currentVariableBorrowRate;
}
/**
* @dev the stable rate returned is 0 if the user is borrowing at variable or not borrowing at all
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the user stable rate
**/
function getUserCurrentStableBorrowRate(address _reserve, address _user)
external
view
returns (uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.stableBorrowRate;
}
/**
* @dev calculates and returns the borrow balances of the user
* @param _reserve the address of the reserve
* @param _user the address of the user
* @return the principal borrow balance, the compounded balance and the balance increase since the last borrow/repay/swap/rebalance
**/
function getUserBorrowBalances(address _reserve, address _user)
public
view
returns (uint256, uint256, uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (user.principalBorrowBalance == 0) {
return (0, 0, 0);
}
uint256 principal = user.principalBorrowBalance;
uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance(
user,
reserves[_reserve]
);
return (principal, compoundedBalance, compoundedBalance.sub(principal));
}
/**
* @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the variable borrow index for the user
**/
function getUserVariableBorrowCumulativeIndex(address _reserve, address _user)
external
view
returns (uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.lastVariableBorrowCumulativeIndex;
}
/**
* @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the variable borrow index for the user
**/
function getUserLastUpdate(address _reserve, address _user)
external
view
returns (uint256 timestamp)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
timestamp = user.lastUpdateTimestamp;
}
/**
* @dev updates the lending pool core configuration
**/
function refreshConfiguration() external onlyLendingPoolConfigurator {
refreshConfigInternal();
}
/**
* @dev initializes a reserve
* @param _reserve the address of the reserve
* @param _aTokenAddress the address of the overlying aToken contract
* @param _decimals the decimals of the reserve currency
* @param _interestRateStrategyAddress the address of the interest rate strategy contract
**/
function initReserve(
address _reserve,
address _aTokenAddress,
uint256 _decimals,
address _interestRateStrategyAddress
) external onlyLendingPoolConfigurator {
reserves[_reserve].init(_aTokenAddress, _decimals, _interestRateStrategyAddress);
addReserveToListInternal(_reserve);
}
/**
* @dev removes the last added reserve in the reservesList array
* @param _reserveToRemove the address of the reserve
**/
function removeLastAddedReserve(address _reserveToRemove)
external onlyLendingPoolConfigurator {
address lastReserve = reservesList[reservesList.length-1];
require(lastReserve == _reserveToRemove, "Reserve being removed is different than the reserve requested");
//as we can't check if totalLiquidity is 0 (since the reserve added might not be an ERC20) we at least check that there is nothing borrowed
require(getReserveTotalBorrows(lastReserve) == 0, "Cannot remove a reserve with liquidity deposited");
reserves[lastReserve].isActive = false;
reserves[lastReserve].aTokenAddress = address(0);
reserves[lastReserve].decimals = 0;
reserves[lastReserve].lastLiquidityCumulativeIndex = 0;
reserves[lastReserve].lastVariableBorrowCumulativeIndex = 0;
reserves[lastReserve].borrowingEnabled = false;
reserves[lastReserve].usageAsCollateralEnabled = false;
reserves[lastReserve].baseLTVasCollateral = 0;
reserves[lastReserve].liquidationThreshold = 0;
reserves[lastReserve].liquidationBonus = 0;
reserves[lastReserve].interestRateStrategyAddress = address(0);
reservesList.pop();
}
/**
* @dev updates the address of the interest rate strategy contract
* @param _reserve the address of the reserve
* @param _rateStrategyAddress the address of the interest rate strategy contract
**/
function setReserveInterestRateStrategyAddress(address _reserve, address _rateStrategyAddress)
external
onlyLendingPoolConfigurator
{
reserves[_reserve].interestRateStrategyAddress = _rateStrategyAddress;
}
/**
* @dev enables borrowing on a reserve. Also sets the stable rate borrowing
* @param _reserve the address of the reserve
* @param _stableBorrowRateEnabled true if the stable rate needs to be enabled, false otherwise
**/
function enableBorrowingOnReserve(address _reserve, bool _stableBorrowRateEnabled)
external
onlyLendingPoolConfigurator
{
reserves[_reserve].enableBorrowing(_stableBorrowRateEnabled);
}
/**
* @dev disables borrowing on a reserve
* @param _reserve the address of the reserve
**/
function disableBorrowingOnReserve(address _reserve) external onlyLendingPoolConfigurator {
reserves[_reserve].disableBorrowing();
}
/**
* @dev enables a reserve to be used as collateral
* @param _reserve the address of the reserve
**/
function enableReserveAsCollateral(
address _reserve,
uint256 _baseLTVasCollateral,
uint256 _liquidationThreshold,
uint256 _liquidationBonus
) external onlyLendingPoolConfigurator {
reserves[_reserve].enableAsCollateral(
_baseLTVasCollateral,
_liquidationThreshold,
_liquidationBonus
);
}
/**
* @dev disables a reserve to be used as collateral
* @param _reserve the address of the reserve
**/
function disableReserveAsCollateral(address _reserve) external onlyLendingPoolConfigurator {
reserves[_reserve].disableAsCollateral();
}
/**
* @dev enable the stable borrow rate mode on a reserve
* @param _reserve the address of the reserve
**/
function enableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isStableBorrowRateEnabled = true;
}
/**
* @dev disable the stable borrow rate mode on a reserve
* @param _reserve the address of the reserve
**/
function disableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isStableBorrowRateEnabled = false;
}
/**
* @dev activates a reserve
* @param _reserve the address of the reserve
**/
function activateReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
require(
reserve.lastLiquidityCumulativeIndex > 0 &&
reserve.lastVariableBorrowCumulativeIndex > 0,
"Reserve has not been initialized yet"
);
reserve.isActive = true;
}
/**
* @dev deactivates a reserve
* @param _reserve the address of the reserve
**/
function deactivateReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isActive = false;
}
/**
* @notice allows the configurator to freeze the reserve.
* A freezed reserve does not allow any action apart from repay, redeem, liquidationCall, rebalance.
* @param _reserve the address of the reserve
**/
function freezeReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isFreezed = true;
}
/**
* @notice allows the configurator to unfreeze the reserve. A unfreezed reserve allows any action to be executed.
* @param _reserve the address of the reserve
**/
function unfreezeReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isFreezed = false;
}
/**
* @notice allows the configurator to update the loan to value of a reserve
* @param _reserve the address of the reserve
* @param _ltv the new loan to value
**/
function setReserveBaseLTVasCollateral(address _reserve, uint256 _ltv)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.baseLTVasCollateral = _ltv;
}
/**
* @notice allows the configurator to update the liquidation threshold of a reserve
* @param _reserve the address of the reserve
* @param _threshold the new liquidation threshold
**/
function setReserveLiquidationThreshold(address _reserve, uint256 _threshold)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.liquidationThreshold = _threshold;
}
/**
* @notice allows the configurator to update the liquidation bonus of a reserve
* @param _reserve the address of the reserve
* @param _bonus the new liquidation bonus
**/
function setReserveLiquidationBonus(address _reserve, uint256 _bonus)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.liquidationBonus = _bonus;
}
/**
* @notice allows the configurator to update the reserve decimals
* @param _reserve the address of the reserve
* @param _decimals the decimals of the reserve
**/
function setReserveDecimals(address _reserve, uint256 _decimals)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.decimals = _decimals;
}
/**
* @notice internal functions
**/
/**
* @dev updates the state of a reserve as a consequence of a borrow action.
* @param _reserve the address of the reserve on which the user is borrowing
* @param _user the address of the borrower
* @param _principalBorrowBalance the previous borrow balance of the borrower before the action
* @param _balanceIncrease the accrued interest of the user on the previous borrowed amount
* @param _amountBorrowed the new amount borrowed
* @param _rateMode the borrow rate mode (stable, variable)
**/
function updateReserveStateOnBorrowInternal(
address _reserve,
address _user,
uint256 _principalBorrowBalance,
uint256 _balanceIncrease,
uint256 _amountBorrowed,
CoreLibrary.InterestRateMode _rateMode
) internal {
reserves[_reserve].updateCumulativeIndexes();
//increasing reserve total borrows to account for the new borrow balance of the user
//NOTE: Depending on the previous borrow mode, the borrows might need to be switched from variable to stable or vice versa
updateReserveTotalBorrowsByRateModeInternal(
_reserve,
_user,
_principalBorrowBalance,
_balanceIncrease,
_amountBorrowed,
_rateMode
);
}
/**
* @dev updates the state of a user as a consequence of a borrow action.
* @param _reserve the address of the reserve on which the user is borrowing
* @param _user the address of the borrower
* @param _amountBorrowed the amount borrowed
* @param _balanceIncrease the accrued interest of the user on the previous borrowed amount
* @param _rateMode the borrow rate mode (stable, variable)
* @return the final borrow rate for the user. Emitted by the borrow() event
**/
function updateUserStateOnBorrowInternal(
address _reserve,
address _user,
uint256 _amountBorrowed,
uint256 _balanceIncrease,
uint256 _fee,
CoreLibrary.InterestRateMode _rateMode
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (_rateMode == CoreLibrary.InterestRateMode.STABLE) {
//stable
//reset the user variable index, and update the stable rate
user.stableBorrowRate = reserve.currentStableBorrowRate;
user.lastVariableBorrowCumulativeIndex = 0;
} else if (_rateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//variable
//reset the user stable rate, and store the new borrow index
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
} else {
revert("Invalid borrow rate mode");
}
//increase the principal borrows and the origination fee
user.principalBorrowBalance = user.principalBorrowBalance.add(_amountBorrowed).add(
_balanceIncrease
);
user.originationFee = user.originationFee.add(_fee);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the reserve as a consequence of a repay action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _paybackAmountMinusFees the amount being paid back minus fees
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateReserveStateOnRepayInternal(
address _reserve,
address _user,
uint256 _paybackAmountMinusFees,
uint256 _balanceIncrease
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user);
//update the indexes
reserves[_reserve].updateCumulativeIndexes();
//compound the cumulated interest to the borrow balance and then subtracting the payback amount
if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_balanceIncrease,
user.stableBorrowRate
);
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_paybackAmountMinusFees,
user.stableBorrowRate
);
} else {
reserve.increaseTotalBorrowsVariable(_balanceIncrease);
reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees);
}
}
/**
* @dev updates the state of the user as a consequence of a repay action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _paybackAmountMinusFees the amount being paid back minus fees
* @param _originationFeeRepaid the fee on the amount that is being repaid
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _repaidWholeLoan true if the user is repaying the whole loan
**/
function updateUserStateOnRepayInternal(
address _reserve,
address _user,
uint256 _paybackAmountMinusFees,
uint256 _originationFeeRepaid,
uint256 _balanceIncrease,
bool _repaidWholeLoan
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
//update the user principal borrow balance, adding the cumulated interest and then subtracting the payback amount
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub(
_paybackAmountMinusFees
);
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
//if the balance decrease is equal to the previous principal (user is repaying the whole loan)
//and the rate mode is stable, we reset the interest rate mode of the user
if (_repaidWholeLoan) {
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = 0;
}
user.originationFee = user.originationFee.sub(_originationFeeRepaid);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the user as a consequence of a swap rate action.
* @param _reserve the address of the reserve on which the user is performing the rate swap
* @param _user the address of the borrower
* @param _principalBorrowBalance the the principal amount borrowed by the user
* @param _compoundedBorrowBalance the principal amount plus the accrued interest
* @param _currentRateMode the rate mode at which the user borrowed
**/
function updateReserveStateOnSwapRateInternal(
address _reserve,
address _user,
uint256 _principalBorrowBalance,
uint256 _compoundedBorrowBalance,
CoreLibrary.InterestRateMode _currentRateMode
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
//compounding reserve indexes
reserve.updateCumulativeIndexes();
if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) {
uint256 userCurrentStableRate = user.stableBorrowRate;
//swap to variable
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_principalBorrowBalance,
userCurrentStableRate
); //decreasing stable from old principal balance
reserve.increaseTotalBorrowsVariable(_compoundedBorrowBalance); //increase variable borrows
} else if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//swap to stable
uint256 currentStableRate = reserve.currentStableBorrowRate;
reserve.decreaseTotalBorrowsVariable(_principalBorrowBalance);
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_compoundedBorrowBalance,
currentStableRate
);
} else {
revert("Invalid rate mode received");
}
}
/**
* @dev updates the state of the user as a consequence of a swap rate action.
* @param _reserve the address of the reserve on which the user is performing the swap
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _currentRateMode the current rate mode of the user
**/
function updateUserStateOnSwapRateInternal(
address _reserve,
address _user,
uint256 _balanceIncrease,
CoreLibrary.InterestRateMode _currentRateMode
) internal returns (CoreLibrary.InterestRateMode) {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.InterestRateMode newMode = CoreLibrary.InterestRateMode.NONE;
if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//switch to stable
newMode = CoreLibrary.InterestRateMode.STABLE;
user.stableBorrowRate = reserve.currentStableBorrowRate;
user.lastVariableBorrowCumulativeIndex = 0;
} else if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) {
newMode = CoreLibrary.InterestRateMode.VARIABLE;
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
} else {
revert("Invalid interest rate mode received");
}
//compounding cumulated interest
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
return newMode;
}
/**
* @dev updates the state of the principal reserve as a consequence of a liquidation action.
* @param _principalReserve the address of the principal reserve that is being repaid
* @param _user the address of the borrower
* @param _amountToLiquidate the amount being repaid by the liquidator
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updatePrincipalReserveStateOnLiquidationInternal(
address _principalReserve,
address _user,
uint256 _amountToLiquidate,
uint256 _balanceIncrease
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_principalReserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_principalReserve];
//update principal reserve data
reserve.updateCumulativeIndexes();
CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(
_principalReserve,
_user
);
if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {
//increase the total borrows by the compounded interest
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_balanceIncrease,
user.stableBorrowRate
);
//decrease by the actual amount to liquidate
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_amountToLiquidate,
user.stableBorrowRate
);
} else {
//increase the total borrows by the compounded interest
reserve.increaseTotalBorrowsVariable(_balanceIncrease);
//decrease by the actual amount to liquidate
reserve.decreaseTotalBorrowsVariable(_amountToLiquidate);
}
}
/**
* @dev updates the state of the collateral reserve as a consequence of a liquidation action.
* @param _collateralReserve the address of the collateral reserve that is being liquidated
**/
function updateCollateralReserveStateOnLiquidationInternal(
address _collateralReserve
) internal {
//update collateral reserve
reserves[_collateralReserve].updateCumulativeIndexes();
}
/**
* @dev updates the state of the user being liquidated as a consequence of a liquidation action.
* @param _reserve the address of the principal reserve that is being repaid
* @param _user the address of the borrower
* @param _amountToLiquidate the amount being repaid by the liquidator
* @param _feeLiquidated the amount of origination fee being liquidated
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateUserStateOnLiquidationInternal(
address _reserve,
address _user,
uint256 _amountToLiquidate,
uint256 _feeLiquidated,
uint256 _balanceIncrease
) internal {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
//first increase by the compounded interest, then decrease by the liquidated amount
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub(
_amountToLiquidate
);
if (
getUserCurrentBorrowRateMode(_reserve, _user) == CoreLibrary.InterestRateMode.VARIABLE
) {
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
}
if(_feeLiquidated > 0){
user.originationFee = user.originationFee.sub(_feeLiquidated);
}
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the reserve as a consequence of a stable rate rebalance
* DEPRECATED FOR THE V1 -> V2 migration
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateReserveStateOnRebalanceInternal(
address _reserve,
address _user,
uint256 _balanceIncrease
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
reserve.updateCumulativeIndexes();
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_balanceIncrease,
user.stableBorrowRate
);
}
/**
* @dev updates the state of the user as a consequence of a stable rate rebalance
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateUserStateOnRebalanceInternal(
address _reserve,
address _user,
uint256 _balanceIncrease
) internal {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease);
user.stableBorrowRate = reserve.currentStableBorrowRate;
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the user as a consequence of a stable rate rebalance
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _amountBorrowed the accrued interest on the borrowed amount
**/
function updateReserveTotalBorrowsByRateModeInternal(
address _reserve,
address _user,
uint256 _principalBalance,
uint256 _balanceIncrease,
uint256 _amountBorrowed,
CoreLibrary.InterestRateMode _newBorrowRateMode
) internal {
CoreLibrary.InterestRateMode previousRateMode = getUserCurrentBorrowRateMode(
_reserve,
_user
);
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
if (previousRateMode == CoreLibrary.InterestRateMode.STABLE) {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_principalBalance,
user.stableBorrowRate
);
} else if (previousRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
reserve.decreaseTotalBorrowsVariable(_principalBalance);
}
uint256 newPrincipalAmount = _principalBalance.add(_balanceIncrease).add(_amountBorrowed);
if (_newBorrowRateMode == CoreLibrary.InterestRateMode.STABLE) {
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
newPrincipalAmount,
reserve.currentStableBorrowRate
);
} else if (_newBorrowRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
reserve.increaseTotalBorrowsVariable(newPrincipalAmount);
} else {
revert("Invalid new borrow rate mode");
}
}
/**
* @dev Updates the reserve current stable borrow rate Rf, the current variable borrow rate Rv and the current liquidity rate Rl.
* Also updates the lastUpdateTimestamp value. Please refer to the whitepaper for further information.
* @param _reserve the address of the reserve to be updated
* @param _liquidityAdded the amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param _liquidityTaken the amount of liquidity taken from the protocol (redeem or borrow)
**/
function updateReserveInterestRatesAndTimestampInternal(
address _reserve,
uint256 _liquidityAdded,
uint256 _liquidityTaken
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
(uint256 newLiquidityRate, uint256 newStableRate, uint256 newVariableRate) = IReserveInterestRateStrategy(
reserve
.interestRateStrategyAddress
)
.calculateInterestRates(
_reserve,
getReserveAvailableLiquidity(_reserve).add(_liquidityAdded).sub(_liquidityTaken),
reserve.totalBorrowsStable,
reserve.totalBorrowsVariable,
reserve.currentAverageStableBorrowRate
);
reserve.currentLiquidityRate = newLiquidityRate;
reserve.currentStableBorrowRate = newStableRate;
reserve.currentVariableBorrowRate = newVariableRate;
//solium-disable-next-line
reserve.lastUpdateTimestamp = uint40(block.timestamp);
emit ReserveUpdated(
_reserve,
newLiquidityRate,
newStableRate,
newVariableRate,
reserve.lastLiquidityCumulativeIndex,
reserve.lastVariableBorrowCumulativeIndex
);
}
/**
* @dev transfers to the protocol fees of a flashloan to the fees collection address
* @param _token the address of the token being transferred
* @param _amount the amount being transferred
**/
function transferFlashLoanProtocolFeeInternal(address _token, uint256 _amount) internal {
address payable receiver = address(uint160(addressesProvider.getTokenDistributor()));
if (_token != EthAddressLib.ethAddress()) {
ERC20(_token).safeTransfer(receiver, _amount);
} else {
//solium-disable-next-line
(bool result, ) = receiver.call.value(_amount)("");
require(result, "Transfer to token distributor failed");
}
}
/**
* @dev updates the internal configuration of the core
**/
function refreshConfigInternal() internal {
lendingPoolAddress = addressesProvider.getLendingPool();
}
/**
* @dev adds a reserve to the array of the reserves address
**/
function addReserveToListInternal(address _reserve) internal {
bool reserveAlreadyAdded = false;
for (uint256 i = 0; i < reservesList.length; i++)
if (reservesList[i] == _reserve) {
reserveAlreadyAdded = true;
}
if (!reserveAlreadyAdded) reservesList.push(_reserve);
}
} | disables a reserve to be used as collateral _reserve the address of the reserve/ | function disableReserveAsCollateral(address _reserve) external onlyLendingPoolConfigurator {
reserves[_reserve].disableAsCollateral();
}
| 2,063,991 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.6;
pragma abicoder v2;
import '../interface/pool/ISummaSwapV3Pool.sol';
import './TickMath.sol';
import './BitMath.sol';
import './FullMath.sol';
import './Base64.sol';
import './HexStrings.sol';
import './NFTSVG.sol';
import './Strings.sol';
import './SafeMath.sol';
import './SignedSafeMath.sol';
library NFTDescriptor {
using TickMath for int24;
using Strings for uint256;
using SafeMath for uint256;
using SafeMath for uint160;
using SafeMath for uint8;
using SignedSafeMath for int256;
using HexStrings for uint256;
uint256 constant sqrt10X128 = 1076067327063303206878105757264492625226;
struct ConstructTokenURIParams {
uint256 tokenId;
address quoteTokenAddress;
address baseTokenAddress;
string quoteTokenSymbol;
string baseTokenSymbol;
uint8 quoteTokenDecimals;
uint8 baseTokenDecimals;
bool flipRatio;
int24 tickLower;
int24 tickUpper;
int24 tickCurrent;
int24 tickSpacing;
uint24 fee;
address poolAddress;
}
function constructTokenURI(ConstructTokenURIParams memory params) public pure returns (string memory) {
string memory name = generateName(params, feeToPercentString(params.fee));
string memory descriptionPartOne =
generateDescriptionPartOne(
escapeQuotes(params.quoteTokenSymbol),
escapeQuotes(params.baseTokenSymbol),
addressToString(params.poolAddress)
);
string memory descriptionPartTwo =
generateDescriptionPartTwo(
params.tokenId.toString(),
escapeQuotes(params.baseTokenSymbol),
addressToString(params.quoteTokenAddress),
addressToString(params.baseTokenAddress),
feeToPercentString(params.fee)
);
string memory image = Base64.encode(bytes(generateSVGImage(params)));
return
string(
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
name,
'", "description":"',
descriptionPartOne,
descriptionPartTwo,
'", "image": "',
'data:image/svg+xml;base64,',
image,
'"}'
)
)
)
)
);
}
function escapeQuotes(string memory symbol) internal pure returns (string memory) {
bytes memory symbolBytes = bytes(symbol);
uint8 quotesCount = 0;
for (uint8 i = 0; i < symbolBytes.length; i++) {
if (symbolBytes[i] == '"') {
quotesCount++;
}
}
if (quotesCount > 0) {
bytes memory escapedBytes = new bytes(symbolBytes.length + (quotesCount));
uint256 index;
for (uint8 i = 0; i < symbolBytes.length; i++) {
if (symbolBytes[i] == '"') {
escapedBytes[index++] = '\\';
}
escapedBytes[index++] = symbolBytes[i];
}
return string(escapedBytes);
}
return symbol;
}
function generateDescriptionPartOne(
string memory quoteTokenSymbol,
string memory baseTokenSymbol,
string memory poolAddress
) private pure returns (string memory) {
return
string(
abi.encodePacked(
'This NFT represents a liquidity position in a SummaSwap V3 ',
quoteTokenSymbol,
'-',
baseTokenSymbol,
' pool. ',
'The owner of this NFT can modify or redeem the position.\\n',
'\\nPool Address: ',
poolAddress,
'\\n',
quoteTokenSymbol
)
);
}
function generateDescriptionPartTwo(
string memory tokenId,
string memory baseTokenSymbol,
string memory quoteTokenAddress,
string memory baseTokenAddress,
string memory feeTier
) private pure returns (string memory) {
return
string(
abi.encodePacked(
' Address: ',
quoteTokenAddress,
'\\n',
baseTokenSymbol,
' Address: ',
baseTokenAddress,
'\\nFee Tier: ',
feeTier,
'\\nToken ID: ',
tokenId,
'\\n\\n',
unicode'⚠️ DISCLAIMER: Due diligence is imperative when assessing this NFT. Make sure token addresses match the expected tokens, as token symbols may be imitated.'
)
);
}
function generateName(ConstructTokenURIParams memory params, string memory feeTier)
private
pure
returns (string memory)
{
return
string(
abi.encodePacked(
'SummaSwap - ',
feeTier,
' - ',
escapeQuotes(params.quoteTokenSymbol),
'/',
escapeQuotes(params.baseTokenSymbol),
' - ',
tickToDecimalString(
!params.flipRatio ? params.tickLower : params.tickUpper,
params.tickSpacing,
params.baseTokenDecimals,
params.quoteTokenDecimals,
params.flipRatio
),
'<>',
tickToDecimalString(
!params.flipRatio ? params.tickUpper : params.tickLower,
params.tickSpacing,
params.baseTokenDecimals,
params.quoteTokenDecimals,
params.flipRatio
)
)
);
}
struct DecimalStringParams {
// significant figures of decimal
uint256 sigfigs;
// length of decimal string
uint8 bufferLength;
// ending index for significant figures (funtion works backwards when copying sigfigs)
uint8 sigfigIndex;
// index of decimal place (0 if no decimal)
uint8 decimalIndex;
// start index for trailing/leading 0's for very small/large numbers
uint8 zerosStartIndex;
// end index for trailing/leading 0's for very small/large numbers
uint8 zerosEndIndex;
// true if decimal number is less than one
bool isLessThanOne;
// true if string should include "%"
bool isPercent;
}
function generateDecimalString(DecimalStringParams memory params) private pure returns (string memory) {
bytes memory buffer = new bytes(params.bufferLength);
if (params.isPercent) {
buffer[buffer.length - 1] = '%';
}
if (params.isLessThanOne) {
buffer[0] = '0';
buffer[1] = '.';
}
// add leading/trailing 0's
for (uint256 zerosCursor = params.zerosStartIndex; zerosCursor < params.zerosEndIndex.add(1); zerosCursor++) {
buffer[zerosCursor] = bytes1(uint8(48));
}
// add sigfigs
while (params.sigfigs > 0) {
if (params.decimalIndex > 0 && params.sigfigIndex == params.decimalIndex) {
buffer[params.sigfigIndex--] = '.';
}
buffer[params.sigfigIndex--] = bytes1(uint8(uint256(48).add(params.sigfigs % 10)));
params.sigfigs /= 10;
}
return string(buffer);
}
function tickToDecimalString(
int24 tick,
int24 tickSpacing,
uint8 baseTokenDecimals,
uint8 quoteTokenDecimals,
bool flipRatio
) internal pure returns (string memory) {
if (tick == (TickMath.MIN_TICK / tickSpacing) * tickSpacing) {
return !flipRatio ? 'MIN' : 'MAX';
} else if (tick == (TickMath.MAX_TICK / tickSpacing) * tickSpacing) {
return !flipRatio ? 'MAX' : 'MIN';
} else {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
if (flipRatio) {
sqrtRatioX96 = uint160(uint256(1 << 192).div(sqrtRatioX96));
}
return fixedPointToDecimalString(sqrtRatioX96, baseTokenDecimals, quoteTokenDecimals);
}
}
function sigfigsRounded(uint256 value, uint8 digits) private pure returns (uint256, bool) {
bool extraDigit;
if (digits > 5) {
value = value.div((10**(digits - 5)));
}
bool roundUp = value % 10 > 4;
value = value.div(10);
if (roundUp) {
value = value + 1;
}
// 99999 -> 100000 gives an extra sigfig
if (value == 100000) {
value /= 10;
extraDigit = true;
}
return (value, extraDigit);
}
function adjustForDecimalPrecision(
uint160 sqrtRatioX96,
uint8 baseTokenDecimals,
uint8 quoteTokenDecimals
) private pure returns (uint256 adjustedSqrtRatioX96) {
uint256 difference = abs(int256(baseTokenDecimals).sub(int256(quoteTokenDecimals)));
if (difference > 0 && difference <= 18) {
if (baseTokenDecimals > quoteTokenDecimals) {
adjustedSqrtRatioX96 = sqrtRatioX96.mul(10**(difference.div(2)));
if (difference % 2 == 1) {
adjustedSqrtRatioX96 = FullMath.mulDiv(adjustedSqrtRatioX96, sqrt10X128, 1 << 128);
}
} else {
adjustedSqrtRatioX96 = sqrtRatioX96.div(10**(difference.div(2)));
if (difference % 2 == 1) {
adjustedSqrtRatioX96 = FullMath.mulDiv(adjustedSqrtRatioX96, 1 << 128, sqrt10X128);
}
}
} else {
adjustedSqrtRatioX96 = uint256(sqrtRatioX96);
}
}
function abs(int256 x) private pure returns (uint256) {
return uint256(x >= 0 ? x : -x);
}
// @notice Returns string that includes first 5 significant figures of a decimal number
// @param sqrtRatioX96 a sqrt price
function fixedPointToDecimalString(
uint160 sqrtRatioX96,
uint8 baseTokenDecimals,
uint8 quoteTokenDecimals
) internal pure returns (string memory) {
uint256 adjustedSqrtRatioX96 = adjustForDecimalPrecision(sqrtRatioX96, baseTokenDecimals, quoteTokenDecimals);
uint256 value = FullMath.mulDiv(adjustedSqrtRatioX96, adjustedSqrtRatioX96, 1 << 64);
bool priceBelow1 = adjustedSqrtRatioX96 < 2**96;
if (priceBelow1) {
// 10 ** 43 is precision needed to retreive 5 sigfigs of smallest possible price + 1 for rounding
value = FullMath.mulDiv(value, 10**44, 1 << 128);
} else {
// leave precision for 4 decimal places + 1 place for rounding
value = FullMath.mulDiv(value, 10**5, 1 << 128);
}
// get digit count
uint256 temp = value;
uint8 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
// don't count extra digit kept for rounding
digits = digits - 1;
// address rounding
(uint256 sigfigs, bool extraDigit) = sigfigsRounded(value, digits);
if (extraDigit) {
digits++;
}
DecimalStringParams memory params;
if (priceBelow1) {
// 7 bytes ( "0." and 5 sigfigs) + leading 0's bytes
params.bufferLength = uint8(uint8(7).add(uint8(43).sub(digits)));
params.zerosStartIndex = 2;
params.zerosEndIndex = uint8(uint256(43).sub(digits).add(1));
params.sigfigIndex = uint8(params.bufferLength.sub(1));
} else if (digits >= 9) {
// no decimal in price string
params.bufferLength = uint8(digits.sub(4));
params.zerosStartIndex = 5;
params.zerosEndIndex = uint8(params.bufferLength.sub(1));
params.sigfigIndex = 4;
} else {
// 5 sigfigs surround decimal
params.bufferLength = 6;
params.sigfigIndex = 5;
params.decimalIndex = uint8(digits.sub(5).add(1));
}
params.sigfigs = sigfigs;
params.isLessThanOne = priceBelow1;
params.isPercent = false;
return generateDecimalString(params);
}
// @notice Returns string as decimal percentage of fee amount.
// @param fee fee amount
function feeToPercentString(uint24 fee) internal pure returns (string memory) {
if (fee == 0) {
return '0%';
}
uint24 temp = fee;
uint256 digits;
uint8 numSigfigs;
while (temp != 0) {
if (numSigfigs > 0) {
// count all digits preceding least significant figure
numSigfigs++;
} else if (temp % 10 != 0) {
numSigfigs++;
}
digits++;
temp /= 10;
}
DecimalStringParams memory params;
uint256 nZeros;
if (digits >= 5) {
// if decimal > 1 (5th digit is the ones place)
uint256 decimalPlace = digits.sub(numSigfigs) >= 4 ? 0 : 1;
nZeros = digits.sub(5) < (numSigfigs.sub(1)) ? 0 : digits.sub(5).sub(numSigfigs.sub(1));
params.zerosStartIndex = numSigfigs;
params.zerosEndIndex = uint8(params.zerosStartIndex.add(nZeros).sub(1));
params.sigfigIndex = uint8(params.zerosStartIndex.sub(1).add(decimalPlace));
params.bufferLength = uint8(nZeros.add(numSigfigs.add(1)).add(decimalPlace));
} else {
// else if decimal < 1
nZeros = uint256(5).sub(digits);
params.zerosStartIndex = 2;
params.zerosEndIndex = uint8(nZeros.add(params.zerosStartIndex).sub(1));
params.bufferLength = uint8(nZeros.add(numSigfigs.add(2)));
params.sigfigIndex = uint8((params.bufferLength).sub(2));
params.isLessThanOne = true;
}
params.sigfigs = uint256(fee).div(10**(digits.sub(numSigfigs)));
params.isPercent = true;
params.decimalIndex = digits > 4 ? uint8(digits.sub(4)) : 0;
return generateDecimalString(params);
}
function addressToString(address addr) internal pure returns (string memory) {
return (uint256(addr)).toHexString(20);
}
function generateSVGImage(ConstructTokenURIParams memory params) internal pure returns (string memory svg) {
NFTSVG.SVGParams memory svgParams =
NFTSVG.SVGParams({
quoteToken: addressToString(params.quoteTokenAddress),
baseToken: addressToString(params.baseTokenAddress),
poolAddress: params.poolAddress,
quoteTokenSymbol: params.quoteTokenSymbol,
baseTokenSymbol: params.baseTokenSymbol,
feeTier: feeToPercentString(params.fee),
tickLower: params.tickLower,
tickUpper: params.tickUpper,
tickSpacing: params.tickSpacing,
overRange: overRange(params.tickLower, params.tickUpper, params.tickCurrent),
tokenId: params.tokenId,
color0: tokenToColorHex(uint256(params.quoteTokenAddress), 136),
color1: tokenToColorHex(uint256(params.baseTokenAddress), 136),
color2: tokenToColorHex(uint256(params.quoteTokenAddress), 0),
color3: tokenToColorHex(uint256(params.baseTokenAddress), 0),
x1: scale(getCircleCoord(uint256(params.quoteTokenAddress), 16, params.tokenId), 0, 255, 16, 274),
y1: scale(getCircleCoord(uint256(params.baseTokenAddress), 16, params.tokenId), 0, 255, 100, 484),
x2: scale(getCircleCoord(uint256(params.quoteTokenAddress), 32, params.tokenId), 0, 255, 16, 274),
y2: scale(getCircleCoord(uint256(params.baseTokenAddress), 32, params.tokenId), 0, 255, 100, 484),
x3: scale(getCircleCoord(uint256(params.quoteTokenAddress), 48, params.tokenId), 0, 255, 16, 274),
y3: scale(getCircleCoord(uint256(params.baseTokenAddress), 48, params.tokenId), 0, 255, 100, 484)
});
return NFTSVG.generateSVG(svgParams);
}
function overRange(
int24 tickLower,
int24 tickUpper,
int24 tickCurrent
) private pure returns (int8) {
if (tickCurrent < tickLower) {
return -1;
} else if (tickCurrent > tickUpper) {
return 1;
} else {
return 0;
}
}
function scale(
uint256 n,
uint256 inMn,
uint256 inMx,
uint256 outMn,
uint256 outMx
) private pure returns (string memory) {
return (n.sub(inMn).mul(outMx.sub(outMn)).div(inMx.sub(inMn)).add(outMn)).toString();
}
function tokenToColorHex(uint256 token, uint256 offset) internal pure returns (string memory str) {
return string((token >> offset).toHexStringNoPrefix(3));
}
function getCircleCoord(
uint256 tokenAddress,
uint256 offset,
uint256 tokenId
) internal pure returns (uint256) {
return (sliceTokenHex(tokenAddress, offset) * tokenId) % 255;
}
function sliceTokenHex(uint256 token, uint256 offset) internal pure returns (uint256) {
return uint256(uint8(token >> offset));
}
}
| add leading/trailing 0's add sigfigs | function generateDecimalString(DecimalStringParams memory params) private pure returns (string memory) {
bytes memory buffer = new bytes(params.bufferLength);
if (params.isPercent) {
buffer[buffer.length - 1] = '%';
}
if (params.isLessThanOne) {
buffer[0] = '0';
buffer[1] = '.';
}
for (uint256 zerosCursor = params.zerosStartIndex; zerosCursor < params.zerosEndIndex.add(1); zerosCursor++) {
buffer[zerosCursor] = bytes1(uint8(48));
}
while (params.sigfigs > 0) {
if (params.decimalIndex > 0 && params.sigfigIndex == params.decimalIndex) {
buffer[params.sigfigIndex--] = '.';
}
buffer[params.sigfigIndex--] = bytes1(uint8(uint256(48).add(params.sigfigs % 10)));
params.sigfigs /= 10;
}
return string(buffer);
}
| 6,387,580 |
pragma solidity ^0.4.24;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private pausers;
constructor() internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
pausers.remove(account);
emit PauserRemoved(account);
}
}
contract CapperRole {
using Roles for Roles.Role;
event CapperAdded(address indexed account);
event CapperRemoved(address indexed account);
Roles.Role private cappers;
constructor() internal {
_addCapper(msg.sender);
}
modifier onlyCapper() {
require(isCapper(msg.sender));
_;
}
function isCapper(address account) public view returns (bool) {
return cappers.has(account);
}
function addCapper(address account) public onlyCapper {
_addCapper(account);
}
function renounceCapper() public {
_removeCapper(msg.sender);
}
function _addCapper(address account) internal {
cappers.add(account);
emit CapperAdded(account);
}
function _removeCapper(address account) internal {
cappers.remove(account);
emit CapperRemoved(account);
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @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;
}
}
contract ERC20 is IERC20, MinterRole {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
mapping(address => bool) mastercardUsers;
mapping(address => bool) SGCUsers;
bool public walletLock;
bool public publicLock;
uint256 private _totalSupply;
/**
* @dev Total number of coins in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Total number of coins in existence
*/
function walletLock() public view returns (bool) {
return walletLock;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of coins that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of coins still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer coin for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of coins on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of coins to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
value = SafeMath.mul(value,1 ether);
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer coins from one address to another
* @param from address The address which you want to send coins from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of coins to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
value = SafeMath.mul(value, 1 ether);
require(value <= _allowed[from][msg.sender]);
require(value <= _balances[from]);
require(to != address(0));
require(value > 0);
require(!mastercardUsers[from]);
require(!walletLock);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
if(publicLock){
require(
SGCUsers[from]
&& SGCUsers[to]
);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
else{
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
return true;
}
/**
* @dev Increase the amount of coins 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 coin.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of coins to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
addedValue = SafeMath.mul(addedValue, 1 ether);
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of coins 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 coin.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of coins to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
subtractedValue = SafeMath.mul(subtractedValue, 1 ether);
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer coin for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
require(value > 0);
require(!mastercardUsers[from]);
if(publicLock && !walletLock){
require(
SGCUsers[from]
&& SGCUsers[to]
);
}
if(isMinter(from)){
_addSGCUsers(to);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
else{
require(!walletLock);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
}
/**
* @dev Internal function that mints an amount of the coin and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created coins.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the coin of a given
* account.
* @param account The account whose coins will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
value = SafeMath.mul(value,1 ether);
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the coin of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose coins will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
value = SafeMath.mul(value,1 ether);
require(value <= _allowed[account][msg.sender]);
require(account != 0);
require(value <= _balances[account]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _addSGCUsers(address newAddress) onlyMinter public {
if(!SGCUsers[newAddress]){
SGCUsers[newAddress] = true;
}
}
function getSGCUsers(address userAddress) public view returns (bool) {
return SGCUsers[userAddress];
}
}
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string name, string symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @title Burnable coin
* @dev Coin that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20, Pausable {
/**
* @dev Burns a specific amount of coins.
* @param value The amount of coin to be burned.
*/
function burn(uint256 value) public whenNotPaused{
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of coins from the target address and decrements allowance
* @param from address The address which you want to send coins from
* @param value uint256 The amount of coin to be burned
*/
function burnFrom(address from, uint256 value) public whenNotPaused {
_burnFrom(from, value);
}
}
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20 {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
function addMastercardUser(
address user
)
public
onlyMinter
{
mastercardUsers[user] = true;
}
function removeMastercardUser(
address user
)
public
onlyMinter
{
mastercardUsers[user] = false;
}
function updateWalletLock(
)
public
onlyMinter
{
if(walletLock){
walletLock = false;
}
else{
walletLock = true;
}
}
function updatePublicCheck(
)
public
onlyMinter
{
if(publicLock){
publicLock = false;
}
else{
publicLock = true;
}
}
}
/**
* @title Capped Coin
* @dev Mintable Coin with a coin cap.
*/
contract ERC20Capped is ERC20Mintable, CapperRole {
uint256 internal _latestCap;
constructor(uint256 cap)
public
{
require(cap > 0);
_latestCap = cap;
}
/**
* @return the cap for the coin minting.
*/
function cap() public view returns(uint256) {
return _latestCap;
}
function _updateCap (uint256 addCap) public onlyCapper {
addCap = SafeMath.mul(addCap, 1 ether);
_latestCap = addCap;
}
function _mint(address account, uint256 value) internal {
value = SafeMath.mul(value, 1 ether);
require(totalSupply().add(value) <= _latestCap);
super._mint(account, value);
}
}
/**
* @title Pausable coin
* @dev ERC20 modified with pausable transfers.
**/
contract ERC20Pausable is ERC20, Pausable {
function transfer(
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(to, value);
}
function transferFrom(
address from,
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(from, to, value);
}
function approve(
address spender,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.approve(spender, value);
}
function increaseAllowance(
address spender,
uint addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(
address spender,
uint subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseAllowance(spender, subtractedValue);
}
}
/**
* @title SecuredGoldCoin
* @dev
* -> SGC Coin is 60% Gold backed and 40% is utility coin
* -> SGC per coin gold weight is 21.2784 Milligrams with certification of LBMA
* (London Bullion Market Association)
* -> SGC Coin - Gold Description - 24 Caret - .9999 Purity - LMBA Certification
* -> The price will be locked till 14 April 2019 - 2 Euro per coin
* -> The merchants can start trading with all SGC users from 15 June 2019
* -> The coin will be available for sale from 15 April 2019 on the basis of live price
* -> Coins price can be live on the SGC users wallet from the day of activation
* of the wallet.
* -> During private sale coins can be bought from VIVA Gold Packages
* -> Coins will be available for public offer from November 2019
* -> The coin will be listed on exchange by November 2019.
* @author Junaid Mushtaq | Talha Yusuf
*/
contract SecuredGoldCoin is ERC20, ERC20Mintable, ERC20Detailed, ERC20Burnable, ERC20Pausable, ERC20Capped {
string public name = "Secured Gold Coin";
string public symbol = "SGC";
uint8 public decimals = 18;
uint public intialCap = 1000000000 * 1 ether;
constructor () public
ERC20Detailed(name, symbol, decimals)
ERC20Mintable()
ERC20Burnable()
ERC20Pausable()
ERC20Capped(intialCap)
ERC20()
{}
} | return the symbol of the token./ | function symbol() public view returns(string) {
return _symbol;
}
| 6,484,777 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IBaseExchange.sol";
import "../interfaces/ITokenFactory.sol";
import "../interfaces/IStrategy.sol";
import "../interfaces/IDividendPayingERC20.sol";
import "./ReentrancyGuardInitializable.sol";
import "../libraries/Signature.sol";
import "../interfaces/IERC2981.sol";
abstract contract BaseExchange is ReentrancyGuardInitializable, IBaseExchange {
using SafeERC20 for IERC20;
using Orders for Orders.Ask;
using Orders for Orders.Bid;
struct BestBid {
address bidder;
uint256 amount;
uint256 price;
address recipient;
address referrer;
uint256 timestamp;
}
mapping(address => mapping(bytes32 => mapping(address => bytes32))) internal _bidHashes;
mapping(bytes32 => BestBid) public override bestBid;
mapping(bytes32 => bool) public override isCancelledOrClaimed;
mapping(bytes32 => uint256) public override amountFilled;
function __BaseNFTExchange_init() internal initializer {
__ReentrancyGuard_init();
}
function DOMAIN_SEPARATOR() public view virtual override returns (bytes32);
function factory() public view virtual override returns (address);
function canTrade(address token) public view virtual override returns (bool) {
return token == address(this);
}
function approvedBidHash(
address proxy,
bytes32 askHash,
address bidder
) external view override returns (bytes32 bidHash) {
return _bidHashes[proxy][askHash][bidder];
}
function _transfer(
address token,
address from,
address to,
uint256 tokenId,
uint256 amount
) internal virtual;
function cancel(Orders.Ask memory order) external override {
require(order.signer == msg.sender || order.proxy == msg.sender, "SHOYU: FORBIDDEN");
bytes32 hash = order.hash();
require(bestBid[hash].bidder == address(0), "SHOYU: BID_EXISTS");
isCancelledOrClaimed[hash] = true;
emit Cancel(hash);
}
function updateApprovedBidHash(
bytes32 askHash,
address bidder,
bytes32 bidHash
) external override {
_bidHashes[msg.sender][askHash][bidder] = bidHash;
emit UpdateApprovedBidHash(msg.sender, askHash, bidder, bidHash);
}
function bid(Orders.Ask memory askOrder, Orders.Bid memory bidOrder)
external
override
nonReentrant
returns (bool executed)
{
bytes32 askHash = askOrder.hash();
require(askHash == bidOrder.askHash, "SHOYU: UNMATCHED_HASH");
require(bidOrder.signer != address(0), "SHOYU: INVALID_SIGNER");
bytes32 bidHash = bidOrder.hash();
if (askOrder.proxy != address(0)) {
require(
askOrder.proxy == msg.sender || _bidHashes[askOrder.proxy][askHash][bidOrder.signer] == bidHash,
"SHOYU: FORBIDDEN"
);
delete _bidHashes[askOrder.proxy][askHash][bidOrder.signer];
emit UpdateApprovedBidHash(askOrder.proxy, askHash, bidOrder.signer, bytes32(0));
}
Signature.verify(bidHash, bidOrder.signer, bidOrder.v, bidOrder.r, bidOrder.s, DOMAIN_SEPARATOR());
return
_bid(
askOrder,
askHash,
bidOrder.signer,
bidOrder.amount,
bidOrder.price,
bidOrder.recipient,
bidOrder.referrer
);
}
function bid(
Orders.Ask memory askOrder,
uint256 bidAmount,
uint256 bidPrice,
address bidRecipient,
address bidReferrer
) external override nonReentrant returns (bool executed) {
require(askOrder.proxy == address(0), "SHOYU: FORBIDDEN");
return _bid(askOrder, askOrder.hash(), msg.sender, bidAmount, bidPrice, bidRecipient, bidReferrer);
}
function _bid(
Orders.Ask memory askOrder,
bytes32 askHash,
address bidder,
uint256 bidAmount,
uint256 bidPrice,
address bidRecipient,
address bidReferrer
) internal returns (bool executed) {
require(canTrade(askOrder.token), "SHOYU: INVALID_EXCHANGE");
require(bidAmount > 0, "SHOYU: INVALID_AMOUNT");
uint256 _amountFilled = amountFilled[askHash];
require(_amountFilled + bidAmount <= askOrder.amount, "SHOYU: SOLD_OUT");
_validate(askOrder, askHash);
Signature.verify(askHash, askOrder.signer, askOrder.v, askOrder.r, askOrder.s, DOMAIN_SEPARATOR());
BestBid storage best = bestBid[askHash];
if (
IStrategy(askOrder.strategy).canClaim(
askOrder.proxy,
askOrder.deadline,
askOrder.params,
bidder,
bidPrice,
best.bidder,
best.price,
best.timestamp
)
) {
amountFilled[askHash] = _amountFilled + bidAmount;
if (_amountFilled + bidAmount == askOrder.amount) isCancelledOrClaimed[askHash] = true;
address recipient = askOrder.recipient;
if (recipient == address(0)) recipient = askOrder.signer;
require(
_transferFeesAndFunds(
askOrder.token,
askOrder.tokenId,
askOrder.currency,
bidder,
recipient,
bidPrice * bidAmount
),
"SHOYU: FAILED_TO_TRANSFER_FUNDS"
);
if (bidRecipient == address(0)) bidRecipient = bidder;
_transfer(askOrder.token, askOrder.signer, bidRecipient, askOrder.tokenId, bidAmount);
emit Claim(askHash, bidder, bidAmount, bidPrice, bidRecipient, bidReferrer);
return true;
} else {
if (
IStrategy(askOrder.strategy).canBid(
askOrder.proxy,
askOrder.deadline,
askOrder.params,
bidder,
bidPrice,
best.bidder,
best.price,
best.timestamp
)
) {
best.bidder = bidder;
best.amount = bidAmount;
best.price = bidPrice;
best.recipient = bidRecipient;
best.referrer = bidReferrer;
best.timestamp = block.timestamp;
emit Bid(askHash, bidder, bidAmount, bidPrice, bidRecipient, bidReferrer);
return false;
}
}
revert("SHOYU: FAILURE");
}
function claim(Orders.Ask memory askOrder) external override nonReentrant {
require(canTrade(askOrder.token), "SHOYU: INVALID_EXCHANGE");
bytes32 askHash = askOrder.hash();
_validate(askOrder, askHash);
Signature.verify(askHash, askOrder.signer, askOrder.v, askOrder.r, askOrder.s, DOMAIN_SEPARATOR());
BestBid memory best = bestBid[askHash];
require(
IStrategy(askOrder.strategy).canClaim(
askOrder.proxy,
askOrder.deadline,
askOrder.params,
best.bidder,
best.price,
best.bidder,
best.price,
best.timestamp
),
"SHOYU: FAILURE"
);
address recipient = askOrder.recipient;
if (recipient == address(0)) recipient = askOrder.signer;
isCancelledOrClaimed[askHash] = true;
require(
_transferFeesAndFunds(
askOrder.token,
askOrder.tokenId,
askOrder.currency,
best.bidder,
recipient,
best.price * best.amount
),
"SHOYU: FAILED_TO_TRANSFER_FUNDS"
);
amountFilled[askHash] = amountFilled[askHash] + best.amount;
address bidRecipient = best.recipient;
if (bidRecipient == address(0)) bidRecipient = best.bidder;
_transfer(askOrder.token, askOrder.signer, bidRecipient, askOrder.tokenId, best.amount);
delete bestBid[askHash];
emit Claim(askHash, best.bidder, best.amount, best.price, bidRecipient, best.referrer);
}
function _validate(Orders.Ask memory askOrder, bytes32 askHash) internal view {
require(!isCancelledOrClaimed[askHash], "SHOYU: CANCELLED_OR_CLAIMED");
require(askOrder.signer != address(0), "SHOYU: INVALID_MAKER");
require(askOrder.token != address(0), "SHOYU: INVALID_NFT");
require(askOrder.amount > 0, "SHOYU: INVALID_AMOUNT");
require(askOrder.strategy != address(0), "SHOYU: INVALID_STRATEGY");
require(askOrder.currency != address(0), "SHOYU: INVALID_CURRENCY");
require(ITokenFactory(factory()).isStrategyWhitelisted(askOrder.strategy), "SHOYU: STRATEGY_NOT_WHITELISTED");
}
function _transferFeesAndFunds(
address token,
uint256 tokenId,
address currency,
address from,
address to,
uint256 amount
) internal returns (bool) {
if (!_safeTransferFrom(currency, from, address(this), amount)) {
return false;
}
address _factory = factory();
uint256 remainder = amount;
{
(address protocolFeeRecipient, uint8 protocolFeePermil) = ITokenFactory(_factory).protocolFeeInfo();
uint256 protocolFeeAmount = (amount * protocolFeePermil) / 1000;
IERC20(currency).safeTransfer(protocolFeeRecipient, protocolFeeAmount);
remainder -= protocolFeeAmount;
}
{
(address operationalFeeRecipient, uint8 operationalFeePermil) =
ITokenFactory(_factory).operationalFeeInfo();
uint256 operationalFeeAmount = (amount * operationalFeePermil) / 1000;
IERC20(currency).safeTransfer(operationalFeeRecipient, operationalFeeAmount);
remainder -= operationalFeeAmount;
}
try IERC2981(token).royaltyInfo(tokenId, amount) returns (
address royaltyFeeRecipient,
uint256 royaltyFeeAmount
) {
if (royaltyFeeAmount > 0) {
remainder -= royaltyFeeAmount;
_transferRoyaltyFee(currency, royaltyFeeRecipient, royaltyFeeAmount);
}
} catch {}
IERC20(currency).safeTransfer(to, remainder);
return true;
}
function _safeTransferFrom(
address token,
address from,
address to,
uint256 value
) private returns (bool) {
(bool success, bytes memory returndata) =
token.call(abi.encodeWithSelector(IERC20(token).transferFrom.selector, from, to, value));
return success && (returndata.length == 0 || abi.decode(returndata, (bool)));
}
function _transferRoyaltyFee(
address currency,
address to,
uint256 amount
) internal {
IERC20(currency).safeTransfer(to, amount);
if (Address.isContract(to)) {
try IDividendPayingERC20(to).sync() returns (uint256) {} catch {}
}
}
}
// 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.5.0;
import "../libraries/Orders.sol";
interface IBaseExchange {
event Cancel(bytes32 indexed hash);
event Claim(
bytes32 indexed hash,
address bidder,
uint256 amount,
uint256 price,
address recipient,
address referrer
);
event Bid(bytes32 indexed hash, address bidder, uint256 amount, uint256 price, address recipient, address referrer);
event UpdateApprovedBidHash(
address indexed proxy,
bytes32 indexed askHash,
address indexed bidder,
bytes32 bidHash
);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function factory() external view returns (address);
function canTrade(address token) external view returns (bool);
function bestBid(bytes32 hash)
external
view
returns (
address bidder,
uint256 amount,
uint256 price,
address recipient,
address referrer,
uint256 blockNumber
);
function isCancelledOrClaimed(bytes32 hash) external view returns (bool);
function amountFilled(bytes32 hash) external view returns (uint256);
function approvedBidHash(
address proxy,
bytes32 askHash,
address bidder
) external view returns (bytes32 bidHash);
function cancel(Orders.Ask memory order) external;
function updateApprovedBidHash(
bytes32 askHash,
address bidder,
bytes32 bidHash
) external;
function bid(Orders.Ask memory askOrder, Orders.Bid memory bidOrder) external returns (bool executed);
function bid(
Orders.Ask memory askOrder,
uint256 bidAmount,
uint256 bidPrice,
address bidRecipient,
address bidReferrer
) external returns (bool executed);
function claim(Orders.Ask memory order) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface ITokenFactory {
event SetBaseURI721(string uri);
event SetBaseURI1155(string uri);
event SetProtocolFeeRecipient(address recipient);
event SetOperationalFee(uint8 fee);
event SetOperationalFeeRecipient(address recipient);
event SetDeployerWhitelisted(address deployer, bool whitelisted);
event SetStrategyWhitelisted(address strategy, bool whitelisted);
event UpgradeNFT721(address newTarget);
event UpgradeNFT1155(address newTarget);
event UpgradeSocialToken(address newTarget);
event UpgradeERC721Exchange(address exchange);
event UpgradeERC1155Exchange(address exchange);
event DeployNFT721AndMintBatch(
address indexed proxy,
address indexed owner,
string name,
string symbol,
uint256[] tokenIds,
address royaltyFeeRecipient,
uint8 royaltyFee
);
event DeployNFT721AndPark(
address indexed proxy,
address indexed owner,
string name,
string symbol,
uint256 toTokenId,
address royaltyFeeRecipient,
uint8 royaltyFee
);
event DeployNFT1155AndMintBatch(
address indexed proxy,
address indexed owner,
uint256[] tokenIds,
uint256[] amounts,
address royaltyFeeRecipient,
uint8 royaltyFee
);
event DeploySocialToken(
address indexed proxy,
address indexed owner,
string name,
string symbol,
address indexed dividendToken,
uint256 initialSupply
);
function MAX_ROYALTY_FEE() external view returns (uint8);
function MAX_OPERATIONAL_FEE() external view returns (uint8);
function PARK_TOKEN_IDS_721_TYPEHASH() external view returns (bytes32);
function MINT_BATCH_721_TYPEHASH() external view returns (bytes32);
function MINT_BATCH_1155_TYPEHASH() external view returns (bytes32);
function MINT_SOCIAL_TOKEN_TYPEHASH() external view returns (bytes32);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function nonces(address account) external view returns (uint256);
function baseURI721() external view returns (string memory);
function baseURI1155() external view returns (string memory);
function erc721Exchange() external view returns (address);
function erc1155Exchange() external view returns (address);
function protocolFeeInfo() external view returns (address recipient, uint8 permil);
function operationalFeeInfo() external view returns (address recipient, uint8 permil);
function isStrategyWhitelisted(address strategy) external view returns (bool);
function isDeployerWhitelisted(address strategy) external view returns (bool);
function setBaseURI721(string memory uri) external;
function setBaseURI1155(string memory uri) external;
function setProtocolFeeRecipient(address protocolFeeRecipient) external;
function setOperationalFeeRecipient(address operationalFeeRecipient) external;
function setOperationalFee(uint8 operationalFee) external;
function setDeployerWhitelisted(address deployer, bool whitelisted) external;
function setStrategyWhitelisted(address strategy, bool whitelisted) external;
function upgradeNFT721(address newTarget) external;
function upgradeNFT1155(address newTarget) external;
function upgradeSocialToken(address newTarget) external;
function upgradeERC721Exchange(address exchange) external;
function upgradeERC1155Exchange(address exchange) external;
function deployNFT721AndMintBatch(
address owner,
string calldata name,
string calldata symbol,
uint256[] calldata tokenIds,
address royaltyFeeRecipient,
uint8 royaltyFee
) external returns (address nft);
function deployNFT721AndPark(
address owner,
string calldata name,
string calldata symbol,
uint256 toTokenId,
address royaltyFeeRecipient,
uint8 royaltyFee
) external returns (address nft);
function isNFT721(address query) external view returns (bool result);
function deployNFT1155AndMintBatch(
address owner,
uint256[] memory tokenIds,
uint256[] memory amounts,
address royaltyFeeRecipient,
uint8 royaltyFee
) external returns (address nft);
function isNFT1155(address query) external view returns (bool result);
function deploySocialToken(
address owner,
string memory name,
string memory symbol,
address dividendToken,
uint256 initialSupply
) external returns (address proxy);
function isSocialToken(address query) external view returns (bool result);
function parkTokenIds721(
address nft,
uint256 toTokenId,
uint8 v,
bytes32 r,
bytes32 s
) external;
function mintBatch721(
address nft,
address to,
uint256[] calldata tokenIds,
bytes calldata data,
uint8 v,
bytes32 r,
bytes32 s
) external;
function mintBatch1155(
address nft,
address to,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
bytes calldata data,
uint8 v,
bytes32 r,
bytes32 s
) external;
function mintSocialToken(
address token,
address to,
uint256 amount,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "../libraries/Orders.sol";
interface IStrategy {
function canClaim(
address proxy,
uint256 deadline,
bytes memory params,
address bidder,
uint256 bidPrice,
address bestBidder,
uint256 bestBidPrice,
uint256 bestBidTimestamp
) external view returns (bool);
function canBid(
address proxy,
uint256 deadline,
bytes memory params,
address bidder,
uint256 bidPrice,
address bestBidder,
uint256 bestBidPrice,
uint256 bestBidTimestamp
) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
interface IDividendPayingERC20 is IERC20, IERC20Metadata {
/// @dev This event MUST emit when erc20/ether dividend is synced.
/// @param increased The amount of increased erc20/ether in wei.
event Sync(uint256 increased);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws erc20/ether from this contract.
/// @param amount The amount of withdrawn erc20/ether in wei.
event DividendWithdrawn(address indexed to, uint256 amount);
function MAGNITUDE() external view returns (uint256);
function dividendToken() external view returns (address);
function totalDividend() external view returns (uint256);
function sync() external payable returns (uint256 increased);
function withdrawDividend() external;
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` can withdraw.
function dividendOf(address account) external view returns (uint256);
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` can withdraw.
function withdrawableDividendOf(address account) external view returns (uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` has withdrawn.
function withdrawnDividendOf(address account) external view returns (uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(account) = withdrawableDividendOf(account) + withdrawnDividendOf(account)
/// = (magnifiedDividendPerShare * balanceOf(account) + magnifiedDividendCorrections[account]) / magnitude
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` has earned in total.
function accumulativeDividendOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardInitializable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
bool private constant _NOT_ENTERED = false;
bool private constant _ENTERED = true;
bool private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "SHOYU: REENTRANT");
// 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.3;
import "../interfaces/IERC1271.sol";
import "@openzeppelin/contracts/utils/Address.sol";
library Signature {
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"SHOYU: INVALID_SIGNATURE_S_VALUE"
);
require(v == 27 || v == 28, "SHOYU: 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), "SHOYU: INVALID_SIGNATURE");
return signer;
}
function verify(
bytes32 hash,
address signer,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 domainSeparator
) internal view {
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hash));
if (Address.isContract(signer)) {
require(
IERC1271(signer).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e,
"SHOYU: UNAUTHORIZED"
);
} else {
require(recover(digest, v, r, s) == signer, "SHOYU: UNAUTHORIZED");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
///
/// @dev Interface for the NFT Royalty Standard
///
interface IERC2981 is IERC165 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/// _registerInterface(_INTERFACE_ID_ERC2981);
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _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
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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.3;
library Orders {
// keccak256("Ask(address signer,address proxy,address token,uint256 tokenId,uint256 amount,address strategy,address currency,address recipient,uint256 deadline,bytes params)")
bytes32 internal constant ASK_TYPEHASH = 0x5fbc9a24e1532fa5245d1ec2dc5592849ae97ac5475f361b1a1f7a6e2ac9b2fd;
// keccak256("Bid(bytes32 askHash,address signer,uint256 amount,uint256 price,address recipient,address referrer)")
bytes32 internal constant BID_TYPEHASH = 0xb98e1dc48988064e6dfb813618609d7da80a8841e5f277039788ac4b50d497b2;
struct Ask {
address signer;
address proxy;
address token;
uint256 tokenId;
uint256 amount;
address strategy;
address currency;
address recipient;
uint256 deadline;
bytes params;
uint8 v;
bytes32 r;
bytes32 s;
}
struct Bid {
bytes32 askHash;
address signer;
uint256 amount;
uint256 price;
address recipient;
address referrer;
uint8 v;
bytes32 r;
bytes32 s;
}
function hash(Ask memory ask) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
ASK_TYPEHASH,
ask.signer,
ask.proxy,
ask.token,
ask.tokenId,
ask.amount,
ask.strategy,
ask.currency,
ask.recipient,
ask.deadline,
keccak256(ask.params)
)
);
}
function hash(Bid memory bid) internal pure returns (bytes32) {
return
keccak256(
abi.encode(BID_TYPEHASH, bid.askHash, bid.signer, bid.amount, bid.price, bid.recipient, bid.referrer)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @title Interface for verifying contract-based account signatures
/// @notice Interface that verifies provided signature for the data
/// @dev Interface defined by EIP-1271
interface IERC1271 {
/// @notice Returns whether the provided signature is valid for the provided data
/// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.
/// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).
/// MUST allow external calls.
/// @param hash Hash of the data to be signed
/// @param signature Signature byte array associated with _data
/// @return magicValue The bytes4 magic value 0x1626ba7e
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "./interfaces/INFT721.sol";
import "./base/BaseNFT721.sol";
import "./base/BaseExchange.sol";
contract NFT721V0 is BaseNFT721, BaseExchange, IERC2981, INFT721 {
uint8 internal _MAX_ROYALTY_FEE;
address internal _royaltyFeeRecipient;
uint8 internal _royaltyFee; // out of 1000
function initialize(
address _owner,
string memory _name,
string memory _symbol,
uint256[] memory tokenIds,
address royaltyFeeRecipient,
uint8 royaltyFee
) external override initializer {
__BaseNFTExchange_init();
initialize(_name, _symbol, _owner);
_MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE();
for (uint256 i = 0; i < tokenIds.length; i++) {
_safeMint(_owner, tokenIds[i]);
}
_setRoyaltyFeeRecipient(royaltyFeeRecipient);
_royaltyFee = type(uint8).max;
if (royaltyFee != 0) _setRoyaltyFee(royaltyFee);
}
function initialize(
address _owner,
string memory _name,
string memory _symbol,
uint256 toTokenId,
address royaltyFeeRecipient,
uint8 royaltyFee
) external override initializer {
__BaseNFTExchange_init();
initialize(_name, _symbol, _owner);
_MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE();
_parkTokenIds(toTokenId);
emit ParkTokenIds(toTokenId);
_setRoyaltyFeeRecipient(royaltyFeeRecipient);
_royaltyFee = type(uint8).max;
if (royaltyFee != 0) _setRoyaltyFee(royaltyFee);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Initializable, IERC165)
returns (bool)
{
return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId);
}
function DOMAIN_SEPARATOR() public view override(BaseNFT721, BaseExchange, INFT721) returns (bytes32) {
return BaseNFT721.DOMAIN_SEPARATOR();
}
function factory() public view override(BaseNFT721, BaseExchange, INFT721) returns (address) {
return _factory;
}
function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address, uint256) {
uint256 royaltyAmount;
if (_royaltyFee != type(uint8).max) royaltyAmount = (_salePrice * _royaltyFee) / 1000;
return (_royaltyFeeRecipient, royaltyAmount);
}
function _transfer(
address,
address from,
address to,
uint256 tokenId,
uint256
) internal override {
if (from == owner() && _parked(tokenId)) {
_safeMint(to, tokenId);
} else {
_transfer(from, to, tokenId);
}
}
function setRoyaltyFeeRecipient(address royaltyFeeRecipient) public override onlyOwner {
_setRoyaltyFeeRecipient(royaltyFeeRecipient);
}
function setRoyaltyFee(uint8 royaltyFee) public override onlyOwner {
_setRoyaltyFee(royaltyFee);
}
function _setRoyaltyFeeRecipient(address royaltyFeeRecipient) internal {
require(royaltyFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT");
_royaltyFeeRecipient = royaltyFeeRecipient;
emit SetRoyaltyFeeRecipient(royaltyFeeRecipient);
}
function _setRoyaltyFee(uint8 royaltyFee) internal {
if (_royaltyFee == type(uint8).max) {
require(royaltyFee <= _MAX_ROYALTY_FEE, "SHOYU: INVALID_FEE");
} else {
require(royaltyFee < _royaltyFee, "SHOYU: INVALID_FEE");
}
_royaltyFee = royaltyFee;
emit SetRoyaltyFee(royaltyFee);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./IBaseNFT721.sol";
import "./IBaseExchange.sol";
interface INFT721 is IBaseNFT721, IBaseExchange {
event SetRoyaltyFeeRecipient(address recipient);
event SetRoyaltyFee(uint8 fee);
function initialize(
address _owner,
string calldata _name,
string calldata _symbol,
uint256[] calldata tokenIds,
address royaltyFeeRecipient,
uint8 royaltyFee
) external;
function initialize(
address _owner,
string calldata _name,
string calldata _symbol,
uint256 toTokenId,
address royaltyFeeRecipient,
uint8 royaltyFee
) external;
function DOMAIN_SEPARATOR() external view override(IBaseNFT721, IBaseExchange) returns (bytes32);
function factory() external view override(IBaseNFT721, IBaseExchange) returns (address);
function setRoyaltyFeeRecipient(address _royaltyFeeRecipient) external;
function setRoyaltyFee(uint8 _royaltyFee) external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/utils/Strings.sol";
import "../interfaces/IBaseNFT721.sol";
import "../interfaces/IERC1271.sol";
import "../interfaces/ITokenFactory.sol";
import "../base/ERC721Initializable.sol";
import "../base/OwnableInitializable.sol";
import "../libraries/Signature.sol";
abstract contract BaseNFT721 is ERC721Initializable, OwnableInitializable, IBaseNFT721 {
// keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH =
0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad;
// keccak256("Permit(address owner,address spender,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_ALL_TYPEHASH =
0xdaab21af31ece73a508939fedd476a5ee5129a5ed4bb091f3236ffb45394df62;
bytes32 internal _DOMAIN_SEPARATOR;
uint256 internal _CACHED_CHAIN_ID;
address internal _factory;
string internal __baseURI;
mapping(uint256 => string) internal _uris;
mapping(uint256 => uint256) public override nonces;
mapping(address => uint256) public override noncesForAll;
function initialize(
string memory _name,
string memory _symbol,
address _owner
) public override initializer {
__ERC721_init(_name, _symbol);
__Ownable_init(_owner);
_factory = msg.sender;
_CACHED_CHAIN_ID = block.chainid;
_DOMAIN_SEPARATOR = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
function DOMAIN_SEPARATOR() public view virtual override returns (bytes32) {
bytes32 domainSeparator;
if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR;
else {
domainSeparator = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
return domainSeparator;
}
function factory() public view virtual override returns (address) {
return _factory;
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721Initializable, IERC721Metadata)
returns (string memory)
{
require(_exists(tokenId) || _parked(tokenId), "SHOYU: INVALID_TOKEN_ID");
string memory _uri = _uris[tokenId];
if (bytes(_uri).length > 0) {
return _uri;
} else {
string memory baseURI = __baseURI;
if (bytes(baseURI).length > 0) {
return string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json"));
} else {
baseURI = ITokenFactory(_factory).baseURI721();
string memory addy = Strings.toHexString(uint160(address(this)), 20);
return string(abi.encodePacked(baseURI, addy, "/", Strings.toString(tokenId), ".json"));
}
}
}
function parked(uint256 tokenId) external view override returns (bool) {
return _parked(tokenId);
}
function setTokenURI(uint256 id, string memory newURI) external override onlyOwner {
_uris[id] = newURI;
emit SetTokenURI(id, newURI);
}
function setBaseURI(string memory uri) external override onlyOwner {
__baseURI = uri;
emit SetBaseURI(uri);
}
function parkTokenIds(uint256 toTokenId) external override {
require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN");
_parkTokenIds(toTokenId);
emit ParkTokenIds(toTokenId);
}
function mint(
address to,
uint256 tokenId,
bytes memory data
) external override {
require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN");
_safeMint(to, tokenId, data);
}
function mintBatch(
address to,
uint256[] memory tokenIds,
bytes memory data
) external override {
require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN");
for (uint256 i = 0; i < tokenIds.length; i++) {
_safeMint(to, tokenIds[i], data);
}
}
function burn(
uint256 tokenId,
uint256 label,
bytes32 data
) external override {
require(ownerOf(tokenId) == msg.sender, "SHOYU: FORBIDDEN");
_burn(tokenId);
emit Burn(tokenId, label, data);
}
function burnBatch(uint256[] memory tokenIds) external override {
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
require(ownerOf(tokenId) == msg.sender, "SHOYU: FORBIDDEN");
_burn(tokenId);
}
}
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(block.timestamp <= deadline, "SHOYU: EXPIRED");
address owner = ownerOf(tokenId);
require(owner != address(0), "SHOYU: INVALID_TOKENID");
require(spender != owner, "SHOYU: NOT_NECESSARY");
bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, spender, tokenId, nonces[tokenId]++, deadline));
Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR());
_approve(spender, tokenId);
}
function permitAll(
address owner,
address spender,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(block.timestamp <= deadline, "SHOYU: EXPIRED");
require(owner != address(0), "SHOYU: INVALID_ADDRESS");
require(spender != owner, "SHOYU: NOT_NECESSARY");
bytes32 hash = keccak256(abi.encode(PERMIT_ALL_TYPEHASH, owner, spender, noncesForAll[owner]++, deadline));
Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR());
_setApprovalForAll(owner, spender, true);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "./IOwnable.sol";
interface IBaseNFT721 is IERC721, IERC721Metadata, IOwnable {
event SetTokenURI(uint256 indexed tokenId, string uri);
event SetBaseURI(string uri);
event ParkTokenIds(uint256 toTokenId);
event Burn(uint256 indexed tokenId, uint256 indexed label, bytes32 data);
function PERMIT_TYPEHASH() external view returns (bytes32);
function PERMIT_ALL_TYPEHASH() external view returns (bytes32);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function factory() external view returns (address);
function nonces(uint256 tokenId) external view returns (uint256);
function noncesForAll(address account) external view returns (uint256);
function parked(uint256 tokenId) external view returns (bool);
function initialize(
string calldata name,
string calldata symbol,
address _owner
) external;
function setTokenURI(uint256 id, string memory uri) external;
function setBaseURI(string memory uri) external;
function parkTokenIds(uint256 toTokenId) external;
function mint(
address to,
uint256 tokenId,
bytes calldata data
) external;
function mintBatch(
address to,
uint256[] calldata tokenIds,
bytes calldata data
) external;
function burn(
uint256 tokenId,
uint256 label,
bytes32 data
) external;
function burnBatch(uint256[] calldata tokenIds) external;
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function permitAll(
address owner,
address spender,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IOwnable {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function owner() external view returns (address);
function renounceOwnership() external;
function transferOwnership(address newOwner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Initializable is Initializable, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Upper bound of tokenId parked
uint256 private _toTokenIdParked;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "SHOYU: INVALID_OWNER");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _owners[tokenId];
}
/**
* @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), "SHOYU: INVALID_TOKEN_ID");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Initializable.ownerOf(tokenId);
require(to != owner, "SHOYU: INVALID_TO");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "SHOYU: FORBIDDEN");
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "SHOYU: INVALID_TOKEN_ID");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "SHOYU: NOT_APPROVED_NOR_OWNER");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(msg.sender, tokenId), "SHOYU: FORBIDDEN");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "SHOYU: INVALID_RECEIVER");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "SHOYU: INVALID_TOKEN_ID");
address owner = ERC721Initializable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal {
require(operator != owner, "SHOYU: INVALID_OPERATOR");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
function _parked(uint256 tokenId) internal view virtual returns (bool) {
address owner = ERC721Initializable.ownerOf(tokenId);
return owner == address(0) && tokenId < _toTokenIdParked;
}
function _parkTokenIds(uint256 toTokenId) internal virtual {
uint256 fromTokenId = _toTokenIdParked;
require(toTokenId > fromTokenId, "SHOYU: INVALID_TO_TOKEN_ID");
_toTokenIdParked = toTokenId;
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "SHOYU: INVALID_RECEIVER");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "SHOYU: INVALID_TO");
require(!_exists(tokenId), "SHOYU: ALREADY_MINTED");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Initializable.ownerOf(tokenId);
require(owner != address(0), "SHOYU: INVALID_TOKEN_ID");
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Initializable.ownerOf(tokenId) == from, "SHOYU: TRANSFER_FORBIDDEN");
require(to != address(0), "SHOYU: INVALID_RECIPIENT");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Initializable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("SHOYU: INVALID_RECEIVER");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "../interfaces/IOwnable.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 OwnableInitializable is Initializable, IOwnable {
address private _owner;
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init(address __owner) internal initializer {
__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 override returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == msg.sender, "SHOYU: FORBIDDEN");
_;
}
/**
* @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 override 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 override onlyOwner {
require(newOwner != address(0), "SHOYU: INVALID_NEW_OWNER");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./interfaces/ITokenFactory.sol";
import "./interfaces/IBaseNFT721.sol";
import "./interfaces/IBaseNFT1155.sol";
import "./interfaces/ISocialToken.sol";
import "./base/ProxyFactory.sol";
import "./libraries/Signature.sol";
contract TokenFactory is ProxyFactory, Ownable, ITokenFactory {
uint8 public constant override MAX_ROYALTY_FEE = 250; // 25%
uint8 public constant override MAX_OPERATIONAL_FEE = 50; // 5%
// keccak256("ParkTokenIds721(address nft,uint256 toTokenId,uint256 nonce)");
bytes32 public constant override PARK_TOKEN_IDS_721_TYPEHASH =
0x3fddacac0a7d8b05f741f01ff6becadd9986be8631a2af41a675f365dd74090d;
// keccak256("MintBatch721(address nft,address to,uint256[] tokenIds,bytes data,uint256 nonce)");
bytes32 public constant override MINT_BATCH_721_TYPEHASH =
0x884adba7f4e17962aed36c871036adea39c6d9f81fb25407a78db239e9731e86;
// keccak256("MintBatch1155(address nft,address to,uint256[] tokenIds,uint256[] amounts,bytes data,uint256 nonce)");
bytes32 public constant override MINT_BATCH_1155_TYPEHASH =
0xb47ce0f6456fcc2f16b7d6e7b0255eb73822b401248e672a4543c2b3d7183043;
// keccak256("MintSocialToken(address token,address to,uint256 amount,uint256 nonce)");
bytes32 public constant override MINT_SOCIAL_TOKEN_TYPEHASH =
0x8f4bf92e5271f5ec2f59dc3fc74368af0064fb84b40a3de9150dd26c08cda104;
bytes32 internal immutable _DOMAIN_SEPARATOR;
uint256 internal immutable _CACHED_CHAIN_ID;
address[] internal _targets721;
address[] internal _targets1155;
address[] internal _targetsSocialToken;
address internal _protocolFeeRecipient;
uint8 internal _protocolFee; // out of 1000
address internal _operationalFeeRecipient;
uint8 internal _operationalFee; // out of 1000
mapping(address => uint256) public override nonces;
string public override baseURI721;
string public override baseURI1155;
address public override erc721Exchange;
address public override erc1155Exchange;
// any account can deploy proxies if isDeployerWhitelisted[0x0000000000000000000000000000000000000000] == true
mapping(address => bool) public override isDeployerWhitelisted;
mapping(address => bool) public override isStrategyWhitelisted;
modifier onlyDeployer {
require(isDeployerWhitelisted[address(0)] || isDeployerWhitelisted[msg.sender], "SHOYU: FORBIDDEN");
_;
}
constructor(
address protocolFeeRecipient,
uint8 protocolFee,
address operationalFeeRecipient,
uint8 operationalFee,
string memory _baseURI721,
string memory _baseURI1155
) {
_protocolFeeRecipient = protocolFeeRecipient;
_protocolFee = protocolFee;
_operationalFeeRecipient = operationalFeeRecipient;
_operationalFee = operationalFee;
baseURI721 = _baseURI721;
baseURI1155 = _baseURI1155;
_CACHED_CHAIN_ID = block.chainid;
_DOMAIN_SEPARATOR = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
function DOMAIN_SEPARATOR() public view override returns (bytes32) {
bytes32 domainSeparator;
if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR;
else {
domainSeparator = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
return domainSeparator;
}
function protocolFeeInfo() external view override returns (address recipient, uint8 permil) {
return (_protocolFeeRecipient, _protocolFee);
}
function operationalFeeInfo() external view override returns (address recipient, uint8 permil) {
return (_operationalFeeRecipient, _operationalFee);
}
// This function should be called with a proper param by a multi-sig `owner`
function setBaseURI721(string memory uri) external override onlyOwner {
baseURI721 = uri;
emit SetBaseURI721(uri);
}
// This function should be called with a proper param by a multi-sig `owner`
function setBaseURI1155(string memory uri) external override onlyOwner {
baseURI1155 = uri;
emit SetBaseURI1155(uri);
}
// This function should be called by a multi-sig `owner`, not an EOA
function setProtocolFeeRecipient(address protocolFeeRecipient) external override onlyOwner {
require(protocolFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT");
_protocolFeeRecipient = protocolFeeRecipient;
emit SetProtocolFeeRecipient(protocolFeeRecipient);
}
// This function should be called by a multi-sig `owner`, not an EOA
function setOperationalFeeRecipient(address operationalFeeRecipient) external override onlyOwner {
require(operationalFeeRecipient != address(0), "SHOYU: INVALID_RECIPIENT");
_operationalFeeRecipient = operationalFeeRecipient;
emit SetOperationalFeeRecipient(operationalFeeRecipient);
}
// This function should be called by a multi-sig `owner`, not an EOA
function setOperationalFee(uint8 operationalFee) external override onlyOwner {
require(operationalFee <= MAX_OPERATIONAL_FEE, "SHOYU: INVALID_FEE");
_operationalFee = operationalFee;
emit SetOperationalFee(operationalFee);
}
// This function should be called by a multi-sig `owner`, not an EOA
function setDeployerWhitelisted(address deployer, bool whitelisted) external override onlyOwner {
isDeployerWhitelisted[deployer] = whitelisted;
emit SetDeployerWhitelisted(deployer, whitelisted);
}
// This function should be called by a multi-sig `owner`, not an EOA
function setStrategyWhitelisted(address strategy, bool whitelisted) external override onlyOwner {
require(strategy != address(0), "SHOYU: INVALID_ADDRESS");
isStrategyWhitelisted[strategy] = whitelisted;
emit SetStrategyWhitelisted(strategy, whitelisted);
}
// This function should be called by a multi-sig `owner`, not an EOA
function upgradeNFT721(address newTarget) external override onlyOwner {
_targets721.push(newTarget);
emit UpgradeNFT721(newTarget);
}
// This function should be called by a multi-sig `owner`, not an EOA
function upgradeNFT1155(address newTarget) external override onlyOwner {
_targets1155.push(newTarget);
emit UpgradeNFT1155(newTarget);
}
// This function should be called by a multi-sig `owner`, not an EOA
function upgradeSocialToken(address newTarget) external override onlyOwner {
_targetsSocialToken.push(newTarget);
emit UpgradeSocialToken(newTarget);
}
// This function should be called by a multi-sig `owner`, not an EOA
function upgradeERC721Exchange(address exchange) external override onlyOwner {
erc721Exchange = exchange;
emit UpgradeERC721Exchange(exchange);
}
// This function should be called by a multi-sig `owner`, not an EOA
function upgradeERC1155Exchange(address exchange) external override onlyOwner {
erc1155Exchange = exchange;
emit UpgradeERC1155Exchange(exchange);
}
function deployNFT721AndMintBatch(
address owner,
string calldata name,
string calldata symbol,
uint256[] memory tokenIds,
address royaltyFeeRecipient,
uint8 royaltyFee
) external override onlyDeployer returns (address nft) {
require(bytes(name).length > 0, "SHOYU: INVALID_NAME");
require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL");
require(owner != address(0), "SHOYU: INVALID_ADDRESS");
nft = _createProxy(
_targets721[_targets721.length - 1],
abi.encodeWithSignature(
"initialize(address,string,string,uint256[],address,uint8)",
owner,
name,
symbol,
tokenIds,
royaltyFeeRecipient,
royaltyFee
)
);
emit DeployNFT721AndMintBatch(nft, owner, name, symbol, tokenIds, royaltyFeeRecipient, royaltyFee);
}
function deployNFT721AndPark(
address owner,
string calldata name,
string calldata symbol,
uint256 toTokenId,
address royaltyFeeRecipient,
uint8 royaltyFee
) external override onlyDeployer returns (address nft) {
require(bytes(name).length > 0, "SHOYU: INVALID_NAME");
require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL");
require(owner != address(0), "SHOYU: INVALID_ADDRESS");
nft = _createProxy(
_targets721[_targets721.length - 1],
abi.encodeWithSignature(
"initialize(address,string,string,uint256,address,uint8)",
owner,
name,
symbol,
toTokenId,
royaltyFeeRecipient,
royaltyFee
)
);
emit DeployNFT721AndPark(nft, owner, name, symbol, toTokenId, royaltyFeeRecipient, royaltyFee);
}
function isNFT721(address query) external view override returns (bool result) {
if (query == address(0)) return false;
for (uint256 i = _targets721.length; i >= 1; i--) {
if (_isProxy(_targets721[i - 1], query)) {
return true;
}
}
return false;
}
function deployNFT1155AndMintBatch(
address owner,
uint256[] memory tokenIds,
uint256[] memory amounts,
address royaltyFeeRecipient,
uint8 royaltyFee
) external override onlyDeployer returns (address nft) {
require(owner != address(0), "SHOYU: INVALID_ADDRESS");
require(tokenIds.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL");
nft = _createProxy(
_targets1155[_targets1155.length - 1],
abi.encodeWithSignature(
"initialize(address,uint256[],uint256[],address,uint8)",
owner,
tokenIds,
amounts,
royaltyFeeRecipient,
royaltyFee
)
);
emit DeployNFT1155AndMintBatch(nft, owner, tokenIds, amounts, royaltyFeeRecipient, royaltyFee);
}
function isNFT1155(address query) external view override returns (bool result) {
if (query == address(0)) return false;
for (uint256 i = _targets1155.length; i >= 1; i--) {
if (_isProxy(_targets1155[i - 1], query)) {
return true;
}
}
return false;
}
function deploySocialToken(
address owner,
string memory name,
string memory symbol,
address dividendToken,
uint256 initialSupply
) external override onlyDeployer returns (address proxy) {
require(bytes(name).length > 0, "SHOYU: INVALID_NAME");
require(bytes(symbol).length > 0, "SHOYU: INVALID_SYMBOL");
require(owner != address(0), "SHOYU: INVALID_ADDRESS");
bytes memory initData =
abi.encodeWithSignature(
"initialize(address,string,string,address,uint256)",
owner,
name,
symbol,
dividendToken,
initialSupply
);
proxy = _createProxy(_targetsSocialToken[_targetsSocialToken.length - 1], initData);
emit DeploySocialToken(proxy, owner, name, symbol, dividendToken, initialSupply);
}
function isSocialToken(address query) external view override returns (bool result) {
if (query == address(0)) return false;
for (uint256 i = _targetsSocialToken.length; i >= 1; i--) {
if (_isProxy(_targetsSocialToken[i - 1], query)) {
return true;
}
}
return false;
}
function parkTokenIds721(
address nft,
uint256 toTokenId,
uint8 v,
bytes32 r,
bytes32 s
) external override {
address owner = IBaseNFT721(nft).owner();
bytes32 hash = keccak256(abi.encode(PARK_TOKEN_IDS_721_TYPEHASH, nft, toTokenId, nonces[owner]++));
Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR());
IBaseNFT721(nft).parkTokenIds(toTokenId);
}
function mintBatch721(
address nft,
address to,
uint256[] calldata tokenIds,
bytes calldata data,
uint8 v,
bytes32 r,
bytes32 s
) external override {
address owner = IBaseNFT721(nft).owner();
bytes32 hash = keccak256(abi.encode(MINT_BATCH_721_TYPEHASH, nft, to, tokenIds, data, nonces[owner]++));
Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR());
IBaseNFT721(nft).mintBatch(to, tokenIds, data);
}
function mintBatch1155(
address nft,
address to,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
bytes calldata data,
uint8 v,
bytes32 r,
bytes32 s
) external override {
address owner = IBaseNFT1155(nft).owner();
bytes32 hash =
keccak256(abi.encode(MINT_BATCH_1155_TYPEHASH, nft, to, tokenIds, amounts, data, nonces[owner]++));
Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR());
IBaseNFT1155(nft).mintBatch(to, tokenIds, amounts, data);
}
function mintSocialToken(
address token,
address to,
uint256 amount,
uint8 v,
bytes32 r,
bytes32 s
) external override {
address owner = ISocialToken(token).owner();
bytes32 hash = keccak256(abi.encode(MINT_SOCIAL_TOKEN_TYPEHASH, token, to, amount, nonces[owner]++));
Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR());
ISocialToken(token).mint(to, amount);
}
}
// 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.5.0;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
import "./IOwnable.sol";
interface IBaseNFT1155 is IERC1155, IERC1155MetadataURI, IOwnable {
event SetURI(uint256 indexed id, string uri);
event SetBaseURI(string uri);
event Burn(uint256 indexed tokenId, uint256 amount, uint256 indexed label, bytes32 data);
function PERMIT_TYPEHASH() external view returns (bytes32);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function factory() external view returns (address);
function nonces(address account) external view returns (uint256);
function initialize(address _owner) external;
function setURI(uint256 id, string memory uri) external;
function setBaseURI(string memory baseURI) external;
function mint(
address to,
uint256 tokenId,
uint256 amount,
bytes calldata data
) external;
function mintBatch(
address to,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
bytes calldata data
) external;
function burn(
uint256 tokenId,
uint256 amount,
uint256 label,
bytes32 data
) external;
function burnBatch(uint256[] calldata tokenIds, uint256[] calldata amounts) external;
function permit(
address owner,
address spender,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./IDividendPayingERC20.sol";
import "./IOwnable.sol";
interface ISocialToken is IDividendPayingERC20, IOwnable {
event Burn(uint256 amount, uint256 indexed label, bytes32 data);
function initialize(
address owner,
string memory name,
string memory symbol,
address dividendToken,
uint256 initialSupply
) external;
function PERMIT_TYPEHASH() external view returns (bytes32);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function factory() external view returns (address);
function nonces(address owner) external view returns (uint256);
function mint(address account, uint256 value) external;
function burn(
uint256 value,
uint256 id,
bytes32 data
) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
// Reference: https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
contract ProxyFactory {
function _createProxy(address target, bytes memory initData) internal returns (address proxy) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
if (initData.length > 0) {
(bool success, ) = proxy.call(initData);
require(success, "SHOYU: CALL_FAILURE");
}
}
function _isProxy(address target, address query) internal view returns (bool result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
mstore(add(clone, 0xa), targetBytes)
mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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
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
pragma solidity =0.8.3;
import "./interfaces/IPaymentSplitterFactory.sol";
import "./base/ProxyFactory.sol";
import "./PaymentSplitter.sol";
contract PaymentSplitterFactory is ProxyFactory, IPaymentSplitterFactory {
address internal _target;
constructor() {
PaymentSplitter target = new PaymentSplitter();
address[] memory payees = new address[](1);
payees[0] = msg.sender;
uint256[] memory shares = new uint256[](1);
shares[0] = 1;
target.initialize("", payees, shares);
_target = address(target);
}
function deployPaymentSplitter(
address owner,
string calldata title,
address[] calldata payees,
uint256[] calldata shares
) external override returns (address splitter) {
splitter = _createProxy(
_target,
abi.encodeWithSignature("initialize(string,address[],uint256[])", title, payees, shares)
);
emit DeployPaymentSplitter(owner, title, payees, shares, splitter);
}
function isPaymentSplitter(address query) external view override returns (bool result) {
return _isProxy(_target, query);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IPaymentSplitterFactory {
event DeployPaymentSplitter(
address indexed owner,
string title,
address[] payees,
uint256[] shares,
address splitter
);
function deployPaymentSplitter(
address owner,
string calldata title,
address[] calldata payees,
uint256[] calldata shares
) external returns (address splitter);
function isPaymentSplitter(address query) external view returns (bool result);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "./interfaces/IPaymentSplitter.sol";
import "./libraries/TokenHelper.sol";
// Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/finance/PaymentSplitter.sol
contract PaymentSplitter is Initializable, IPaymentSplitter {
using TokenHelper for address;
string public override title;
/**
* @dev Getter for the total shares held by payees.
*/
uint256 public override totalShares;
/**
* @dev Getter for the total amount of token already released.
*/
mapping(address => uint256) public override totalReleased;
/**
* @dev Getter for the amount of shares held by an account.
*/
mapping(address => uint256) public override shares;
/**
* @dev Getter for the amount of token already released to a payee.
*/
mapping(address => mapping(address => uint256)) public override released;
/**
* @dev Getter for the address of the payee number `index`.
*/
address[] public override payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
function initialize(
string calldata _title,
address[] calldata _payees,
uint256[] calldata _shares
) external override initializer {
require(_payees.length == _shares.length, "SHOYU: LENGTHS_NOT_EQUAL");
require(_payees.length > 0, "SHOYU: LENGTH_TOO_SHORT");
title = _title;
for (uint256 i = 0; i < _payees.length; i++) {
_addPayee(_payees[i], _shares[i]);
}
}
/**
* @dev Triggers a transfer to `account` of the amount of token they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address token, address account) external virtual override {
require(shares[account] > 0, "SHOYU: FORBIDDEN");
uint256 totalReceived = token.balanceOf(address(this)) + totalReleased[token];
uint256 payment = (totalReceived * shares[account]) / totalShares - released[token][account];
require(payment != 0, "SHOYU: NO_PAYMENT");
released[token][account] += payment;
totalReleased[token] += payment;
token.safeTransfer(account, payment);
emit PaymentReleased(token, account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param _shares The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 _shares) private {
require(account != address(0), "SHOYU: INVALID_ADDRESS");
require(_shares > 0, "SHOYU: INVALID_SHARES");
require(shares[account] == 0, "SHOYU: ALREADY_ADDED");
payees.push(account);
shares[account] = _shares;
totalShares = totalShares + _shares;
emit PayeeAdded(account, _shares);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IPaymentSplitter {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address token, address to, uint256 amount);
function initialize(
string calldata _title,
address[] calldata _payees,
uint256[] calldata _shares
) external;
function title() external view returns (string memory);
function totalShares() external view returns (uint256);
function totalReleased(address account) external view returns (uint256);
function shares(address account) external view returns (uint256);
function released(address token, address account) external view returns (uint256);
function payees(uint256 index) external view returns (address);
function release(address token, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
library TokenHelper {
using SafeERC20 for IERC20;
address public constant ETH = 0x0000000000000000000000000000000000000000;
function balanceOf(address token, address account) internal view returns (uint256) {
if (token == ETH) {
return account.balance;
} else {
return IERC20(token).balanceOf(account);
}
}
function safeTransfer(
address token,
address to,
uint256 amount
) internal {
if (token == ETH) {
(bool success, ) = to.call{value: amount}("");
require(success, "SHOYU: TRANSFER_FAILURE");
} else {
IERC20(token).safeTransfer(to, amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "../interfaces/IERC2981.sol";
contract ERC721RoyaltyMock is ERC721("Mock", "MOCK") {
address public owner;
constructor() {
owner = msg.sender;
}
function safeMint(
address to,
uint256 tokenId,
bytes memory data
) external {
_safeMint(to, tokenId, data);
}
function safeMintBatch0(
address[] calldata to,
uint256[] calldata tokenId,
bytes memory data
) external {
require(to.length == tokenId.length);
for (uint256 i = 0; i < to.length; i++) {
_safeMint(to[i], tokenId[i], data);
}
}
function safeMintBatch1(
address to,
uint256[] calldata tokenId,
bytes memory data
) external {
for (uint256 i = 0; i < tokenId.length; i++) {
_safeMint(to, tokenId[i], data);
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId);
}
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address, uint256) {
uint256 fee = 100;
if (_tokenId < 10) fee = 10;
return (owner, (_salePrice * fee) / 1000);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "./interfaces/INFT1155.sol";
import "./interfaces/IERC2981.sol";
import "./base/BaseNFT1155.sol";
import "./base/BaseExchange.sol";
contract NFT1155V0 is BaseNFT1155, BaseExchange, IERC2981, INFT1155 {
uint8 internal _MAX_ROYALTY_FEE;
address internal _royaltyFeeRecipient;
uint8 internal _royaltyFee; // out of 1000
function initialize(
address _owner,
uint256[] memory tokenIds,
uint256[] memory amounts,
address royaltyFeeRecipient,
uint8 royaltyFee
) external override initializer {
__BaseNFTExchange_init();
initialize(_owner);
_MAX_ROYALTY_FEE = ITokenFactory(_factory).MAX_ROYALTY_FEE();
if (tokenIds.length > 0) {
_mintBatch(_owner, tokenIds, amounts, "");
}
_setRoyaltyFeeRecipient(royaltyFeeRecipient);
_royaltyFee = type(uint8).max;
if (royaltyFee != 0) _setRoyaltyFee(royaltyFee);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC1155Initializable, IERC165)
returns (bool)
{
return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId);
}
function DOMAIN_SEPARATOR() public view override(BaseNFT1155, BaseExchange, INFT1155) returns (bytes32) {
return BaseNFT1155.DOMAIN_SEPARATOR();
}
function factory() public view override(BaseNFT1155, BaseExchange, INFT1155) returns (address) {
return _factory;
}
function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address, uint256) {
uint256 royaltyAmount;
if (_royaltyFee != type(uint8).max) royaltyAmount = (_salePrice * _royaltyFee) / 1000;
return (_royaltyFeeRecipient, royaltyAmount);
}
function _transfer(
address,
address from,
address to,
uint256 tokenId,
uint256 amount
) internal override {
_transfer(from, to, tokenId, amount);
emit TransferSingle(msg.sender, from, to, tokenId, amount);
}
function setRoyaltyFeeRecipient(address royaltyFeeRecipient) public override onlyOwner {
_setRoyaltyFeeRecipient(royaltyFeeRecipient);
}
function setRoyaltyFee(uint8 royaltyFee) public override onlyOwner {
_setRoyaltyFee(royaltyFee);
}
function _setRoyaltyFeeRecipient(address royaltyFeeRecipient) internal {
require(royaltyFeeRecipient != address(0), "SHOYU: INVALID_FEE_RECIPIENT");
_royaltyFeeRecipient = royaltyFeeRecipient;
emit SetRoyaltyFeeRecipient(royaltyFeeRecipient);
}
function _setRoyaltyFee(uint8 royaltyFee) internal {
if (_royaltyFee == type(uint8).max) {
require(royaltyFee <= _MAX_ROYALTY_FEE, "SHOYU: INVALID_FEE");
} else {
require(royaltyFee < _royaltyFee, "SHOYU: INVALID_FEE");
}
_royaltyFee = royaltyFee;
emit SetRoyaltyFee(royaltyFee);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./IBaseNFT1155.sol";
import "./IBaseExchange.sol";
interface INFT1155 is IBaseNFT1155, IBaseExchange {
event SetRoyaltyFeeRecipient(address recipient);
event SetRoyaltyFee(uint8 fee);
function initialize(
address _owner,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
address royaltyFeeRecipient,
uint8 royaltyFee
) external;
function DOMAIN_SEPARATOR() external view override(IBaseNFT1155, IBaseExchange) returns (bytes32);
function factory() external view override(IBaseNFT1155, IBaseExchange) returns (address);
function setRoyaltyFeeRecipient(address _royaltyFeeRecipient) external;
function setRoyaltyFee(uint8 _royaltyFee) external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/utils/Strings.sol";
import "../interfaces/IBaseNFT1155.sol";
import "../interfaces/IERC1271.sol";
import "../interfaces/ITokenFactory.sol";
import "../base/ERC1155Initializable.sol";
import "../base/OwnableInitializable.sol";
import "../libraries/Signature.sol";
abstract contract BaseNFT1155 is ERC1155Initializable, OwnableInitializable, IBaseNFT1155 {
using Strings for uint256;
// keccak256("Permit(address owner,address spender,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH =
0xdaab21af31ece73a508939fedd476a5ee5129a5ed4bb091f3236ffb45394df62;
bytes32 internal _DOMAIN_SEPARATOR;
uint256 internal _CACHED_CHAIN_ID;
uint8 internal MAX_ROYALTY_FEE;
address internal _factory;
string internal _baseURI;
mapping(uint256 => string) internal _uris;
mapping(address => uint256) public override nonces;
function initialize(address _owner) public override initializer {
__ERC1155_init("");
__Ownable_init(_owner);
_factory = msg.sender;
_CACHED_CHAIN_ID = block.chainid;
_DOMAIN_SEPARATOR = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
function DOMAIN_SEPARATOR() public view virtual override returns (bytes32) {
bytes32 domainSeparator;
if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR;
else {
domainSeparator = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
return domainSeparator;
}
function factory() public view virtual override returns (address) {
return _factory;
}
function uri(uint256 id)
public
view
virtual
override(ERC1155Initializable, IERC1155MetadataURI)
returns (string memory)
{
string memory _uri = _uris[id];
if (bytes(_uri).length > 0) {
return _uri;
} else {
string memory baseURI = _baseURI;
if (bytes(baseURI).length > 0) {
return string(abi.encodePacked(baseURI, "{id}.json"));
} else {
baseURI = ITokenFactory(_factory).baseURI1155();
string memory addy = Strings.toHexString(uint160(address(this)), 20);
return string(abi.encodePacked(baseURI, addy, "/{id}.json"));
}
}
}
function setURI(uint256 id, string memory newURI) external override onlyOwner {
_uris[id] = newURI;
emit SetURI(id, newURI);
}
function setBaseURI(string memory baseURI) external override onlyOwner {
_baseURI = baseURI;
emit SetBaseURI(baseURI);
}
function mint(
address to,
uint256 tokenId,
uint256 amount,
bytes memory data
) external override {
require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN");
_mint(to, tokenId, amount, data);
}
function mintBatch(
address to,
uint256[] memory tokenIds,
uint256[] memory amounts,
bytes memory data
) external override {
require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN");
_mintBatch(to, tokenIds, amounts, data);
}
function burn(
uint256 tokenId,
uint256 amount,
uint256 label,
bytes32 data
) external override {
_burn(msg.sender, tokenId, amount);
emit Burn(tokenId, amount, label, data);
}
function burnBatch(uint256[] calldata tokenIds, uint256[] calldata amounts) external override {
_burnBatch(msg.sender, tokenIds, amounts);
}
function permit(
address owner,
address spender,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(block.timestamp <= deadline, "SHOYU: EXPIRED");
require(owner != address(0), "SHOYU: INVALID_ADDRESS");
require(spender != owner, "SHOYU: NOT_NECESSARY");
bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, nonces[owner]++, deadline));
Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR());
_setApprovalForAll(owner, spender, true);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/utils/Address.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 ERC1155Initializable is Initializable, 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}.
*/
function __ERC1155_init(string memory uri_) internal initializer {
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal initializer {
_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), "SHOYU: INVALID_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, "SHOYU: LENGTHS_NOT_EQUAL");
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(msg.sender, 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(to != address(0), "SHOYU: INVALID_ADDRESS");
require(from == msg.sender || isApprovedForAll(from, msg.sender), "SHOYU: FORBIDDEN");
address operator = msg.sender;
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_transfer(from, to, id, amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
function _transfer(
address from,
address to,
uint256 id,
uint256 amount
) internal {
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL");
require(to != address(0), "SHOYU: INVALID_ADDRESS");
require(from == msg.sender || isApprovedForAll(from, msg.sender), "SHOYU: FORBIDDEN");
address operator = msg.sender;
_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, "SHOYU: INSUFFICIENT_BALANCE");
_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;
}
function _setApprovalForAll(
address account,
address operator,
bool approved
) internal {
require(account != operator, "SHOYU: NOT_ALLOWED");
_operatorApprovals[account][operator] = approved;
emit ApprovalForAll(account, operator, approved);
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "SHOYU: INVALID_ADDRESS");
address operator = msg.sender;
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, 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), "SHOYU: INVALID_ADDRESS");
require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL");
address operator = msg.sender;
_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 `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "SHOYU: INVALID_ADDRESS");
address operator = msg.sender;
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE");
_balances[id][account] = accountBalance - amount;
emit TransferSingle(operator, account, 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 account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "SHOYU: INVALID_ADDRESS");
require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL");
address operator = msg.sender;
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "SHOYU: INSUFFICIENT_BALANCE");
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @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(to).onERC1155Received.selector) {
revert("SHOYU: INVALID_RECEIVER");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("SHOYU: NO_RECEIVER");
}
}
}
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(to).onERC1155BatchReceived.selector) {
revert("SHOYU: INVALID_RECEIVER");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("SHOYU: NO_RECEIVER");
}
}
}
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;
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
pragma solidity =0.8.3;
import "@openzeppelin/contracts/utils/Strings.sol";
import "./base/DividendPayingERC20.sol";
import "./base/OwnableInitializable.sol";
import "./interfaces/ISocialToken.sol";
import "./libraries/Signature.sol";
contract SocialTokenV0 is DividendPayingERC20, OwnableInitializable, ISocialToken {
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 internal _DOMAIN_SEPARATOR;
uint256 internal _CACHED_CHAIN_ID;
address internal _factory;
mapping(address => uint256) public override nonces;
function initialize(
address _owner,
string memory _name,
string memory _symbol,
address _dividendToken,
uint256 initialSupply
) external override initializer {
__Ownable_init(_owner);
__DividendPayingERC20_init(_name, _symbol, _dividendToken);
_factory = msg.sender;
_mint(_owner, initialSupply);
_CACHED_CHAIN_ID = block.chainid;
_DOMAIN_SEPARATOR = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
function DOMAIN_SEPARATOR() public view override returns (bytes32) {
bytes32 domainSeparator;
if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR;
else {
domainSeparator = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
return domainSeparator;
}
function factory() public view override returns (address) {
return _factory;
}
function mint(address account, uint256 value) external override {
require(owner() == msg.sender || _factory == msg.sender, "SHOYU: FORBIDDEN");
_mint(account, value);
}
function burn(
uint256 value,
uint256 label,
bytes32 data
) external override {
_burn(msg.sender, value);
emit Burn(value, label, data);
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(block.timestamp <= deadline, "SHOYU: EXPIRED");
require(owner != address(0), "SHOYU: INVALID_ADDRESS");
require(spender != owner, "SHOYU: NOT_NECESSARY");
bytes32 hash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
Signature.verify(hash, owner, v, r, s, DOMAIN_SEPARATOR());
_approve(owner, spender, value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./ERC20Initializable.sol";
import "../libraries/TokenHelper.sol";
import "../interfaces/IDividendPayingERC20.sol";
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether/erc20
/// to token holders as dividends and allows token holders to withdraw their dividends.
/// Reference: https://github.com/Roger-Wu/erc1726-dividend-paying-token/blob/master/contracts/DividendPayingToken.sol
abstract contract DividendPayingERC20 is ERC20Initializable, IDividendPayingERC20 {
using SafeCast for uint256;
using SafeCast for int256;
using TokenHelper for address;
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 public constant override MAGNITUDE = 2**128;
address public override dividendToken;
uint256 public override totalDividend;
uint256 internal magnifiedDividendPerShare;
function __DividendPayingERC20_init(
string memory _name,
string memory _symbol,
address _dividendToken
) internal initializer {
__ERC20_init(_name, _symbol);
dividendToken = _dividendToken;
}
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
/// @dev Syncs dividends whenever ether is paid to this contract.
receive() external payable {
if (msg.value > 0) {
require(dividendToken == TokenHelper.ETH, "SHOYU: UNABLE_TO_RECEIVE_ETH");
sync();
}
}
/// @notice Syncs the amount of ether/erc20 increased to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// @return increased The amount of total dividend increased
/// It emits the `Sync` event if the amount of received ether/erc20 is greater than 0.
/// About undistributed ether/erc20:
/// In each distribution, there is a small amount of ether/erc20 not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether/erc20
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether/erc20 in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether/erc20, so we don't do that.
function sync() public payable override returns (uint256 increased) {
uint256 _totalSupply = totalSupply();
require(_totalSupply > 0, "SHOYU: NO_SUPPLY");
uint256 balance = dividendToken.balanceOf(address(this));
increased = balance - totalDividend;
require(increased > 0, "SHOYU: INSUFFICIENT_AMOUNT");
magnifiedDividendPerShare += (increased * MAGNITUDE) / _totalSupply;
totalDividend = balance;
emit Sync(increased);
}
/// @notice Withdraws the ether/erc20 distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether/erc20 is greater than 0.
function withdrawDividend() public override {
uint256 _withdrawableDividend = withdrawableDividendOf(msg.sender);
if (_withdrawableDividend > 0) {
withdrawnDividends[msg.sender] += _withdrawableDividend;
emit DividendWithdrawn(msg.sender, _withdrawableDividend);
totalDividend -= _withdrawableDividend;
dividendToken.safeTransfer(msg.sender, _withdrawableDividend);
}
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` can withdraw.
function dividendOf(address account) public view override returns (uint256) {
return withdrawableDividendOf(account);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` can withdraw.
function withdrawableDividendOf(address account) public view override returns (uint256) {
return accumulativeDividendOf(account) - withdrawnDividends[account];
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` has withdrawn.
function withdrawnDividendOf(address account) public view override returns (uint256) {
return withdrawnDividends[account];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(account) = withdrawableDividendOf(account) + withdrawnDividendOf(account)
/// = (magnifiedDividendPerShare * balanceOf(account) + magnifiedDividendCorrections[account]) / magnitude
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` has earned in total.
function accumulativeDividendOf(address account) public view override returns (uint256) {
return
((magnifiedDividendPerShare * balanceOf(account)).toInt256() + magnifiedDividendCorrections[account])
.toUint256() / MAGNITUDE;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(
address from,
address to,
uint256 value
) internal override {
super._transfer(from, to, value);
int256 _magCorrection = (magnifiedDividendPerShare * value).toInt256();
magnifiedDividendCorrections[from] += _magCorrection;
magnifiedDividendCorrections[to] -= _magCorrection;
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] -= (magnifiedDividendPerShare * value).toInt256();
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] += (magnifiedDividendPerShare * value).toInt256();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Initializable is Initializable, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_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:
*
* - `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(msg.sender, 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(msg.sender, 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][msg.sender];
require(currentAllowance >= amount, "SHOYU: INSUFFICIENT_ALLOWANCE");
_approve(sender, msg.sender, 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(msg.sender, spender, _allowances[msg.sender][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[msg.sender][spender];
require(currentAllowance >= subtractedValue, "SHOYU: ALLOWANCE_UNDERFLOW");
_approve(msg.sender, 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), "SHOYU: INVALID_SENDER");
require(recipient != address(0), "SHOYU: INVALID_RECIPIENT");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "SHOYU: INSUFFICIENT_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), "SHOYU: INVALID_ACCOUNT");
_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), "SHOYU: INVALID_ACCOUNT");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "SHOYU: INSUFFICIENT_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), "SHOYU: INVALID_OWNER");
require(spender != address(0), "SHOYU: INVALID_SPENDER");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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 {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_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(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
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");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
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");
_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 `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, 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 (uint 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 `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
emit TransferSingle(operator, account, 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 account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @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(to).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(to).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.3;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "../interfaces/IERC2981.sol";
contract ERC1155RoyaltyMock is ERC1155("MOCK") {
address public owner;
constructor() {
owner = msg.sender;
}
function mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) external {
_mint(account, id, amount, data);
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) external {
_mintBatch(to, ids, amounts, data);
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId);
}
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address, uint256) {
uint256 fee = 100;
if (_tokenId < 10) fee = 10;
return (owner, (_salePrice * fee) / 1000);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
contract ERC1155Mock is ERC1155("MOCK") {
function mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) external {
_mint(account, id, amount, data);
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) external {
_mintBatch(to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./base/BaseExchange.sol";
contract ERC1155ExchangeV0 is BaseExchange {
bytes32 internal immutable _DOMAIN_SEPARATOR;
uint256 internal immutable _CACHED_CHAIN_ID;
address internal immutable _factory;
constructor(address factory_) {
__BaseNFTExchange_init();
_factory = factory_;
_CACHED_CHAIN_ID = block.chainid;
_DOMAIN_SEPARATOR = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
function DOMAIN_SEPARATOR() public view override returns (bytes32) {
bytes32 domainSeparator;
if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR;
else {
domainSeparator = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
return domainSeparator;
}
function factory() public view override returns (address) {
return _factory;
}
function canTrade(address nft) public view override returns (bool) {
return !ITokenFactory(_factory).isNFT1155(nft);
}
function _transfer(
address nft,
address from,
address to,
uint256 tokenId,
uint256 amount
) internal override {
IERC1155(nft).safeTransferFrom(from, to, tokenId, amount, "");
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./base/BaseExchange.sol";
contract ERC721ExchangeV0 is BaseExchange {
bytes32 internal immutable _DOMAIN_SEPARATOR;
uint256 internal immutable _CACHED_CHAIN_ID;
address internal immutable _factory;
constructor(address factory_) {
__BaseNFTExchange_init();
_factory = factory_;
_CACHED_CHAIN_ID = block.chainid;
_DOMAIN_SEPARATOR = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
function DOMAIN_SEPARATOR() public view override returns (bytes32) {
bytes32 domainSeparator;
if (_CACHED_CHAIN_ID == block.chainid) domainSeparator = _DOMAIN_SEPARATOR;
else {
domainSeparator = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
}
return domainSeparator;
}
function factory() public view override returns (address) {
return _factory;
}
function canTrade(address nft) public view override returns (bool) {
return !ITokenFactory(_factory).isNFT721(nft);
}
function _transfer(
address nft,
address from,
address to,
uint256 tokenId,
uint256
) internal override {
IERC721(nft).safeTransferFrom(from, to, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract ERC721Mock is ERC721("Mock", "MOCK") {
function safeMint(
address to,
uint256 tokenId,
bytes memory data
) external {
_safeMint(to, tokenId, data);
}
function safeMintBatch0(
address[] calldata to,
uint256[] calldata tokenId,
bytes memory data
) external {
require(to.length == tokenId.length);
for (uint256 i = 0; i < to.length; i++) {
_safeMint(to[i], tokenId[i], data);
}
}
function safeMintBatch1(
address to,
uint256[] calldata tokenId,
bytes memory data
) external {
for (uint256 i = 0; i < tokenId.length; i++) {
_safeMint(to, tokenId[i], data);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract ERC20Mock is ERC20("Mock", "MOCK") {
function mint(address to, uint256 amount) external {
_mint(to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
interface IERC20Snapshot is IERC20, IERC20Metadata {
function balanceOfAt(address account, uint256 snapshotId) external view returns (uint256);
function totalSupplyAt(uint256 snapshotId) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "../interfaces/IStrategy.sol";
contract FixedPriceSale is IStrategy {
function canClaim(
address proxy,
uint256 deadline,
bytes memory params,
address,
uint256 bidPrice,
address,
uint256,
uint256
) external view override returns (bool) {
uint256 price = abi.decode(params, (uint256));
require(price > 0, "SHOYU: INVALID_PRICE");
return (proxy != address(0) || block.timestamp <= deadline) && bidPrice == price;
}
function canBid(
address,
uint256,
bytes memory,
address,
uint256,
address,
uint256,
uint256
) external pure override returns (bool) {
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "../interfaces/IStrategy.sol";
contract EnglishAuction is IStrategy {
function canClaim(
address proxy,
uint256 deadline,
bytes memory params,
address bidder,
uint256 bidPrice,
address bestBidder,
uint256 bestBidPrice,
uint256
) external view override returns (bool) {
if (proxy == address(0)) {
return bidder == bestBidder && bidPrice == bestBidPrice && deadline < block.timestamp;
} else {
uint256 startPrice = abi.decode(params, (uint256));
require(startPrice > 0, "SHOYU: INVALID_START_PRICE");
return bidPrice >= startPrice && deadline < block.timestamp;
}
}
function canBid(
address proxy,
uint256 deadline,
bytes memory params,
address,
uint256 bidPrice,
address,
uint256 bestBidPrice,
uint256
) external view override returns (bool) {
if (proxy == address(0)) {
uint256 startPrice = abi.decode(params, (uint256));
require(startPrice > 0, "SHOYU: INVALID_START_PRICE");
return block.timestamp <= deadline && bidPrice >= startPrice && bidPrice > bestBidPrice;
} else {
return false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.3;
import "../interfaces/IStrategy.sol";
contract DutchAuction is IStrategy {
function canClaim(
address proxy,
uint256 deadline,
bytes memory params,
address,
uint256 bidPrice,
address,
uint256,
uint256
) external view override returns (bool) {
(uint256 startPrice, uint256 endPrice, uint256 startedAt) = abi.decode(params, (uint256, uint256, uint256));
require(startPrice > endPrice, "SHOYU: INVALID_PRICE_RANGE");
require(startedAt < deadline, "SHOYU: INVALID_STARTED_AT");
uint256 tickPerBlock = (startPrice - endPrice) / (deadline - startedAt);
uint256 currentPrice =
block.timestamp >= deadline ? endPrice : startPrice - ((block.timestamp - startedAt) * tickPerBlock);
return (proxy != address(0) || block.timestamp <= deadline) && bidPrice >= currentPrice;
}
function canBid(
address,
uint256,
bytes memory,
address,
uint256,
address,
uint256,
uint256
) external pure override returns (bool) {
return false;
}
}
| xref:ROOT:erc1155.adocbatch-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), "SHOYU: INVALID_ADDRESS");
require(ids.length == amounts.length, "SHOYU: LENGTHS_NOT_EQUAL");
address operator = msg.sender;
_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);
}
| 96,802 |
pragma solidity ^0.4.14;
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function transfer(address to, uint tokens) public returns (bool success);
}
// ----------------------------------------------------------------------------
// Four Leaf clover (FLC) Token interface
// ----------------------------------------------------------------------------
contract FLC {
function create(uint units) public;
}
// ----------------------------------------------------------------------------
// contract WhiteListAccess
// ----------------------------------------------------------------------------
contract WhiteListAccess {
function WhiteListAccess() public {
owner = msg.sender;
whitelist[owner] = true;
whitelist[address(this)] = true;
}
address public owner;
mapping (address => bool) whitelist;
modifier onlyBy(address who) { require(msg.sender == who); _; }
modifier onlyOwner {require(msg.sender == owner); _;}
modifier onlyWhitelisted {require(whitelist[msg.sender]); _;}
function addToWhiteList(address trusted) public onlyOwner() {
whitelist[trusted] = true;
}
function removeFromWhiteList(address untrusted) public onlyOwner() {
whitelist[untrusted] = false;
}
}
// ----------------------------------------------------------------------------
// NRB_Common contract
// ----------------------------------------------------------------------------
contract NRB_Common is WhiteListAccess {
string public name; // contract's name
bool _init;
function NRB_Common() public { ETH_address = 0x1; }
// Deployment
address public ETH_address; // representation of Ether as Token (0x1)
address public FLC_address;
address public NRB_address;
function init(address _main, address _flc) public {
require(!_init);
FLC_address = _flc;
NRB_address = _main;
whitelist[NRB_address] = true;
_init = true;
}
// Debug
event Debug(string, bool);
event Debug(string, uint);
event Debug(string, uint, uint);
event Debug(string, uint, uint, uint);
event Debug(string, uint, uint, uint, uint);
event Debug(string, address);
event Debug(string, address, address);
event Debug(string, address, address, address);
}
// ----------------------------------------------------------------------------
// NRB_Tokens (main) contract
// ----------------------------------------------------------------------------
contract NRB_Tokens is NRB_Common {
// how much raised for each token
mapping(address => uint) raisedAmount;
mapping(address => Token) public tokens;
mapping(uint => address) public tokenlist;
uint public tokenlenth;
struct Token {
bool registered;
bool validated;
uint index;
uint decimals;
uint nextRecord;
string name;
string symbol;
address addrs;
}
function NRB_Tokens() public {
name = "NRB_Tokens";
tokenlenth = 1;
registerAndValidateToken(ETH_address, "Ethereum", "ETH", 18, 7812500000000000);
}
function getTokenListLength() constant public returns (uint) {
return tokenlenth-1;
}
function getTokenByIndex(uint _index) constant public returns (bool, uint, uint, uint, string, string, address) {
return getTokenByAddress(tokenlist[_index]);
}
function getTokenByAddress(address _token) constant public returns (bool, uint, uint, uint, string, string, address) {
Token memory _t = tokens[_token];
return (_t.validated, _t.index, _t.decimals, _t.nextRecord, _t.name, _t.symbol, _t.addrs);
}
function getTokenAddressByIndex(uint _index) constant public returns (address) {
return tokens[tokenlist[_index]].addrs;
}
function isTokenRegistered(address _token) constant public returns (bool) {
return tokens[_token].registered;
}
function registerTokenPayment(address _token, uint _value) public onlyWhitelisted() {
raisedAmount[_token] = raisedAmount[_token] + _value;
}
function registerAndValidateToken(address _token, string _name, string _symbol, uint _decimals, uint _nextRecord) public onlyOwner() {
registerToken(_token, _name, _symbol, _decimals, _nextRecord);
tokens[_token].validated = true;
}
function registerToken(address _token, string _name, string _symbol, uint _decimals, uint _nextRecord) public onlyWhitelisted() {
require(!tokens[_token].validated);
if (_token != ETH_address) {
require(ERC20Interface(_token).totalSupply() > 0);
require(ERC20Interface(_token).balanceOf(address(this)) == 0);
}
tokens[_token].validated = false;
tokens[_token].registered = true;
tokens[_token].addrs = _token;
tokens[_token].name = _name;
tokens[_token].symbol = _symbol;
tokens[_token].decimals = _decimals;
tokens[_token].index = tokenlenth;
tokens[_token].nextRecord = _nextRecord;
tokenlist[tokenlenth] = _token;
tokenlenth++;
}
function validateToken(address _token, bool _valid) public onlyOwner() {
tokens[_token].validated = _valid;
}
function sendFLC(address user, address token, uint totalpaid) public onlyWhitelisted() returns (uint) {
uint flc = 0;
uint next = 0;
(flc, next) = calculateFLCCore(token, totalpaid);
if (flc > 0) {
tokens[token].nextRecord = next;
FLC(FLC_address).create(flc);
ERC20Interface(FLC_address).transfer(user, flc);
}
return flc;
}
function calculateFLC(address token, uint totalpaid) constant public returns (uint) {
uint flc = 0;
uint next = 0;
(flc, next) = calculateFLCCore(token, totalpaid);
return flc;
}
function calculateFLCCore(address token, uint totalpaid) constant public returns (uint, uint) {
uint next = tokens[token].nextRecord;
uint flc = 0;
while (next <= totalpaid) {
next = next * 2;
flc++;
}
return (flc, next);
}
// recover tokens sent accidentally
function _withdrawal(address _token) public {
uint _balance = ERC20Interface(_token).balanceOf(address(this));
if (_balance > 0) {
ERC20Interface(_token).transfer(owner, _balance);
}
}
// Don't accept ETH
function () public payable {
revert();
}
} | recover tokens sent accidentally | function _withdrawal(address _token) public {
uint _balance = ERC20Interface(_token).balanceOf(address(this));
if (_balance > 0) {
ERC20Interface(_token).transfer(owner, _balance);
}
}
| 1,326,807 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.6;
/**
* @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 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);
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @dev 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);
}
}
}
}
/**
* @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"
);
}
}
}
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(
initializing || isConstructor() || !initialized,
"Contract instance has already been initialized"
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
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;
}
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: YAMRewards.sol
*
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
* 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
*/
abstract contract IRewardDistributionRecipient {
address public rewardDistribution;
function notifyRewardAmount(uint256 reward) internal virtual;
modifier onlyRewardDistribution() {
require(
msg.sender == rewardDistribution,
"Caller is not reward distribution"
);
_;
}
function setRewardDistribution(address _rewardDistribution) external {
rewardDistribution = _rewardDistribution;
}
}
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public y;
function setStakeToken(address _y) internal {
y = IERC20(_y);
}
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public virtual {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
y.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public virtual {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
y.safeTransfer(msg.sender, amount);
}
}
contract StakingPool is
Initializable,
LPTokenWrapper,
IRewardDistributionRecipient
{
using Address for address;
string public poolName;
IERC20 public rewardToken;
address public orchestrator;
uint256 public duration;
bool public manualStartPool;
uint256 public initReward;
uint256 public maxReward;
bool public poolStarted;
uint256 public startTime;
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public rewardDistributed;
address constant uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event ManualPoolStarted(uint256 startedAt);
modifier checkHalve() {
if (block.timestamp >= periodFinish) {
initReward = initReward.mul(50).div(100);
rewardRate = initReward.div(duration);
periodFinish = block.timestamp.add(duration);
emit RewardAdded(initReward);
}
_;
}
modifier checkStart() {
if (manualStartPool) {
require(poolStarted, "Orchestrator hasn't started pool");
} else {
require(
block.timestamp > startTime,
"Can't use pool before start time"
);
}
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
// https://uniswap.org/docs/v2/smart-contract-integration/getting-pair-addresses/
function genUniAddr(address left, address right)
internal
pure
returns (address)
{
address first = left < right ? left : right;
address second = left < right ? right : left;
address pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
uniFactory,
keccak256(abi.encodePacked(first, second)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f"
)
)
)
);
return pair;
}
function initialize(
string memory poolName_,
address rewardToken_,
address pairToken_,
bool isUniPair,
address orchestrator_,
uint256 duration_,
bool manualStartPool_,
uint256 oracleStartTimeOffset
) public initializer {
poolName = poolName_;
if (isUniPair) {
setStakeToken(genUniAddr(rewardToken_, pairToken_));
} else {
setStakeToken(pairToken_);
}
rewardToken = IERC20(rewardToken_);
orchestrator = orchestrator_;
maxReward = rewardToken.balanceOf(address(this));
duration = duration_;
manualStartPool = manualStartPool_;
if (!manualStartPool) {
startTime = block.timestamp + oracleStartTimeOffset;
notifyRewardAmount(maxReward.mul(50).div(100));
}
}
function startPool() external {
require(msg.sender == address(orchestrator));
require(!poolStarted, "Pool can only be started once");
poolStarted = true;
startTime = block.timestamp + 1;
notifyRewardAmount(maxReward.mul(50).div(100));
emit ManualPoolStarted(startTime);
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(10**18)
.div(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(10**18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount)
public
override
updateReward(msg.sender)
checkHalve
checkStart
{
require(
!address(msg.sender).isContract(),
"Caller must not be a contract"
);
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount)
public
override
updateReward(msg.sender)
checkHalve
checkStart
{
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) checkHalve checkStart {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
rewardToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
rewardDistributed = rewardDistributed.add(reward);
}
}
function notifyRewardAmount(uint256 reward)
internal
override
updateReward(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(duration);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(duration);
}
initReward = reward;
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(duration);
emit RewardAdded(reward);
}
}
| https:uniswap.org/docs/v2/smart-contract-integration/getting-pair-addresses/ | function genUniAddr(address left, address right)
internal
pure
returns (address)
{
address first = left < right ? left : right;
address second = left < right ? right : left;
address pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
uniFactory,
keccak256(abi.encodePacked(first, second)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f"
)
)
)
);
return pair;
}
| 1,772,206 |
./full_match/1/0xfB2Bfc368a7edfD51aa2cbEC513ad50edEa74E84/sources/contracts/cctp/libs/Request.sol | Decodes the base request from a bytes array. Will revert if the request is not properly formatted. baseRequest Formatted base request return originDomain Domain of the origin chain return nonce Nonce of the CCTP message on origin domain return originBurnToken Circle token that was burned on origin domain return amount Amount of tokens to burn return recipient Recipient of the tokens on destination domain | function decodeBaseRequest(bytes memory baseRequest)
internal
pure
returns (
uint32 originDomain,
uint64 nonce,
address originBurnToken,
uint256 amount,
address recipient
)
{
if (baseRequest.length != REQUEST_BASE_LENGTH) revert IncorrectRequestLength();
return abi.decode(baseRequest, (uint32, uint64, address, uint256, address));
}
| 5,006,510 |
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol";
import "../common/hotpotinterface.sol";
import "../common/ILoan.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 "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
contract Reward is Ownable, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address public devAddress;
IHotPot public hotpot;
IERC721Enumerable public erc721;
IERC20 public erc20;
ILoan public loan;
event WithdrawReward(address _user, uint256 _tokenId, uint256 _amount);
event Rescue(address indexed dst, uint256 sad);
event RescueToken(address indexed dst, address indexed token, uint256 sad);
//weight,percent
uint256 public weightGrade1 = 100;
uint256 public weightGrade2 = 120;
uint256 public weightGrade3 = 150;
//can withdraw total reward daily, percent
uint256 public availableRewardRatio = 20;
uint256 public devRewardRatio = 7;
modifier checkAllAddress() {
require(hotpot != IHotPot(0), "Contract NFT is not initialized!");
require(
erc721 != IERC721Enumerable(0),
"Contract HotPot is not initialized!"
);
require(erc20 != IERC20(0), "Contract is not initialized!");
_;
}
modifier validNFToken(uint256 _tokenId) {
require(
erc721.ownerOf(_tokenId) != address(0),
"It is not a NFT token!"
);
_;
}
constructor(
address _dev,
address _nft,
address _hotpot
) public {
require(_dev != address(0));
require(_nft != address(0));
require(_hotpot != address(0));
require(_nft.isContract(), "It's not contract address!");
require(_hotpot.isContract(), "It's not contract address!");
devAddress = _dev;
hotpot = IHotPot(_nft);
erc721 = IERC721Enumerable(_nft);
erc20 = IERC20(_hotpot);
}
function setDevRatio(uint8 _ratio) external onlyOwner {
require(_ratio < 10, "Dev ratio can not be greater than 10%");
devRewardRatio = _ratio;
}
function setDevAddress(address _dev) external onlyOwner {
require(_dev != address(0));
devAddress = _dev;
}
function getBalance() external view returns (uint256) {
return erc20.balanceOf(address(this));
}
function setHotPotTicket(address _addr) external onlyOwner {
require(_addr.isContract(), "It's not contract address!");
hotpot = IHotPot(_addr);
erc721 = IERC721Enumerable(_addr);
}
function setHotPot(address _addr) external onlyOwner {
require(_addr.isContract(), "It's not contract address!");
erc20 = IERC20(_addr);
}
function setLoan(address _addr) external onlyOwner {
require(_addr.isContract(), "It's not contract address!");
loan = ILoan(_addr);
}
function calNormalReward(uint256 _tokenId) external view returns (uint256) {
if (erc721.totalSupply() == 0) {
return 0;
}
//3.calculate the Reward
uint256 grade1 = hotpot.getGradeCount(1);
uint256 grade2 = hotpot.getGradeCount(2);
uint256 grade3 = hotpot.getGradeCount(3);
uint8 grade = hotpot.getGrade(_tokenId);
uint256 totalWeight = grade1 *
weightGrade1 +
grade2 *
weightGrade2 +
grade3 *
weightGrade3;
uint256 weight = weightGrade1;
if (grade == 1) {
weight = weightGrade1;
} else if (grade == 2) {
weight = weightGrade2;
} else if (grade == 3) {
weight = weightGrade3;
}
uint256 totalReward = erc20.balanceOf(address(this));
uint256 available = totalReward.mul(availableRewardRatio).div(100);
uint256 ratio = weight.mul(100000).div(totalWeight);
if (ratio > 20000) {
ratio = 20000;
}
uint256 reward = available.mul(ratio).div(100000);
return reward;
}
function calReward(uint256 _tokenId)
external
view
checkAllAddress
validNFToken(_tokenId)
returns (uint256)
{
//1.check the NFT is used?
uint256 time = hotpot.getUseTime(_tokenId);
if (time + 86400 > now) {
return 0;
}
return this.calNormalReward(_tokenId);
}
// event WithdrawReward(address _user,uint256 _tokenId, uint256 _amount);
function getReward(uint256 _tokenId)
external
checkAllAddress
validNFToken(_tokenId)
nonReentrant
whenNotPaused
{
//1.check the NFT is used?
uint256 time = hotpot.getUseTime(_tokenId);
require(time + 86400 < now, "This ticket is used within 24 hours!");
require(this.getBalance() > 0, "The reward pool is empty!");
//2. check ownership
require(
loan.checkPrivilege(msg.sender, _tokenId, now),
"You do not have right to use this token!"
);
uint256 reward = this.calReward(_tokenId);
uint256 devReward = reward.mul(devRewardRatio).div(100);
uint256 userReward = reward.sub(devReward);
//2.set use
hotpot.setUse(_tokenId);
erc20.safeTransfer(devAddress, devReward);
//send to user and dev
erc20.safeTransfer(msg.sender, userReward);
emit WithdrawReward(msg.sender, _tokenId, reward);
}
function rescue(address payable to_, uint256 amount_) external onlyOwner {
require(to_ != address(0), "must not 0");
require(amount_ > 0, "must gt 0");
to_.transfer(amount_);
emit Rescue(to_, amount_);
}
function rescue(
address to_,
IERC20 token_,
uint256 amount_
) external onlyOwner {
require(to_ != address(0), "must not 0");
require(amount_ > 0, "must gt 0");
token_.transfer(to_, amount_);
emit RescueToken(to_, address(token_), amount_);
}
function pause() external onlyOwner{
_pause();
}
function unpause() external onlyOwner{
_unpause();
}
}
| 1.check the NFT is used? | function calReward(uint256 _tokenId)
external
view
checkAllAddress
validNFToken(_tokenId)
returns (uint256)
{
uint256 time = hotpot.getUseTime(_tokenId);
if (time + 86400 > now) {
return 0;
}
return this.calNormalReward(_tokenId);
}
| 5,351,100 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
/**
* @title AirSwap Staking: Stake and Unstake Tokens
* @notice https://www.airswap.io/
*/
contract Staking is Ownable {
using SafeERC20 for ERC20;
using SafeMath for uint256;
struct Stake {
uint256 duration;
uint256 cliff;
uint256 initial;
uint256 balance;
uint256 timestamp;
}
// Token to be staked
ERC20 public immutable token;
// Vesting duration and cliff
uint256 public duration;
uint256 public cliff;
// Mapping of account to stakes
mapping(address => Stake[]) public allStakes;
// ERC-20 token properties
string public name;
string public symbol;
// ERC-20 Transfer event
event Transfer(address indexed from, address indexed to, uint256 tokens);
/**
* @notice Constructor
* @param _token address
* @param _name string
* @param _symbol string
* @param _duration uint256
* @param _cliff uint256
*/
constructor(
ERC20 _token,
string memory _name,
string memory _symbol,
uint256 _duration,
uint256 _cliff
) {
token = _token;
name = _name;
symbol = _symbol;
duration = _duration;
cliff = _cliff;
}
/**
* @notice Set vesting config
* @param _duration uint256
* @param _cliff uint256
*/
function setVesting(uint256 _duration, uint256 _cliff) external onlyOwner {
duration = _duration;
cliff = _cliff;
}
/**
* @notice Set metadata config
* @param _name string
* @param _symbol string
*/
function setMetaData(string memory _name, string memory _symbol)
external
onlyOwner
{
name = _name;
symbol = _symbol;
}
/**
* @notice Stake tokens
* @param amount uint256
*/
function stake(uint256 amount) external {
stakeFor(msg.sender, amount);
}
/**
* @notice Extend a stake
* @param amount uint256
*/
function extend(uint256 index, uint256 amount) external {
extendFor(index, msg.sender, amount);
}
/**
* @notice Unstake multiple
* @param amounts uint256[]
*/
function unstake(uint256[] calldata amounts) external {
uint256 totalAmount = 0;
uint256 length = amounts.length;
while (length > 0) {
length = length - 1;
if (amounts[length] > 0) {
_unstake(length, amounts[length]);
totalAmount += amounts[length];
}
}
if (totalAmount > 0) {
token.transfer(msg.sender, totalAmount);
emit Transfer(msg.sender, address(0), totalAmount);
}
}
/**
* @notice All stakes for an account
* @param account uint256
*/
function getStakes(address account)
external
view
returns (Stake[] memory stakes)
{
uint256 length = allStakes[account].length;
stakes = new Stake[](length);
while (length > 0) {
length = length - 1;
stakes[length] = allStakes[account][length];
}
return stakes;
}
/**
* @notice Total balance of all accounts (ERC-20)
*/
function totalSupply() external view returns (uint256) {
return token.balanceOf(address(this));
}
/**
* @notice Balance of an account (ERC-20)
*/
function balanceOf(address account) external view returns (uint256 total) {
Stake[] memory stakes = allStakes[account];
uint256 length = stakes.length;
while (length > 0) {
length = length - 1;
total = total.add(stakes[length].balance);
}
return total;
}
/**
* @notice Decimals of underlying token (ERC-20)
*/
function decimals() external view returns (uint8) {
return token.decimals();
}
/**
* @notice Stake tokens for an account
* @param account address
* @param amount uint256
*/
function stakeFor(address account, uint256 amount) public {
require(amount > 0, "AMOUNT_INVALID");
allStakes[account].push(
Stake(duration, cliff, amount, amount, block.timestamp)
);
token.safeTransferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), account, amount);
}
/**
* @notice Extend a stake for an account
* @param index uint256
* @param account address
* @param amount uint256
*/
function extendFor(
uint256 index,
address account,
uint256 amount
) public {
require(amount > 0, "AMOUNT_INVALID");
Stake storage selected = allStakes[account][index];
// If selected stake is fully vested create a new stake
if (vested(account, index) == selected.initial) {
stakeFor(account, amount);
} else {
uint256 newInitial = selected.initial.add(amount);
uint256 newBalance = selected.balance.add(amount);
// Calculate a new timestamp proportional to the new amount
// New timestamp limited to current timestamp (amount / newInitial approaches 1)
uint256 newTimestamp = selected.timestamp +
amount.mul(block.timestamp.sub(selected.timestamp)).div(newInitial);
allStakes[account][index] = Stake(
duration,
cliff,
newInitial,
newBalance,
newTimestamp
);
token.safeTransferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), account, amount);
}
}
/**
* @notice Vested amount for an account
* @param account uint256
* @param index uint256
*/
function vested(address account, uint256 index)
public
view
returns (uint256)
{
Stake storage stakeData = allStakes[account][index];
if (block.timestamp.sub(stakeData.timestamp) > duration) {
return stakeData.initial;
}
return
stakeData.initial.mul(block.timestamp.sub(stakeData.timestamp)).div(
stakeData.duration
);
}
/**
* @notice Available amount for an account
* @param account uint256
* @param index uint256
*/
function available(address account, uint256 index)
public
view
returns (uint256)
{
Stake memory selected = allStakes[account][index];
if (block.timestamp.sub(selected.timestamp) < selected.cliff) {
return 0;
}
return vested(account, index) - (selected.initial - selected.balance);
}
/**
* @notice Unstake tokens
* @param index uint256
* @param amount uint256
*/
function _unstake(uint256 index, uint256 amount) internal {
require(index < allStakes[msg.sender].length, "INDEX_OUT_OF_RANGE");
Stake storage selected = allStakes[msg.sender][index];
require(
block.timestamp.sub(selected.timestamp) >= selected.cliff,
"CLIFF_NOT_REACHED"
);
require(amount <= available(msg.sender, index), "AMOUNT_EXCEEDS_AVAILABLE");
selected.balance = selected.balance.sub(amount);
if (selected.balance == 0) {
Stake[] memory stakes = allStakes[msg.sender];
allStakes[msg.sender][index] = stakes[stakes.length.sub(1)];
allStakes[msg.sender].pop();
}
}
}
| Unstake tokens index uint256 amount uint256/ | function _unstake(uint256 index, uint256 amount) internal {
require(index < allStakes[msg.sender].length, "INDEX_OUT_OF_RANGE");
Stake storage selected = allStakes[msg.sender][index];
require(
block.timestamp.sub(selected.timestamp) >= selected.cliff,
"CLIFF_NOT_REACHED"
);
require(amount <= available(msg.sender, index), "AMOUNT_EXCEEDS_AVAILABLE");
selected.balance = selected.balance.sub(amount);
if (selected.balance == 0) {
Stake[] memory stakes = allStakes[msg.sender];
allStakes[msg.sender][index] = stakes[stakes.length.sub(1)];
allStakes[msg.sender].pop();
}
}
| 2,549,078 |
pragma solidity ^0.4.23;
import "./EthStoreSample.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/** @title The EthStore administrator-related functions */
contract EthStoreAdministrator is EthStoreSample {
using SafeMath for uint256;
/** @dev Create a new store.
* @param _storeOwner The address of the store owner.
*/
function createStore(address _storeOwner) public onlyOwner {
require(storeOwnerToStoreId[_storeOwner] == 0);
// create a store for the store owner
uint256 storeId = storeCount.add(1);
storeCount = stores.push(Store(storeId, _storeOwner, true, "", "", "", 0));
storeOwnerToStoreId[_storeOwner] = storeId;
emit NewStore(storeId, _storeOwner);
}
/** @dev Enable / disable a store.
* @param _storeId The id of the store.
* @param _enabled The flag of enabled.
*/
function enableStore(uint256 _storeId, bool _enabled) public onlyOwner {
require(_storeId > 0 && _storeId <= storeCount);
Store storage store = stores[_storeId.sub(1)];
store.enabled = _enabled;
}
/** @dev Enable / disable a product.
* @param _productId The id of the product.
* @param _enabled The flag of enabled.
*/
function enableProduct(uint256 _productId, bool _enabled) public onlyOwner {
require(_productId > 0 && _productId <= productCount);
Product storage product = products[_productId.sub(1)];
product.enabled = _enabled;
}
} | Enable / disable a store. _storeId The id of the store. _enabled The flag of enabled./ | function enableStore(uint256 _storeId, bool _enabled) public onlyOwner {
require(_storeId > 0 && _storeId <= storeCount);
Store storage store = stores[_storeId.sub(1)];
store.enabled = _enabled;
}
| 5,386,661 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _owner;
}
/**
* Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/ReethMonetaryPolicyV2.sol
pragma solidity =0.6.6;
// This monetary policy controls the rebase mechanism in the reeth token
// Rebase can only be called once a day by a non-contract
// To incentivize rebase, the policy will mint reeth to the delegatecaller equal to up to the fast gas price (determined by Chainlink)
// There is an absolute max price however
interface PriceOracle {
function getLatestREETHPrice() external view returns (uint256);
function updateREETHPrice() external; // Update price oracle upon every token transfer
function mainLiquidity() external view returns (address); // Returns address of REETH/ETH LP pair
}
interface AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
interface UniswapLikeLPToken {
function sync() external; // Call sync right after rebase call
}
interface ReethToken {
function mint(address, uint256) external returns (bool);
function isRebaseable() external view returns (bool);
function reethScalingFactor() external view returns (uint256);
function maxScalingFactor() external view returns (uint256);
function rebase(uint256 _price, uint256 _indexDelta, bool _positive) external returns (uint256); // Epoch is stored in the token
}
contract ReethMonetaryPolicyV2 is Ownable, ReentrancyGuard {
// Adopted from YamRebaserV2
using SafeMath for uint256;
/// @notice an event emitted when deviationThreshold is changed
event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold);
/// @notice Spreads out getting to the target price
uint256 public rebaseLag;
/// @notice Peg target
uint256 public targetRate;
// 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.
uint256 public deviationThreshold;
/// @notice More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec;
/// @notice Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
/// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec;
/// @notice The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec;
/// @notice The number of rebase cycles since inception
uint256 public epoch;
/// @notice Reeth token address
address public reethAddress;
// price oracle address
address public reethPriceOracle;
/// @notice list of uniswap like pairs to sync
address[] public uniSyncPairs;
// Used for division scaling math
uint256 constant BASE = 1e18;
address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle
// Gas price maximum
uint256 public maxGasPrice = 200000000000; // 200 Gwei
uint256 public callerBonus = 5000; // Rebase caller gets a initial bonus of 5%
event RebaseMint(uint256 _gasCost, uint256 _reethMinted, address _receiver);
constructor(
address _reethAddress,
address _priceOracle
)
public
{
reethAddress = _reethAddress;
reethPriceOracle = _priceOracle;
minRebaseTimeIntervalSec = 1 days;
rebaseWindowOffsetSec = 12 hours; // 12:00 UTC rebase
// 1 REETH = 1 ETH
targetRate = BASE;
// once daily rebase, with targeting reaching peg in 10 days
rebaseLag = 10;
// 5%
deviationThreshold = 5 * 10**16;
// 60 minutes
rebaseWindowLengthSec = 1 hours;
}
// This is an optional function that is ran anytime a reeth transfer is made
function reethTransferActions() external {
require(_msgSender() == reethAddress, "Not sent from REETH token");
// We are running the price oracle update
if(reethPriceOracle != address(0)){
PriceOracle oracle = PriceOracle(reethPriceOracle);
oracle.updateREETHPrice(); // Update the price of reeth
}
}
// Rebase function
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is 1e18
*/
// Users can give their gas spent to another user if they choose to (in case of bot calls)
function rebase(address _delegateCaller)
public
{
// Users will be recognized for 1.5x the eth they spend when using this oracle
uint256 gasUsed = gasleft(); // Start calculate gas spent
// EOA only or gov
require(_msgSender() == tx.origin || _msgSender() == governance(), "Contract call not allowed unless governance");
// ensure rebasing at correct time
require(inRebaseWindow() == true, "Not in rebase window");
// This comparison also ensures there is no reentrancy.
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "Call already executed for this epoch");
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = now.sub(
now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec);
PriceOracle oracle = PriceOracle(reethPriceOracle);
oracle.updateREETHPrice(); // Update the price of reeth
uint256 exchangeRate = oracle.getLatestREETHPrice();
require(exchangeRate > 0, "Bad oracle price");
// calculates % change to supply
(uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate);
uint256 indexDelta = offPegPerc;
// Apply the Dampening factor.
indexDelta = indexDelta.div(rebaseLag);
ReethToken reeth = ReethToken(reethAddress);
if (positive) {
require(reeth.reethScalingFactor().mul(BASE.add(indexDelta)).div(BASE) < reeth.maxScalingFactor(), "new scaling factor will be too big");
}
// rebase the token
reeth.rebase(exchangeRate, indexDelta, positive);
// sync the pools
{
// first sync the main pool
address mainLP = oracle.mainLiquidity();
UniswapLikeLPToken lp = UniswapLikeLPToken(mainLP);
lp.sync(); // Sync this pool post rebase
// And any additional pairs to sync
for(uint256 i = 0; i < uniSyncPairs.length; i++){
lp = UniswapLikeLPToken(uniSyncPairs[i]);
lp.sync();
}
}
// Determine what gas price to use when minting reeth
// We do this instead of updating the spent ETH oracle to incentivize calling rebase
uint256 gasPrice = tx.gasprice;
{
uint256 fastPrice = getFastGasPrice();
if(gasPrice > fastPrice){
gasPrice = fastPrice;
}
if(gasPrice > maxGasPrice){
gasPrice = maxGasPrice;
}
}
if(_delegateCaller == address(0)){
_delegateCaller = _msgSender();
}
gasUsed = gasUsed.sub(gasleft()).mul(gasPrice).mul(100000 + callerBonus).div(100000); // The amount of ETH reimbursed for this transaction with bonus
// Convert ETH units to REETH units and mint to delegated caller
uint256 reethReturn = gasUsed.mul(10**uint256(IERC20(reethAddress).decimals())).div(1e18);
reethReturn = reethReturn.mul(1e18).div(exchangeRate);
if(reethReturn > 0){
reeth.mint(_delegateCaller, reethReturn);
emit RebaseMint(gasUsed, reethReturn, _delegateCaller);
}
}
/**
* @return If the latest block timestamp is within the rebase time window it, returns true.
* Otherwise, returns false.
*/
function inRebaseWindow() public view returns (bool) {
// First check if reeth token is active for rebasing
if(ReethToken(reethAddress).isRebaseable() == false){return false;}
return (block.timestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
block.timestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)));
}
/**
* @return Computes in % how far off market is from peg
*/
function computeOffPegPerc(uint256 rate)
private
view
returns (uint256, bool)
{
if (withinDeviationThreshold(rate)) {
return (0, false);
}
// indexDelta = (rate - targetRate) / targetRate
if (rate > targetRate) {
return (rate.sub(targetRate).mul(BASE).div(targetRate), true);
} else {
return (targetRate.sub(rate).mul(BASE).div(targetRate), false);
}
}
/**
* @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)
private
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
.div(10 ** 18);
return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
|| (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
function getFastGasPrice() public view returns (uint256) {
AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS);
( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer
return uint256(intGasPrice);
}
// Governance only functions
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
uint256[3] private _timelock_data;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Add to the synced pairs
// --------------------
function startAddSyncPair(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishAddSyncPair() external onlyGovernance timelockConditionsMet(2) {
uniSyncPairs.push(_timelock_address);
}
// --------------------
// Remove from synced pairs
// --------------------
function startRemoveSyncPair(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishRemoveSyncPair() external onlyGovernance timelockConditionsMet(3) {
uint256 length = uniSyncPairs.length;
for(uint256 i = 0; i < length; i++){
if(uniSyncPairs[i] == _timelock_address){
for(uint256 i2 = i; i2 < length-1; i2++){
uniSyncPairs[i2] =uniSyncPairs[i2 + 1]; // Shift the data down one
}
uniSyncPairs.pop(); //Remove last element
break;
}
}
}
// --------------------
// Change the deviation threshold
// --------------------
function startChangeDeviationThreshold(uint256 _threshold) external onlyGovernance {
require(_threshold > 0);
_timelockStart = now;
_timelockType = 4;
_timelock_data[0] = _threshold;
}
function finishChangeDeviationThreshold() external onlyGovernance timelockConditionsMet(4) {
deviationThreshold = _timelock_data[0];
}
// --------------------
// Change the rebase lag
// --------------------
function startChangeRebaseLag(uint256 _lag) external onlyGovernance {
require(_lag > 1);
_timelockStart = now;
_timelockType = 5;
_timelock_data[0] = _lag;
}
function finishChangeRebaseLag() external onlyGovernance timelockConditionsMet(5) {
rebaseLag = _timelock_data[0];
}
// --------------------
// Change the target rate
// --------------------
function startChangeTargetRate(uint256 _rate) external onlyGovernance {
require(_rate > 0);
_timelockStart = now;
_timelockType = 6;
_timelock_data[0] = _rate;
}
function finishChangeTargetRate() external onlyGovernance timelockConditionsMet(6) {
targetRate = _timelock_data[0];
}
// --------------------
// Change the rebase times
// --------------------
function startChangeRebaseTimes(uint256 _UTCOffset, uint256 _windowLength, uint256 _frequency) external onlyGovernance {
require(_frequency > 0);
require(_UTCOffset < _frequency);
require(_UTCOffset + _windowLength < _frequency);
_timelockStart = now;
_timelockType = 7;
_timelock_data[0] = _UTCOffset;
_timelock_data[1] = _windowLength;
_timelock_data[2] = _frequency;
}
function finishChangeRebaseTimes() external onlyGovernance timelockConditionsMet(7) {
rebaseWindowOffsetSec = _timelock_data[0];
rebaseWindowLengthSec = _timelock_data[1];
minRebaseTimeIntervalSec = _timelock_data[2];
}
// --------------------
// Change the max gas allowed
// --------------------
function startChangeMaxGasPrice(uint256 _gas) external onlyGovernance {
_timelockStart = now;
_timelockType = 8;
_timelock_data[0] = _gas;
}
function finishChangeMaxGasPrice() external onlyGovernance timelockConditionsMet(8) {
maxGasPrice = _timelock_data[0];
}
// --------------------
// Change the caller bonus
// --------------------
function startChangeCallerBonus(uint256 _bonus) external onlyGovernance {
require(_bonus < 100000, "Bonus is too high");
_timelockStart = now;
_timelockType = 9;
_timelock_data[0] = _bonus;
}
function finishChangeCallerBonus() external onlyGovernance timelockConditionsMet(9) {
callerBonus = _timelock_data[0];
}
// --------------------
} | Change the rebase lag -------------------- | function startChangeRebaseLag(uint256 _lag) external onlyGovernance {
require(_lag > 1);
_timelockStart = now;
_timelockType = 5;
_timelock_data[0] = _lag;
}
| 13,387,935 |
./full_match/43113/0x6b9c8c5ac8161a932FF63308D0dF500a76c069AF/sources/src/Comptroller/IronControllerV2.sol | Validates repayBorrow and reverts on rejection. May emit logs. rToken Asset being repaid payer The address repaying the borrow borrower The address of the borrower actualRepayAmount The amount of underlying being repaid/ Shh - currently unused Shh - we don't ever want this hook to be marked pure | function repayBorrowVerify(
address rToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
rToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
if (false) {
maxAssets = maxAssets;
}
}
| 7,113,031 |
pragma solidity ^0.8.0;
// Copyright 2020 Keyko GmbH.
// This product includes software developed at BigchainDB GmbH and Ocean Protocol
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import './AgreementStoreLibrary.sol';
import '../conditions/ConditionStoreManager.sol';
import '../conditions/LockPaymentCondition.sol';
import '../registry/DIDRegistry.sol';
import '../templates/TemplateStoreManager.sol';
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';
/**
* @title Agreement Store Manager
* @author Keyko & Ocean Protocol
*
* @dev Implementation of the Agreement Store.
*
* The agreement store generates conditions for an agreement template.
* Agreement templates must to be approved in the Template Store
* Each agreement is linked to the DID of an asset.
*/
contract AgreementStoreManager is OwnableUpgradeable, AccessControlUpgradeable {
bytes32 private constant PROXY_ROLE = keccak256('PROXY_ROLE');
function grantProxyRole(address _address) public onlyOwner {
grantRole(PROXY_ROLE, _address);
}
function revokeProxyRole(address _address) public onlyOwner {
revokeRole(PROXY_ROLE, _address);
}
/**
* @dev The Agreement Store Library takes care of the basic storage functions
*/
using AgreementStoreLibrary for AgreementStoreLibrary.AgreementList;
/**
* @dev state storage for the agreements
*/
AgreementStoreLibrary.AgreementList internal agreementList;
ConditionStoreManager internal conditionStoreManager;
TemplateStoreManager internal templateStoreManager;
DIDRegistry internal didRegistry;
/**
* @dev initialize AgreementStoreManager Initializer
* Initializes Ownable. Only on contract creation.
* @param _owner refers to the owner of the contract
* @param _conditionStoreManagerAddress is the address of the connected condition store
* @param _templateStoreManagerAddress is the address of the connected template store
* @param _didRegistryAddress is the address of the connected DID Registry
*/
function initialize(
address _owner,
address _conditionStoreManagerAddress,
address _templateStoreManagerAddress,
address _didRegistryAddress
)
public
initializer
{
require(
_owner != address(0) &&
_conditionStoreManagerAddress != address(0) &&
_templateStoreManagerAddress != address(0) &&
_didRegistryAddress != address(0),
'Invalid address'
);
OwnableUpgradeable.__Ownable_init();
transferOwnership(_owner);
conditionStoreManager = ConditionStoreManager(
_conditionStoreManagerAddress
);
templateStoreManager = TemplateStoreManager(
_templateStoreManagerAddress
);
didRegistry = DIDRegistry(
_didRegistryAddress
);
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
}
/**
* @dev Create a new agreement and associate the agreement created to the address originating the transaction.
* The agreement will create conditions of conditionType with conditionId.
* Only "approved" templates can access this function.
* @param _id is the ID of the new agreement. Must be unique.
* @param _did is the bytes32 DID of the asset. The DID must be registered beforehand.
* @param _conditionTypes is a list of addresses that point to Condition contracts.
* @param _conditionIds is a list of bytes32 content-addressed Condition IDs
* @param _timeLocks is a list of uint time lock values associated to each Condition
* @param _timeOuts is a list of uint time out values associated to each Condition
* @return size the size of the agreement list after the create action.
*/
function createAgreement(
bytes32 _id,
bytes32 _did,
address[] memory _conditionTypes,
bytes32[] memory _conditionIds,
uint[] memory _timeLocks,
uint[] memory _timeOuts
)
public
returns (uint size)
{
return createAgreement(
_id,
_did,
_conditionTypes,
_conditionIds,
_timeLocks,
_timeOuts,
tx.origin // solhint-disable avoid-tx-origin
);
}
/**
* @dev Create a new agreement.
* The agreement will create conditions of conditionType with conditionId.
* Only "approved" templates can access this function.
* @param _id is the ID of the new agreement. Must be unique.
* @param _did is the bytes32 DID of the asset. The DID must be registered beforehand.
* @param _conditionTypes is a list of addresses that point to Condition contracts.
* @param _conditionIds is a list of bytes32 content-addressed Condition IDs
* @param _timeLocks is a list of uint time lock values associated to each Condition
* @param _timeOuts is a list of uint time out values associated to each Condition
* @param _creator address of the account associated as agreement and conditions creator
* @return size the size of the agreement list after the create action.
*/
function createAgreement(
bytes32 _id,
bytes32 _did,
address[] memory _conditionTypes,
bytes32[] memory _conditionIds,
uint[] memory _timeLocks,
uint[] memory _timeOuts,
address _creator
)
public
returns (uint size)
{
require(
templateStoreManager.isTemplateApproved(msg.sender) == true,
'Template not Approved'
);
require(
didRegistry.getBlockNumberUpdated(_did) > 0,
'DID not registered'
);
require(
_conditionIds.length == _conditionTypes.length &&
_timeLocks.length == _conditionTypes.length &&
_timeOuts.length == _conditionTypes.length,
'Arguments have wrong length'
);
// create the conditions in condition store. Fail if conditionId already exists.
for (uint256 i = 0; i < _conditionTypes.length; i++) {
conditionStoreManager.createCondition(
_conditionIds[i],
_conditionTypes[i],
_timeLocks[i],
_timeOuts[i],
_creator
);
}
agreementList.create(
_id,
_did,
msg.sender,
_conditionIds
);
// same as above
return getAgreementListSize();
}
function createAgreementAndPay(
bytes32 _id,
bytes32 _did,
address[] memory _conditionTypes,
bytes32[] memory _conditionIds,
uint[] memory _timeLocks,
uint[] memory _timeOuts,
address _creator,
uint _idx,
address payable _rewardAddress,
address _tokenAddress,
uint256[] memory _amounts,
address[] memory _receivers
)
public payable
{
require(hasRole(PROXY_ROLE, msg.sender), 'Invalid access role');
createAgreement(_id, _did, _conditionTypes, _conditionIds, _timeLocks, _timeOuts, _creator);
LockPaymentCondition(_conditionTypes[_idx]).fulfillProxy(_creator, _id, _did, _rewardAddress, _tokenAddress, _amounts, _receivers);
}
/**
* @dev Get agreement with _id.
* The agreement will create conditions of conditionType with conditionId.
* Only "approved" templates can access this function.
* @param _id is the ID of the agreement.
* @return did
* @return didOwner
* @return templateId
* @return conditionIds
* @return lastUpdatedBy
* @return blockNumberUpdated
*/
function getAgreement(bytes32 _id)
external
view
returns (
bytes32 did,
address didOwner,
address templateId,
bytes32[] memory conditionIds,
address lastUpdatedBy,
uint256 blockNumberUpdated
)
{
did = agreementList.agreements[_id].did;
didOwner = didRegistry.getDIDOwner(did);
templateId = agreementList.agreements[_id].templateId;
conditionIds = agreementList.agreements[_id].conditionIds;
lastUpdatedBy = agreementList.agreements[_id].lastUpdatedBy;
blockNumberUpdated = agreementList.agreements[_id].blockNumberUpdated;
}
/**
* @dev get the DID owner for this agreement with _id.
* @param _id is the ID of the agreement.
* @return didOwner the DID owner associated with agreement.did from the DID registry.
*/
function getAgreementDIDOwner(bytes32 _id)
external
view
returns (address didOwner)
{
bytes32 did = agreementList.agreements[_id].did;
return didRegistry.getDIDOwner(did);
}
/**
* @dev check the DID owner for this agreement with _id.
* @param _id is the ID of the agreement.
* @param _owner is the DID owner
* @return the DID owner associated with agreement.did from the DID registry.
*/
function isAgreementDIDOwner(bytes32 _id, address _owner)
external
view
returns (bool)
{
bytes32 did = agreementList.agreements[_id].did;
return (_owner == didRegistry.getDIDOwner(did));
}
/**
* @dev isAgreementDIDProvider for a given agreement Id
* and address check whether a DID provider is associated with this agreement
* @param _id is the ID of the agreement
* @param _provider is the DID provider
* @return true if a DID provider is associated with the agreement ID
*/
function isAgreementDIDProvider(bytes32 _id, address _provider)
external
view
returns(bool)
{
bytes32 did = agreementList.agreements[_id].did;
return didRegistry.isDIDProvider(did, _provider);
}
/**
* @return size the length of the agreement list.
*/
function getAgreementListSize()
public
view
virtual
returns (uint size)
{
return agreementList.agreementIds.length;
}
/**
* @param _did is the bytes32 DID of the asset.
* @return the agreement IDs for a given DID
*/
function getAgreementIdsForDID(bytes32 _did)
public
view
returns (bytes32[] memory)
{
return agreementList.didToAgreementIds[_did];
}
/**
* @param _templateId is the address of the agreement template.
* @return the agreement IDs for a given DID
*/
function getAgreementIdsForTemplateId(address _templateId)
public
view
returns (bytes32[] memory)
{
return agreementList.templateIdToAgreementIds[_templateId];
}
/**
* @dev getDIDRegistryAddress utility function
* used by other contracts or any EOA.
* @return the DIDRegistry address
*/
function getDIDRegistryAddress()
public
view
returns(address)
{
return address(didRegistry);
}
}
| get the DID owner for this agreement with _id. _id is the ID of the agreement. return didOwner the DID owner associated with agreement.did from the DID registry./ | function getAgreementDIDOwner(bytes32 _id)
external
view
returns (address didOwner)
{
bytes32 did = agreementList.agreements[_id].did;
return didRegistry.getDIDOwner(did);
}
| 2,473,888 |
// File: @openzeppelin/contracts/math/SafeMath.sol
// License: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// License: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts/v1/AbstractFiatTokenV1.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
abstract contract AbstractFiatTokenV1 is IERC20 {
function _approve(
address owner,
address spender,
uint256 value
) internal virtual;
function _transfer(
address from,
address to,
uint256 value
) internal virtual;
}
// File: contracts/v1/Ownable.sol
/**
* License: MIT
*
* Copyright (c) 2018 zOS Global Limited.
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @notice The Ownable contract has an owner address, and provides basic
* authorization control functions
* @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol
* Modifications:
* 1. Consolidate OwnableStorage into this contract (7/13/18)
* 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20)
* 3. Make public functions external (5/27/20)
*/
contract Ownable {
// Owner of the contract
address private _owner;
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev The constructor sets the original owner of the contract to the sender account.
*/
constructor() public {
setOwner(msg.sender);
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() external view returns (address) {
return _owner;
}
/**
* @dev Sets a new owner address
*/
function setOwner(address newOwner) internal {
_owner = newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == _owner, "Ownable: caller is not the 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) external onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
setOwner(newOwner);
}
}
// File: contracts/v1/Pausable.sol
/**
* License: MIT
*
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Copyright (c) 2018-2020 CENTRE SECZ0
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @notice Base contract which allows children to implement an emergency stop
* mechanism
* @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol
* Modifications:
* 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018)
* 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018)
* 3. Removed whenPaused (6/14/2018)
* 4. Switches ownable library to use ZeppelinOS (7/12/18)
* 5. Remove constructor (7/13/18)
* 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20)
* 7. Make public functions external (5/27/20)
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
event PauserChanged(address indexed newAddress);
address public pauser;
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Pausable: paused");
_;
}
/**
* @dev throws if called by any account other than the pauser
*/
modifier onlyPauser() {
require(msg.sender == pauser, "Pausable: caller is not the pauser");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() external onlyPauser {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() external onlyPauser {
paused = false;
emit Unpause();
}
/**
* @dev update the pauser role
*/
function updatePauser(address _newPauser) external onlyOwner {
require(
_newPauser != address(0),
"Pausable: new pauser is the zero address"
);
pauser = _newPauser;
emit PauserChanged(pauser);
}
}
// File: contracts/v1/Blacklistable.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title Blacklistable Token
* @dev Allows accounts to be blacklisted by a "blacklister" role
*/
contract Blacklistable is Ownable {
address public blacklister;
mapping(address => bool) internal blacklisted;
event Blacklisted(address indexed _account);
event UnBlacklisted(address indexed _account);
event BlacklisterChanged(address indexed newBlacklister);
/**
* @dev Throws if called by any account other than the blacklister
*/
modifier onlyBlacklister() {
require(
msg.sender == blacklister,
"Blacklistable: caller is not the blacklister"
);
_;
}
/**
* @dev Throws if argument account is blacklisted
* @param _account The address to check
*/
modifier notBlacklisted(address _account) {
require(
!blacklisted[_account],
"Blacklistable: account is blacklisted"
);
_;
}
/**
* @dev Checks if account is blacklisted
* @param _account The address to check
*/
function isBlacklisted(address _account) external view returns (bool) {
return blacklisted[_account];
}
/**
* @dev Adds account to blacklist
* @param _account The address to blacklist
*/
function blacklist(address _account) external onlyBlacklister {
blacklisted[_account] = true;
emit Blacklisted(_account);
}
/**
* @dev Removes account from blacklist
* @param _account The address to remove from the blacklist
*/
function unBlacklist(address _account) external onlyBlacklister {
blacklisted[_account] = false;
emit UnBlacklisted(_account);
}
function updateBlacklister(address _newBlacklister) external onlyOwner {
require(
_newBlacklister != address(0),
"Blacklistable: new blacklister is the zero address"
);
blacklister = _newBlacklister;
emit BlacklisterChanged(blacklister);
}
}
// File: contracts/v1/FiatTokenV1.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title FiatToken
* @dev ERC20 Token backed by fiat reserves
*/
contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
string public currency;
address public masterMinter;
bool internal initialized;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
uint256 internal totalSupply_ = 0;
mapping(address => bool) internal minters;
mapping(address => uint256) internal minterAllowed;
event Mint(address indexed minter, address indexed to, uint256 amount);
event Burn(address indexed burner, uint256 amount);
event MinterConfigured(address indexed minter, uint256 minterAllowedAmount);
event MinterRemoved(address indexed oldMinter);
event MasterMinterChanged(address indexed newMasterMinter);
function initialize(
string memory tokenName,
string memory tokenSymbol,
string memory tokenCurrency,
uint8 tokenDecimals,
address newMasterMinter,
address newPauser,
address newBlacklister,
address newOwner
) public {
require(!initialized, "FiatToken: contract is already initialized");
require(
newMasterMinter != address(0),
"FiatToken: new masterMinter is the zero address"
);
require(
newPauser != address(0),
"FiatToken: new pauser is the zero address"
);
require(
newBlacklister != address(0),
"FiatToken: new blacklister is the zero address"
);
require(
newOwner != address(0),
"FiatToken: new owner is the zero address"
);
name = tokenName;
symbol = tokenSymbol;
currency = tokenCurrency;
decimals = tokenDecimals;
masterMinter = newMasterMinter;
pauser = newPauser;
blacklister = newBlacklister;
setOwner(newOwner);
initialized = true;
}
/**
* @dev Throws if called by any account other than a minter
*/
modifier onlyMinters() {
require(minters[msg.sender], "FiatToken: caller is not a minter");
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint. Must be less than or equal
* to the minterAllowance of the caller.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount)
external
whenNotPaused
onlyMinters
notBlacklisted(msg.sender)
notBlacklisted(_to)
returns (bool)
{
require(_to != address(0), "FiatToken: mint to the zero address");
require(_amount > 0, "FiatToken: mint amount not greater than 0");
uint256 mintingAllowedAmount = minterAllowed[msg.sender];
require(
_amount <= mintingAllowedAmount,
"FiatToken: mint amount exceeds minterAllowance"
);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
emit Mint(msg.sender, _to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Throws if called by any account other than the masterMinter
*/
modifier onlyMasterMinter() {
require(
msg.sender == masterMinter,
"FiatToken: caller is not the masterMinter"
);
_;
}
/**
* @dev Get minter allowance for an account
* @param minter The address of the minter
*/
function minterAllowance(address minter) external view returns (uint256) {
return minterAllowed[minter];
}
/**
* @dev Checks if account is a minter
* @param account The address to check
*/
function isMinter(address account) external view returns (bool) {
return minters[account];
}
/**
* @notice Amount of remaining tokens spender is allowed to transfer on
* behalf of the token owner
* @param owner Token owner's address
* @param spender Spender's address
* @return Allowance amount
*/
function allowance(address owner, address spender)
external
override
view
returns (uint256)
{
return allowed[owner][spender];
}
/**
* @dev Get totalSupply of token
*/
function totalSupply() external override view returns (uint256) {
return totalSupply_;
}
/**
* @dev Get token balance of an account
* @param account address The account
*/
function balanceOf(address account)
external
override
view
returns (uint256)
{
return balances[account];
}
/**
* @notice Set spender's allowance over the caller's tokens to be a given
* value.
* @param spender Spender's address
* @param value Allowance amount
* @return True if successful
*/
function approve(address spender, uint256 value)
external
override
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(spender)
returns (bool)
{
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Internal function to set allowance
* @param owner Token owner's address
* @param spender Spender's address
* @param value Allowance amount
*/
function _approve(
address owner,
address spender,
uint256 value
) internal override {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @notice Transfer tokens by spending allowance
* @param from Payer's address
* @param to Payee's address
* @param value Transfer amount
* @return True if successful
*/
function transferFrom(
address from,
address to,
uint256 value
)
external
override
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(from)
notBlacklisted(to)
returns (bool)
{
require(
value <= allowed[from][msg.sender],
"ERC20: transfer amount exceeds allowance"
);
_transfer(from, to, value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
return true;
}
/**
* @notice Transfer tokens from the caller
* @param to Payee's address
* @param value Transfer amount
* @return True if successful
*/
function transfer(address to, uint256 value)
external
override
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(to)
returns (bool)
{
_transfer(msg.sender, to, value);
return true;
}
/**
* @notice Internal function to process transfers
* @param from Payer's address
* @param to Payee's address
* @param value Transfer amount
*/
function _transfer(
address from,
address to,
uint256 value
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(
value <= balances[from],
"ERC20: transfer amount exceeds balance"
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Function to add/update a new minter
* @param minter The address of the minter
* @param minterAllowedAmount The minting amount allowed for the minter
* @return True if the operation was successful.
*/
function configureMinter(address minter, uint256 minterAllowedAmount)
external
whenNotPaused
onlyMasterMinter
returns (bool)
{
minters[minter] = true;
minterAllowed[minter] = minterAllowedAmount;
emit MinterConfigured(minter, minterAllowedAmount);
return true;
}
/**
* @dev Function to remove a minter
* @param minter The address of the minter to remove
* @return True if the operation was successful.
*/
function removeMinter(address minter)
external
onlyMasterMinter
returns (bool)
{
minters[minter] = false;
minterAllowed[minter] = 0;
emit MinterRemoved(minter);
return true;
}
/**
* @dev allows a minter to burn some of its own tokens
* Validates that caller is a minter and that sender is not blacklisted
* amount is less than or equal to the minter's account balance
* @param _amount uint256 the amount of tokens to be burned
*/
function burn(uint256 _amount)
external
whenNotPaused
onlyMinters
notBlacklisted(msg.sender)
{
uint256 balance = balances[msg.sender];
require(_amount > 0, "FiatToken: burn amount not greater than 0");
require(balance >= _amount, "FiatToken: burn amount exceeds balance");
totalSupply_ = totalSupply_.sub(_amount);
balances[msg.sender] = balance.sub(_amount);
emit Burn(msg.sender, _amount);
emit Transfer(msg.sender, address(0), _amount);
}
function updateMasterMinter(address _newMasterMinter) external onlyOwner {
require(
_newMasterMinter != address(0),
"FiatToken: new masterMinter is the zero address"
);
masterMinter = _newMasterMinter;
emit MasterMinterChanged(masterMinter);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// License: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash
= 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{
value: weiValue
}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
// License: MIT
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(
value
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File: contracts/v1.1/Rescuable.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
contract Rescuable is Ownable {
using SafeERC20 for IERC20;
address private _rescuer;
event RescuerChanged(address indexed newRescuer);
/**
* @notice Returns current rescuer
* @return Rescuer's address
*/
function rescuer() external view returns (address) {
return _rescuer;
}
/**
* @notice Revert if called by any account other than the rescuer.
*/
modifier onlyRescuer() {
require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer");
_;
}
/**
* @notice Rescue ERC20 tokens locked up in this contract.
* @param tokenContract ERC20 token contract address
* @param to Recipient address
* @param amount Amount to withdraw
*/
function rescueERC20(
IERC20 tokenContract,
address to,
uint256 amount
) external onlyRescuer {
tokenContract.safeTransfer(to, amount);
}
/**
* @notice Assign the rescuer role to a given address.
* @param newRescuer New rescuer's address
*/
function updateRescuer(address newRescuer) external onlyOwner {
require(
newRescuer != address(0),
"Rescuable: new rescuer is the zero address"
);
_rescuer = newRescuer;
emit RescuerChanged(newRescuer);
}
}
// File: contracts/v1.1/FiatTokenV1_1.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title FiatTokenV1_1
* @dev ERC20 Token backed by fiat reserves
*/
contract FiatTokenV1_1 is FiatTokenV1, Rescuable {
}
// File: contracts/v2/AbstractFiatTokenV2.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 {
function _increaseAllowance(
address owner,
address spender,
uint256 increment
) internal virtual;
function _decreaseAllowance(
address owner,
address spender,
uint256 decrement
) internal virtual;
}
// File: contracts/util/ECRecover.sol
/**
* License: MIT
*
* Copyright (c) 2016-2019 zOS Global Limited
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title ECRecover
* @notice A library that provides a safe ECDSA recovery function
*/
library ECRecover {
/**
* @notice Recover signer's address from a signed message
* @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol
* Modifications: Accept v, r, and s as separate arguments
* @param digest Keccak-256 hash digest of the signed message
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
* @return Signer address
*/
function recover(
bytes32 digest,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (
uint256(s) >
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
) {
revert("ECRecover: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECRecover: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(digest, v, r, s);
require(signer != address(0), "ECRecover: invalid signature");
return signer;
}
}
// File: contracts/util/EIP712.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title EIP712
* @notice A library that provides EIP712 helper functions
*/
library EIP712 {
/**
* @notice Make EIP712 domain separator
* @param name Contract name
* @param version Contract version
* @return Domain separator
*/
function makeDomainSeparator(string memory name, string memory version)
internal
view
returns (bytes32)
{
uint256 chainId;
assembly {
chainId := chainid()
}
return
keccak256(
abi.encode(
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
// = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this)
)
);
}
/**
* @notice Recover signer's address from a EIP712 signature
* @param domainSeparator Domain separator
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
* @param typeHashAndData Type hash concatenated with data
* @return Signer's address
*/
function recover(
bytes32 domainSeparator,
uint8 v,
bytes32 r,
bytes32 s,
bytes memory typeHashAndData
) internal pure returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(typeHashAndData)
)
);
return ECRecover.recover(digest, v, r, s);
}
}
// File: contracts/v2/EIP712Domain.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title EIP712 Domain
*/
contract EIP712Domain {
/**
* @dev EIP712 Domain Separator
*/
bytes32 public DOMAIN_SEPARATOR;
}
// File: contracts/v2/GasAbstraction.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title Gas Abstraction
* @notice Provide internal implementation for gas-abstracted transfers and
* approvals
* @dev Contracts that inherit from this must wrap these with publicly
* accessible functions, optionally adding modifiers where necessary
*/
abstract contract GasAbstraction is AbstractFiatTokenV2, EIP712Domain {
bytes32
public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
// = keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32
public constant APPROVE_WITH_AUTHORIZATION_TYPEHASH = 0x808c10407a796f3ef2c7ea38c0638ea9d2b8a1c63e3ca9e1f56ce84ae59df73c;
// = keccak256("ApproveWithAuthorization(address owner,address spender,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32
public constant INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = 0x424222bb050a1f7f14017232a5671f2680a2d3420f504bd565cf03035c53198a;
// = keccak256("IncreaseAllowanceWithAuthorization(address owner,address spender,uint256 increment,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32
public constant DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH = 0xb70559e94cbda91958ebec07f9b65b3b490097c8d25c8dacd71105df1015b6d8;
// = keccak256("DecreaseAllowanceWithAuthorization(address owner,address spender,uint256 decrement,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32
public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
// = keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
enum AuthorizationState { Unused, Used, Canceled }
/**
* @dev authorizer address => nonce => authorization state
*/
mapping(address => mapping(bytes32 => AuthorizationState))
private _authorizationStates;
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
event AuthorizationCanceled(
address indexed authorizer,
bytes32 indexed nonce
);
/**
* @notice Returns the state of an authorization
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @return Authorization state
*/
function authorizationState(address authorizer, bytes32 nonce)
external
view
returns (AuthorizationState)
{
return _authorizationStates[authorizer][nonce];
}
/**
* @notice Verify a signed transfer authorization and execute if valid
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireValidAuthorization(from, nonce, validAfter, validBefore);
bytes memory data = abi.encode(
TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
from,
to,
value,
validAfter,
validBefore,
nonce
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from,
"FiatTokenV2: invalid signature"
);
_markAuthorizationAsUsed(from, nonce);
_transfer(from, to, value);
}
/**
* @notice Verify a signed authorization for an increase in the allowance
* granted to the spender and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param increment Amount of increase in allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _increaseAllowanceWithAuthorization(
address owner,
address spender,
uint256 increment,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireValidAuthorization(owner, nonce, validAfter, validBefore);
bytes memory data = abi.encode(
INCREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH,
owner,
spender,
increment,
validAfter,
validBefore,
nonce
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner,
"FiatTokenV2: invalid signature"
);
_markAuthorizationAsUsed(owner, nonce);
_increaseAllowance(owner, spender, increment);
}
/**
* @notice Verify a signed authorization for a decrease in the allowance
* granted to the spender and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param decrement Amount of decrease in allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _decreaseAllowanceWithAuthorization(
address owner,
address spender,
uint256 decrement,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireValidAuthorization(owner, nonce, validAfter, validBefore);
bytes memory data = abi.encode(
DECREASE_ALLOWANCE_WITH_AUTHORIZATION_TYPEHASH,
owner,
spender,
decrement,
validAfter,
validBefore,
nonce
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner,
"FiatTokenV2: invalid signature"
);
_markAuthorizationAsUsed(owner, nonce);
_decreaseAllowance(owner, spender, decrement);
}
/**
* @notice Verify a signed approval authorization and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _approveWithAuthorization(
address owner,
address spender,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireValidAuthorization(owner, nonce, validAfter, validBefore);
bytes memory data = abi.encode(
APPROVE_WITH_AUTHORIZATION_TYPEHASH,
owner,
spender,
value,
validAfter,
validBefore,
nonce
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner,
"FiatTokenV2: invalid signature"
);
_markAuthorizationAsUsed(owner, nonce);
_approve(owner, spender, value);
}
/**
* @notice Attempt to cancel an authorization
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _cancelAuthorization(
address authorizer,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireUnusedAuthorization(authorizer, nonce);
bytes memory data = abi.encode(
CANCEL_AUTHORIZATION_TYPEHASH,
authorizer,
nonce
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer,
"FiatTokenV2: invalid signature"
);
_authorizationStates[authorizer][nonce] = AuthorizationState.Canceled;
emit AuthorizationCanceled(authorizer, nonce);
}
/**
* @notice Check that an authorization is unused
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
*/
function _requireUnusedAuthorization(address authorizer, bytes32 nonce)
private
view
{
require(
_authorizationStates[authorizer][nonce] ==
AuthorizationState.Unused,
"FiatTokenV2: authorization is used or canceled"
);
}
/**
* @notice Check that authorization is valid
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
*/
function _requireValidAuthorization(
address authorizer,
bytes32 nonce,
uint256 validAfter,
uint256 validBefore
) private view {
require(
now > validAfter,
"FiatTokenV2: authorization is not yet valid"
);
require(now < validBefore, "FiatTokenV2: authorization is expired");
_requireUnusedAuthorization(authorizer, nonce);
}
/**
* @notice Mark an authorization as used
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
*/
function _markAuthorizationAsUsed(address authorizer, bytes32 nonce)
private
{
_authorizationStates[authorizer][nonce] = AuthorizationState.Used;
emit AuthorizationUsed(authorizer, nonce);
}
}
// File: contracts/v2/Permit.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title Permit
* @notice An alternative to approveWithAuthorization, provided for
* compatibility with the draft EIP2612 proposed by Uniswap.
* @dev Differences:
* - Uses sequential nonce, which restricts transaction submission to one at a
* time, or else it will revert
* - Has deadline (= validBefore - 1) but does not have validAfter
* - Doesn't have a way to change allowance atomically to prevent ERC20 multiple
* withdrawal attacks
*/
abstract contract Permit is AbstractFiatTokenV2, EIP712Domain {
bytes32
public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
mapping(address => uint256) private _permitNonces;
/**
* @notice Nonces for permit
* @param owner Token owner's address (Authorizer)
* @return Next nonce
*/
function nonces(address owner) external view returns (uint256) {
return _permitNonces[owner];
}
/**
* @notice Verify a signed approval permit and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param deadline The time at which this expires (unix time)
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(deadline >= now, "FiatTokenV2: permit is expired");
bytes memory data = abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
_permitNonces[owner]++,
deadline
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner,
"FiatTokenV2: invalid signature"
);
_approve(owner, spender, value);
}
}
// File: contracts/v2/FiatTokenV2.sol
/**
* License: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title FiatToken V2
* @notice ERC20 Token backed by fiat reserves, version 2
*/
contract FiatTokenV2 is FiatTokenV1_1, GasAbstraction, Permit {
bool internal _initializedV2;
/**
* @notice Initialize V2 contract
* @dev When upgrading to V2, this function must also be invoked by using
* upgradeToAndCall instead of upgradeTo, or by calling both from a contract
* in a single transaction.
* @param newName New token name
*/
function initializeV2(string calldata newName) external {
require(
!_initializedV2,
"FiatTokenV2: contract is already initialized"
);
name = newName;
DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(newName, "2");
_initializedV2 = true;
}
/**
* @notice Increase the allowance by a given increment
* @param spender Spender's address
* @param increment Amount of increase in allowance
* @return True if successful
*/
function increaseAllowance(address spender, uint256 increment)
external
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(spender)
returns (bool)
{
_increaseAllowance(msg.sender, spender, increment);
return true;
}
/**
* @notice Decrease the allowance by a given decrement
* @param spender Spender's address
* @param decrement Amount of decrease in allowance
* @return True if successful
*/
function decreaseAllowance(address spender, uint256 decrement)
external
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(spender)
returns (bool)
{
_decreaseAllowance(msg.sender, spender, decrement);
return true;
}
/**
* @notice Execute a transfer with a signed authorization
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
_transferWithAuthorization(
from,
to,
value,
validAfter,
validBefore,
nonce,
v,
r,
s
);
}
/**
* @notice Update allowance with a signed authorization
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function approveWithAuthorization(
address owner,
address spender,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) {
_approveWithAuthorization(
owner,
spender,
value,
validAfter,
validBefore,
nonce,
v,
r,
s
);
}
/**
* @notice Increase allowance with a signed authorization
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param increment Amount of increase in allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function increaseAllowanceWithAuthorization(
address owner,
address spender,
uint256 increment,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) {
_increaseAllowanceWithAuthorization(
owner,
spender,
increment,
validAfter,
validBefore,
nonce,
v,
r,
s
);
}
/**
* @notice Decrease allowance with a signed authorization
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param decrement Amount of decrease in allowance
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function decreaseAllowanceWithAuthorization(
address owner,
address spender,
uint256 decrement,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) {
_decreaseAllowanceWithAuthorization(
owner,
spender,
decrement,
validAfter,
validBefore,
nonce,
v,
r,
s
);
}
/**
* @notice Attempt to cancel an authorization
* @dev Works only if the authorization is not yet used.
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function cancelAuthorization(
address authorizer,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused {
_cancelAuthorization(authorizer, nonce, v, r, s);
}
/**
* @notice Update allowance with a signed permit
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param deadline Expiration time, seconds since the epoch
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) {
_permit(owner, spender, value, deadline, v, r, s);
}
/**
* @notice Internal function to increase the allowance by a given increment
* @param owner Token owner's address
* @param spender Spender's address
* @param increment Amount of increase
*/
function _increaseAllowance(
address owner,
address spender,
uint256 increment
) internal override {
_approve(owner, spender, allowed[owner][spender].add(increment));
}
/**
* @notice Internal function to decrease the allowance by a given decrement
* @param owner Token owner's address
* @param spender Spender's address
* @param decrement Amount of decrease
*/
function _decreaseAllowance(
address owner,
address spender,
uint256 decrement
) internal override {
_approve(
owner,
spender,
allowed[owner][spender].sub(
decrement,
"ERC20: decreased allowance below zero"
)
);
}
} | Verify a signed approval permit and execute if valid owner Token owner's address (Authorizer) spender Spender's address value Amount of allowance deadline The time at which this expires (unix time) v v of the signature r r of the signature s s of the signature/ | function _permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(deadline >= now, "FiatTokenV2: permit is expired");
bytes memory data = abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
_permitNonces[owner]++,
deadline
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner,
"FiatTokenV2: invalid signature"
);
_approve(owner, spender, value);
}
| 529,594 |
./partial_match/56/0x3F6ad3c13E3a6bB5655F09A95cA05B6FF4c3DCd6/sources/LPToken.sol | Swap two tokens using this pool tokenIndexFrom the token the user wants to swap from tokenIndexTo the token the user wants to swap to dx the amount of tokens the user wants to swap from minDy the min amount the user would like to receive, or revert. deadline latest timestamp to accept this transaction/ | function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) {
return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy);
}
| 11,182,705 |
./partial_match/1/0x1fC7bD85293f3982f40D52698DF8D26be89360d6/sources/EtheremonWorld.sol | convenient tool to add monster can add only one time add stat step | function addMonsterClassBasic(uint32 _classId, uint8 _type, uint256 _price, uint256 _returnPrice,
uint8 _ss1, uint8 _ss2, uint8 _ss3, uint8 _ss4, uint8 _ss5, uint8 _ss6) onlyModerators external {
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterClassAcc memory class;
(class.classId, class.price, class.returnPrice, class.total, class.catchable) = data.getMonsterClass(_classId);
if (_classId == 0 || class.classId == _classId)
revert();
data.setMonsterClass(_classId, _price, _returnPrice, true);
data.addElementToArrayType(ArrayType.CLASS_TYPE, uint64(_classId), _type);
data.addElementToArrayType(ArrayType.STAT_START, uint64(_classId), _ss1);
data.addElementToArrayType(ArrayType.STAT_START, uint64(_classId), _ss2);
data.addElementToArrayType(ArrayType.STAT_START, uint64(_classId), _ss3);
data.addElementToArrayType(ArrayType.STAT_START, uint64(_classId), _ss4);
data.addElementToArrayType(ArrayType.STAT_START, uint64(_classId), _ss5);
data.addElementToArrayType(ArrayType.STAT_START, uint64(_classId), _ss6);
}
| 2,667,480 |
./full_match/4/0x7b26bd610E97456aEb8ED44cC5398DCaeF291919/sources/contracts/playground.sol | Bag memory bag = bag[id]; | function _claim(uint256 id) internal noCheaters {
Action memory action = activities[id];
if(block.timestamp <= action.timestamp) return;
uint256 timeDiff = uint256(block.timestamp - action.timestamp);
if (action.action == Actions.FARM) cryptoodleCredits.mint(action.owner, claimableCredits(timeDiff, bag[id].bagModifier));
if (action.action == Actions.TRAIN) {
bag[id].lvlProgress += uint16(timeDiff * 3000 / 1 minutes);
bag[id].level = uint16(bag[id].lvlProgress / 1000);
}
activities[id].timestamp = uint88(block.timestamp);
}
| 751,525 |
pragma solidity ^0.4.23;
import "./BitLibrary.sol";
/** @title Bit Oracle. */
contract BitOracle {
/** @dev Denotes the contract owner. */
address public owner;
/** @dev Denotes the contract state. */
BitLibrary.Data private data;
/** @dev Constructs the contract. */
constructor() public {
owner = msg.sender;
}
/** @dev Restricts invocation to contract owner. */
modifier restricted() {
if (msg.sender == owner) _;
}
/** @dev Sets contract state to provided value and returns it. The
* invocation is restricted to the contract owner. Also, a
* `Bit` event is emitted.
*
* @param _bit Bit value to set to.
*/
function setBit(bool _bit) public restricted returns (bool) {
emit Bit(msg.sender, _bit);
BitLibrary.set(data, _bit);
return _bit;
}
/** @dev Gets contract state.*/
function getBit() public view returns (bool) {
return BitLibrary.get(data);
}
/** @dev Event emitted on contract state changes.*/
event Bit(
/** @dev Contract state change originator. */
address indexed from,
/** @dev Contract state change value. */
bool indexed bit
);
}
| Sets contract state to provided value and returns it. The invocation is restricted to the contract owner. Also, a `Bit` event is emitted. _bit Bit value to set to./ | function setBit(bool _bit) public restricted returns (bool) {
emit Bit(msg.sender, _bit);
BitLibrary.set(data, _bit);
return _bit;
}
| 12,682,123 |
./full_match/11155111/0xe2011488ea6B02692Ee58717698aecDdfBf4756F/sources/contracts/upgrades/GraphProxyAdmin.sol | Accepts a proxy. _implementation Address of the implementation accepting the proxy. _proxy Address of the proxy being accepted./ | function acceptProxy(GraphUpgradeable _implementation, IGraphProxy _proxy)
external
onlyGovernor
{
_implementation.acceptProxy(_proxy);
}
| 3,841,364 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../libraries/SafeMathExt.sol";
import "../libraries/Utils.sol";
contract Tracer {
using SafeMath for uint256;
using SafeMathExt for uint256;
using Utils for EnumerableSetUpgradeable.AddressSet;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set;
struct PerpetualUID {
address liquidityPool;
uint256 perpetualIndex;
}
// liquidity pool address[]
EnumerableSetUpgradeable.AddressSet internal _liquidityPoolSet;
// hash(puid) => PerpetualUID {}
mapping(bytes32 => PerpetualUID) internal _perpetualUIDs;
// trader => hash(puid) []
mapping(address => EnumerableSetUpgradeable.Bytes32Set) internal _traderActiveLiquidityPools;
// operator => address
mapping(address => EnumerableSetUpgradeable.AddressSet) internal _operatorOwnedLiquidityPools;
mapping(address => address) internal _liquidityPoolOwners;
modifier onlyLiquidityPool() {
require(isLiquidityPool(msg.sender), "caller is not liquidity pool instance");
_;
}
// =========================== Liquidity Pool ===========================
/**
* @notice Get the number of all liquidity pools.
*
* @return uint256 The number of all liquidity pools
*/
function getLiquidityPoolCount() public view returns (uint256) {
return _liquidityPoolSet.length();
}
/**
* @notice Check if the liquidity pool exists.
*
* @param liquidityPool The address of the liquidity pool.
* @return True if the liquidity pool exists.
*/
function isLiquidityPool(address liquidityPool) public view returns (bool) {
return _liquidityPoolSet.contains(liquidityPool);
}
/**
* @notice Get the liquidity pools whose index between begin and end.
*
* @param begin The begin index.
* @param end The end index.
* @return result An array of liquidity pool addresses whose index between begin and end.
*/
function listLiquidityPools(uint256 begin, uint256 end)
public
view
returns (address[] memory result)
{
result = _liquidityPoolSet.toArray(begin, end);
}
/**
* @notice Get the number of the liquidity pools owned by the operator.
*
* @param operator The address of operator.
* @return uint256 The number of the liquidity pools owned by the operator.
*/
function getOwnedLiquidityPoolsCountOf(address operator) public view returns (uint256) {
return _operatorOwnedLiquidityPools[operator].length();
}
/**
* @notice Get the liquidity pools owned by the operator and whose index between begin and end.
*
* @param operator The address of the operator.
* @param begin The begin index.
* @param end The end index.
* @return result The liquidity pools owned by the operator and whose index between begin and end.
*/
function listLiquidityPoolOwnedBy(
address operator,
uint256 begin,
uint256 end
) public view returns (address[] memory result) {
return _operatorOwnedLiquidityPools[operator].toArray(begin, end);
}
/**
* @notice Liquidity pool must call this method when changing its ownership to the new operator.
* Can only be called by a liquidity pool. This method does not affect 'ownership' or privileges
* of operator but only make a record for further query.
*
* @param liquidityPool The address of the liquidity pool.
* @param operator The address of the new operator, must be different from the old operator.
*/
function registerOperatorOfLiquidityPool(address liquidityPool, address operator)
public
onlyLiquidityPool
{
address prevOperator = _liquidityPoolOwners[liquidityPool];
_operatorOwnedLiquidityPools[prevOperator].remove(liquidityPool);
_operatorOwnedLiquidityPools[operator].add(liquidityPool);
_liquidityPoolOwners[liquidityPool] = operator;
}
/**
* @dev Record the liquidity pool, the liquidity pool should not be recorded before
*
* @param liquidityPool The address of the liquidity pool.
* @param operator The address of operator.
*/
function _registerLiquidityPool(address liquidityPool, address operator) internal {
require(liquidityPool != address(0), "invalid liquidity pool address");
bool success = _liquidityPoolSet.add(liquidityPool);
require(success, "liquidity pool exists");
_operatorOwnedLiquidityPools[operator].add(liquidityPool);
_liquidityPoolOwners[liquidityPool] = operator;
}
// =========================== Active Liquidity Pool of Trader ===========================
/**
* @notice Get the number of the trader's active liquidity pools. Active means the trader's account is
* not all empty in perpetuals of the liquidity pool. Empty means cash and position are zero.
*
* @param trader The address of the trader.
* @return Number of the trader's active liquidity pools.
*/
function getActiveLiquidityPoolCountOf(address trader) public view returns (uint256) {
return _traderActiveLiquidityPools[trader].length();
}
/**
* @notice Check if the perpetual is active for the trader. Active means the trader's account is
* not empty in the perpetual. Empty means cash and position are zero.
*
* @param trader The address of the trader.
* @param liquidityPool The address of liquidity pool.
* @param perpetualIndex The index of the perpetual in the liquidity pool.
* @return True if the perpetual is active for the trader.
*/
function isActiveLiquidityPoolOf(
address trader,
address liquidityPool,
uint256 perpetualIndex
) public view returns (bool) {
return
_traderActiveLiquidityPools[trader].contains(
_getPerpetualKey(liquidityPool, perpetualIndex)
);
}
/**
* @notice Get the liquidity pools whose index between begin and end and active for the trader.
* Active means the trader's account is not all empty in perpetuals of the liquidity pool.
* Empty means cash and position are zero.
*
* @param trader The address of the trader.
* @param begin The begin index.
* @param end The end index.
* @return result An array of active (non-empty margin account) liquidity pool address and perpetul index.
*/
function listActiveLiquidityPoolsOf(
address trader,
uint256 begin,
uint256 end
) public view returns (PerpetualUID[] memory result) {
require(end > begin, "begin should be lower than end");
uint256 length = _traderActiveLiquidityPools[trader].length();
if (begin >= length) {
return result;
}
uint256 safeEnd = end.min(length);
result = new PerpetualUID[](safeEnd.sub(begin));
for (uint256 i = begin; i < safeEnd; i++) {
result[i.sub(begin)] = _perpetualUIDs[_traderActiveLiquidityPools[trader].at(i)];
}
return result;
}
/**
* @notice Activate the perpetual for the trader. Active means the trader's account is not empty in
* the perpetual. Empty means cash and position are zero. Can only called by a liquidity pool.
*
* @param trader The address of the trader.
* @param perpetualIndex The index of the perpetual in the liquidity pool.
* @return True if the activation is successful.
*/
function activatePerpetualFor(address trader, uint256 perpetualIndex)
external
onlyLiquidityPool
returns (bool)
{
bytes32 key = _getPerpetualKey(msg.sender, perpetualIndex);
if (_perpetualUIDs[key].liquidityPool == address(0)) {
_perpetualUIDs[key] = PerpetualUID({
liquidityPool: msg.sender,
perpetualIndex: perpetualIndex
});
}
return _traderActiveLiquidityPools[trader].add(key);
}
/**
* @notice Deactivate the perpetual for the trader. Active means the trader's account is not empty in
* the perpetual. Empty means cash and position are zero. Can only called by a liquidity pool.
*
* @param trader The address of the trader.
* @param perpetualIndex The index of the perpetual in the liquidity pool.
* @return True if the deactivation is successful.
*/
function deactivatePerpetualFor(address trader, uint256 perpetualIndex)
external
onlyLiquidityPool
returns (bool)
{
return
_traderActiveLiquidityPools[trader].remove(
_getPerpetualKey(msg.sender, perpetualIndex)
);
}
// =========================== Active Liquidity Pool of Trader ===========================
/**
* @dev Get the key of the perpetual
* @param liquidityPool The address of the liquidity pool which the perpetual belongs to.
* @param perpetualIndex The index of the perpetual in the liquidity pool.
* @return Key hash of the perpetual.
*/
function _getPerpetualKey(address liquidityPool, uint256 perpetualIndex)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(liquidityPool, perpetualIndex));
}
}
| Check if the perpetual is active for the trader. Active means the trader's account is not empty in the perpetual. Empty means cash and position are zero. trader The address of the trader. liquidityPool The address of liquidity pool. perpetualIndex The index of the perpetual in the liquidity pool. return True if the perpetual is active for the trader./ | function isActiveLiquidityPoolOf(
address trader,
address liquidityPool,
uint256 perpetualIndex
) public view returns (bool) {
return
_traderActiveLiquidityPools[trader].contains(
_getPerpetualKey(liquidityPool, perpetualIndex)
);
}
| 12,750,665 |
/**
*Submitted for verification at Etherscan.io on 2022-04-14
*/
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// 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)
}
}
}
// File: @openzeppelin/contracts/utils/Counters.sol
// 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;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface 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);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract 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);
}
}
// File: jovians.sol
pragma solidity >=0.8.0;
/*
.------..------..------.
|4.--. ||0.--. ||9.--. |
| :/\: || :/\: || :/\: |
| :\/: || :\/: || :\/: |
| '--'4|| '--'0|| '--'9|
`------'`------'`------'
*/
contract NamelessJoviansShards is ERC721Enumerable, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounterRedShard;
Counters.Counter private _tokenIdCounterBlackShard;
Counters.Counter private _tokenIdCounterGoldShard;
bool public onlyWhitelisted = false;
bool public openMint = false;
mapping (address => uint256) whitelist;
mapping (address => uint256) addressList;
struct ShardInfo {
uint256 price;
uint256 maxSupply;
uint256 startingTokenId;
}
enum Color {
Red,
Black,
Gold
}
mapping (Color => ShardInfo) shards;
string private _contractURI;
string public baseURI = "";
uint256 public maxMintPerTx = 3;
uint256 public maxMintPerWL = 3;
uint256 public maxMintPerAddress = 6;
bytes32 public whitelistMerkleRoot;
constructor() ERC721("Nameless Jovians: Shards", "NJS") {
shards[Color.Gold] = ShardInfo(0.2 ether, 808, 1);
shards[Color.Black] = ShardInfo(0.1 ether, 808, 809);
shards[Color.Red] = ShardInfo(.08 ether, 5793, 1617);
}
//-----Setters-----
function setMaxMintPerWL(uint256 _maxMint) external onlyOwner {
maxMintPerWL = _maxMint;
}
function setMaxMintPerTx(uint256 _maxMint) external onlyOwner {
maxMintPerTx = _maxMint;
}
function setMaxMintPerAddress(uint256 _maxMint) external onlyOwner {
maxMintPerAddress = _maxMint;
}
//Set Base URI
function setBaseURI(string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
function setWhitelistMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
whitelistMerkleRoot = _merkleRoot;
}
function getInfo(Color color) private view returns (ShardInfo memory) {
return shards[color];
}
function setPrice(Color color, uint256 _newPrice) external onlyOwner {
shards[color].price = _newPrice;
}
function setSupply(Color color, uint256 _newSupply) external onlyOwner {
require(_newSupply < shards[color].maxSupply, "supply cannot be greater");
shards[color].maxSupply = _newSupply;
}
//------Control-----
function flipWhitelistedState() public onlyOwner {
onlyWhitelisted = !onlyWhitelisted;
}
function flipMintState() public onlyOwner {
openMint = !openMint;
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: Nonexistent token");
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, Strings.toString(tokenId))) : "";
}
modifier onlyEOA() {
require(msg.sender == tx.origin, "no contracts!!!!!");
_;
}
modifier mintCompliance(Color color, uint256 quantity) {
require(openMint, "public sale is not open");
require(quantity <= maxMintPerTx, "too many");
require(addressList[msg.sender] + quantity <= maxMintPerAddress, "too many");
ShardInfo memory shard = shards[color];
require(totalSupplyByColor(color) + quantity <= shard.maxSupply, "too many");
require(msg.value >= shard.price * quantity, "not enough ether sent");
_;
}
modifier mintComplianceWithWL(Color color, uint256 quantity) {
require(onlyWhitelisted, "whitelist mint is not open");
require(whitelist[msg.sender] + quantity <= maxMintPerWL, "too many");
ShardInfo memory shard = shards[color];
require(totalSupplyByColor(color) + quantity <= shard.maxSupply, "too many");
require(msg.value >= shard.price * quantity, "not enough ether sent");
_;
}
modifier isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root) {
require(
MerkleProof.verify(
merkleProof,
root,
keccak256(abi.encodePacked(msg.sender))
),
"Address does not exist in nameless"
);
_;
}
//---------Mint functions--------
function mintRedShard(uint256 quantity) external payable {
_mint(Color.Red, quantity);
}
function mintRedShardWhitelist(bytes32[] calldata merkleProof, uint256 quantity) external payable {
_mintWithWL(Color.Red, quantity, merkleProof);
}
function mintRedShardForAddress(uint256 quantity, address receiver) external onlyOwner {
_mintForAddress(Color.Red, quantity, receiver);
}
function mintBlackShard(uint256 quantity) external payable {
_mint(Color.Black, quantity);
}
function mintBlackShardWhitelist(bytes32[] calldata merkleProof, uint256 quantity) external payable {
_mintWithWL(Color.Black, quantity, merkleProof);
}
function mintBlackShardForAddress(uint256 quantity, address receiver) external onlyOwner {
_mintForAddress(Color.Black, quantity, receiver);
}
function mintGoldShard(uint256 quantity) external payable {
_mint(Color.Gold, quantity);
}
function mintGoldShardWhitelist(bytes32[] calldata merkleProof, uint256 quantity) external payable {
_mintWithWL(Color.Gold, quantity, merkleProof);
}
function mintGoldShardForAddress(uint256 quantity, address receiver) external onlyOwner {
_mintForAddress(Color.Gold, quantity, receiver);
}
function _mint(Color color, uint256 quantity) internal onlyEOA mintCompliance(color, quantity) {
addressList[msg.sender] += quantity;
_safeMintLoop(color, quantity, msg.sender);
}
function _mintWithWL(
Color color,
uint256 quantity,
bytes32[] calldata merkleProof
)
internal
onlyEOA
isValidMerkleProof(merkleProof, whitelistMerkleRoot)
mintComplianceWithWL(color, quantity)
{
whitelist[msg.sender] += quantity;
_safeMintLoop(color, quantity, msg.sender);
}
function _mintForAddress(Color color, uint256 quantity, address receiver) internal onlyOwner {
ShardInfo memory shard = shards[color];
require(totalSupplyByColor(color) + quantity <= shard.maxSupply, "too many");
_safeMintLoop(color, quantity, receiver);
}
function _safeMintLoop(Color color, uint256 quantity, address to) internal {
for (uint256 i = 0; i < quantity; i++) {
uint256 tokenId = totalSupplyByColor(color) + getInfo(color).startingTokenId;
increaseSupplyByColor(color);
_safeMint(to, tokenId);
}
}
function getCounter(Color color) private view returns (Counters.Counter storage) {
if (color == Color.Gold) {
return _tokenIdCounterGoldShard;
}
if (color == Color.Black) {
return _tokenIdCounterBlackShard;
}
if (color == Color.Red) {
return _tokenIdCounterRedShard;
}
revert("invalid color");
}
function totalSupplyByColor(Color color) public view returns (uint) {
return getCounter(color).current();
}
function increaseSupplyByColor(Color color) internal {
getCounter(color).increment();
}
function maxSupplyByColor(Color color) public view returns (uint) {
return getInfo(color).maxSupply;
}
function priceByColor(Color color) external view returns (uint) {
return getInfo(color).price;
}
function ownerWithdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function emergencyWithdrawAll() external onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
} | ---------Mint functions-------- | function mintRedShard(uint256 quantity) external payable {
_mint(Color.Red, quantity);
}
| 7,650,770 |
pragma solidity 0.4.24;
/**
* @dev Pulled from OpenZeppelin: https://git.io/vbaRf
* When this is in a public release we will switch to not vendoring this file
*
* @title Eliptic curve signature operations
*
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using his signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Extracting these values isn't possible without assembly
// solhint-disable no-inline-assembly
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
}
/**
* @title SigningLogic is contract implementing signature recovery from typed data signatures
* @notice Recovers signatures based on the SignTypedData implementation provided by ethSigUtil
* @dev This contract is inherited by other contracts.
*/
contract SigningLogic {
// Signatures contain a nonce to make them unique. usedSignatures tracks which signatures
// have been used so they can't be replayed
mapping (bytes32 => bool) public usedSignatures;
function burnSignatureDigest(bytes32 _signatureDigest, address _sender) internal {
bytes32 _txDataHash = keccak256(abi.encode(_signatureDigest, _sender));
require(!usedSignatures[_txDataHash], "Signature not unique");
usedSignatures[_txDataHash] = true;
}
bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 constant ATTESTATION_REQUEST_TYPEHASH = keccak256(
"AttestationRequest(bytes32 dataHash,bytes32 nonce)"
);
bytes32 constant ADD_ADDRESS_TYPEHASH = keccak256(
"AddAddress(address addressToAdd,bytes32 nonce)"
);
bytes32 constant REMOVE_ADDRESS_TYPEHASH = keccak256(
"RemoveAddress(address addressToRemove,bytes32 nonce)"
);
bytes32 constant PAY_TOKENS_TYPEHASH = keccak256(
"PayTokens(address sender,address receiver,uint256 amount,bytes32 nonce)"
);
bytes32 constant RELEASE_TOKENS_FOR_TYPEHASH = keccak256(
"ReleaseTokensFor(address sender,uint256 amount,bytes32 nonce)"
);
bytes32 constant ATTEST_FOR_TYPEHASH = keccak256(
"AttestFor(address subject,address requester,uint256 reward,bytes32 dataHash,bytes32 requestNonce)"
);
bytes32 constant CONTEST_FOR_TYPEHASH = keccak256(
"ContestFor(address requester,uint256 reward,bytes32 requestNonce)"
);
bytes32 constant REVOKE_ATTESTATION_FOR_TYPEHASH = keccak256(
"RevokeAttestationFor(bytes32 link,bytes32 nonce)"
);
bytes32 constant VOTE_FOR_TYPEHASH = keccak256(
"VoteFor(uint16 choice,address voter,bytes32 nonce,address poll)"
);
bytes32 constant LOCKUP_TOKENS_FOR_TYPEHASH = keccak256(
"LockupTokensFor(address sender,uint256 amount,bytes32 nonce)"
);
bytes32 DOMAIN_SEPARATOR;
constructor (string name, string version, uint256 chainId) public {
DOMAIN_SEPARATOR = hash(EIP712Domain({
name: name,
version: version,
chainId: chainId,
verifyingContract: this
}));
}
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
function hash(EIP712Domain eip712Domain) private pure returns (bytes32) {
return keccak256(abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
));
}
struct AttestationRequest {
bytes32 dataHash;
bytes32 nonce;
}
function hash(AttestationRequest request) private pure returns (bytes32) {
return keccak256(abi.encode(
ATTESTATION_REQUEST_TYPEHASH,
request.dataHash,
request.nonce
));
}
struct AddAddress {
address addressToAdd;
bytes32 nonce;
}
function hash(AddAddress request) private pure returns (bytes32) {
return keccak256(abi.encode(
ADD_ADDRESS_TYPEHASH,
request.addressToAdd,
request.nonce
));
}
struct RemoveAddress {
address addressToRemove;
bytes32 nonce;
}
function hash(RemoveAddress request) private pure returns (bytes32) {
return keccak256(abi.encode(
REMOVE_ADDRESS_TYPEHASH,
request.addressToRemove,
request.nonce
));
}
struct PayTokens {
address sender;
address receiver;
uint256 amount;
bytes32 nonce;
}
function hash(PayTokens request) private pure returns (bytes32) {
return keccak256(abi.encode(
PAY_TOKENS_TYPEHASH,
request.sender,
request.receiver,
request.amount,
request.nonce
));
}
struct AttestFor {
address subject;
address requester;
uint256 reward;
bytes32 dataHash;
bytes32 requestNonce;
}
function hash(AttestFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
ATTEST_FOR_TYPEHASH,
request.subject,
request.requester,
request.reward,
request.dataHash,
request.requestNonce
));
}
struct ContestFor {
address requester;
uint256 reward;
bytes32 requestNonce;
}
function hash(ContestFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
CONTEST_FOR_TYPEHASH,
request.requester,
request.reward,
request.requestNonce
));
}
struct RevokeAttestationFor {
bytes32 link;
bytes32 nonce;
}
function hash(RevokeAttestationFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
REVOKE_ATTESTATION_FOR_TYPEHASH,
request.link,
request.nonce
));
}
struct VoteFor {
uint16 choice;
address voter;
bytes32 nonce;
address poll;
}
function hash(VoteFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
VOTE_FOR_TYPEHASH,
request.choice,
request.voter,
request.nonce,
request.poll
));
}
struct LockupTokensFor {
address sender;
uint256 amount;
bytes32 nonce;
}
function hash(LockupTokensFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
LOCKUP_TOKENS_FOR_TYPEHASH,
request.sender,
request.amount,
request.nonce
));
}
struct ReleaseTokensFor {
address sender;
uint256 amount;
bytes32 nonce;
}
function hash(ReleaseTokensFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
RELEASE_TOKENS_FOR_TYPEHASH,
request.sender,
request.amount,
request.nonce
));
}
function generateRequestAttestationSchemaHash(
bytes32 _dataHash,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(AttestationRequest(
_dataHash,
_nonce
))
)
);
}
function generateAddAddressSchemaHash(
address _addressToAdd,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(AddAddress(
_addressToAdd,
_nonce
))
)
);
}
function generateRemoveAddressSchemaHash(
address _addressToRemove,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(RemoveAddress(
_addressToRemove,
_nonce
))
)
);
}
function generatePayTokensSchemaHash(
address _sender,
address _receiver,
uint256 _amount,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(PayTokens(
_sender,
_receiver,
_amount,
_nonce
))
)
);
}
function generateAttestForDelegationSchemaHash(
address _subject,
address _requester,
uint256 _reward,
bytes32 _dataHash,
bytes32 _requestNonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(AttestFor(
_subject,
_requester,
_reward,
_dataHash,
_requestNonce
))
)
);
}
function generateContestForDelegationSchemaHash(
address _requester,
uint256 _reward,
bytes32 _requestNonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(ContestFor(
_requester,
_reward,
_requestNonce
))
)
);
}
function generateRevokeAttestationForDelegationSchemaHash(
bytes32 _link,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(RevokeAttestationFor(
_link,
_nonce
))
)
);
}
function generateVoteForDelegationSchemaHash(
uint16 _choice,
address _voter,
bytes32 _nonce,
address _poll
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(VoteFor(
_choice,
_voter,
_nonce,
_poll
))
)
);
}
function generateLockupTokensDelegationSchemaHash(
address _sender,
uint256 _amount,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(LockupTokensFor(
_sender,
_amount,
_nonce
))
)
);
}
function generateReleaseTokensDelegationSchemaHash(
address _sender,
uint256 _amount,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(ReleaseTokensFor(
_sender,
_amount,
_nonce
))
)
);
}
function recoverSigner(bytes32 _hash, bytes _sig) internal pure returns (address) {
address signer = ECRecovery.recover(_hash, _sig);
require(signer != address(0));
return signer;
}
}
pragma solidity ^0.4.21;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @notice TokenEscrowMarketplace is an ERC20 payment channel that enables users to send BLT by exchanging signatures off-chain
* Users approve the contract address to transfer BLT on their behalf using the standard ERC20.approve function
* After approval, either the user or the contract admin initiates the transfer of BLT into the contract
* Once in the contract, users can send payments via a signed message to another user.
* The signature transfers BLT from lockup to the recipient's balance
* Users can withdraw funds at any time. Or the admin can release them on the user's behalf
*
* BLT is stored in the contract by address
*
* Only the AttestationLogic contract is authorized to release funds once a jobs is complete
*/
contract TokenEscrowMarketplace is SigningLogic {
using SafeERC20 for ERC20;
using SafeMath for uint256;
address public attestationLogic;
mapping(address => uint256) public tokenEscrow;
ERC20 public token;
event TokenMarketplaceWithdrawal(address escrowPayer, uint256 amount);
event TokenMarketplaceEscrowPayment(address escrowPayer, address escrowPayee, uint256 amount);
event TokenMarketplaceDeposit(address escrowPayer, uint256 amount);
/**
* @notice The TokenEscrowMarketplace constructor initializes the interfaces to the other contracts
* @dev Some actions are restricted to be performed by the attestationLogic contract.
* Signing logic is upgradeable in case the signTypedData spec changes
* @param _token Address of BLT
* @param _attestationLogic Address of current attestation logic contract
*/
constructor(
ERC20 _token,
address _attestationLogic
) public SigningLogic("Bloom Token Escrow Marketplace", "2", 1) {
token = _token;
attestationLogic = _attestationLogic;
}
modifier onlyAttestationLogic() {
require(msg.sender == attestationLogic);
_;
}
/**
* @notice Lockup tokens for set time period on behalf of user. Must be preceeded by approve
* @dev Authorized by a signTypedData signature by sender
* Sigs can only be used once. They contain a unique nonce
* So an action can be repeated, with a different signature
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function moveTokensToEscrowLockupFor(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) external {
validateLockupTokensSig(
_sender,
_amount,
_nonce,
_delegationSig
);
moveTokensToEscrowLockupForUser(_sender, _amount);
}
/**
* @notice Verify lockup signature is valid
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function validateLockupTokensSig(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) private {
bytes32 _signatureDigest = generateLockupTokensDelegationSchemaHash(_sender, _amount, _nonce);
require(_sender == recoverSigner(_signatureDigest, _delegationSig), 'Invalid LockupTokens Signature');
burnSignatureDigest(_signatureDigest, _sender);
}
/**
* @notice Lockup tokens by user. Must be preceeded by approve
* @param _amount Tokens to lock up
*/
function moveTokensToEscrowLockup(uint256 _amount) external {
moveTokensToEscrowLockupForUser(msg.sender, _amount);
}
/**
* @notice Lockup tokens for set time. Must be preceeded by approve
* @dev Private function called by appropriate public function
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
*/
function moveTokensToEscrowLockupForUser(
address _sender,
uint256 _amount
) private {
token.safeTransferFrom(_sender, this, _amount);
addToEscrow(_sender, _amount);
}
/**
* @notice Withdraw tokens from escrow back to requester
* @dev Authorized by a signTypedData signature by sender
* Sigs can only be used once. They contain a unique nonce
* So an action can be repeated, with a different signature
* @param _sender User withdrawing their tokens
* @param _amount Tokens to withdraw
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function releaseTokensFromEscrowFor(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) external {
validateReleaseTokensSig(
_sender,
_amount,
_nonce,
_delegationSig
);
releaseTokensFromEscrowForUser(_sender, _amount);
}
/**
* @notice Verify lockup signature is valid
* @param _sender User withdrawing their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function validateReleaseTokensSig(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) private {
bytes32 _signatureDigest = generateReleaseTokensDelegationSchemaHash(_sender, _amount, _nonce);
require(_sender == recoverSigner(_signatureDigest, _delegationSig), 'Invalid ReleaseTokens Signature');
burnSignatureDigest(_signatureDigest, _sender);
}
/**
* @notice Release tokens back to payer's available balance if lockup expires
* @dev Token balance retreived by accountId. Can be different address from the one that deposited tokens
* @param _amount Tokens to retreive from escrow
*/
function releaseTokensFromEscrow(uint256 _amount) external {
releaseTokensFromEscrowForUser(msg.sender, _amount);
}
/**
* @notice Release tokens back to payer's available balance
* @param _payer User retreiving tokens from escrow
* @param _amount Tokens to retreive from escrow
*/
function releaseTokensFromEscrowForUser(
address _payer,
uint256 _amount
) private {
subFromEscrow(_payer, _amount);
token.safeTransfer(_payer, _amount);
emit TokenMarketplaceWithdrawal(_payer, _amount);
}
/**
* @notice Pay from escrow of payer to available balance of receiever
* @dev Private function to modify balances on payment
* @param _payer User with tokens in escrow
* @param _receiver User receiving tokens
* @param _amount Tokens being sent
*/
function payTokensFromEscrow(address _payer, address _receiver, uint256 _amount) private {
subFromEscrow(_payer, _amount);
token.safeTransfer(_receiver, _amount);
}
/**
* @notice Pay tokens to receiver from payer's escrow given a valid signature
* @dev Execution restricted to attestationLogic contract
* @param _payer User paying tokens from escrow
* @param _receiver User receiving payment
* @param _amount Tokens being paid
* @param _nonce Unique Id for sig to make it one-time-use
* @param _paymentSig Signed parameters by payer authorizing payment
*/
function requestTokenPayment(
address _payer,
address _receiver,
uint256 _amount,
bytes32 _nonce,
bytes _paymentSig
) external onlyAttestationLogic {
validatePaymentSig(
_payer,
_receiver,
_amount,
_nonce,
_paymentSig
);
payTokensFromEscrow(_payer, _receiver, _amount);
emit TokenMarketplaceEscrowPayment(_payer, _receiver, _amount);
}
/**
* @notice Verify payment signature is valid
* @param _payer User paying tokens from escrow
* @param _receiver User receiving payment
* @param _amount Tokens being paid
* @param _nonce Unique Id for sig to make it one-time-use
* @param _paymentSig Signed parameters by payer authorizing payment
*/
function validatePaymentSig(
address _payer,
address _receiver,
uint256 _amount,
bytes32 _nonce,
bytes _paymentSig
) private {
bytes32 _signatureDigest = generatePayTokensSchemaHash(_payer, _receiver, _amount, _nonce);
require(_payer == recoverSigner(_signatureDigest, _paymentSig), 'Invalid Payment Signature');
burnSignatureDigest(_signatureDigest, _payer);
}
/**
* @notice Helper function to add to escrow balance
* @param _from Account address for escrow mapping
* @param _amount Tokens to lock up
*/
function addToEscrow(address _from, uint256 _amount) private {
tokenEscrow[_from] = tokenEscrow[_from].add(_amount);
emit TokenMarketplaceDeposit(_from, _amount);
}
/**
* Helper function to reduce escrow token balance of user
*/
function subFromEscrow(address _from, uint256 _amount) private {
require(tokenEscrow[_from] >= _amount);
tokenEscrow[_from] = tokenEscrow[_from].sub(_amount);
}
}
/**
* @title Initializable
* @dev The Initializable contract has an initializer address, and provides basic authorization control
* only while in initialization mode. Once changed to production mode the inializer loses authority
*/
contract Initializable {
address public initializer;
bool public initializing;
event InitializationEnded();
/**
* @dev The Initializable constructor sets the initializer to the provided address
*/
constructor(address _initializer) public {
initializer = _initializer;
initializing = true;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyDuringInitialization() {
require(msg.sender == initializer, 'Method can only be called by initializer');
require(initializing, 'Method can only be called during initialization');
_;
}
/**
* @dev Allows the initializer to end the initialization period
*/
function endInitialization() public onlyDuringInitialization {
initializing = false;
emit InitializationEnded();
}
}
/**
* @title AttestationLogic allows users to submit attestations given valid signatures
* @notice Attestation Logic Logic provides a public interface for Bloom and
* users to submit attestations.
*/
contract AttestationLogic is Initializable, SigningLogic{
TokenEscrowMarketplace public tokenEscrowMarketplace;
/**
* @notice AttestationLogic constructor sets the implementation address of all related contracts
* @param _tokenEscrowMarketplace Address of marketplace holding tokens which are
* released to attesters upon completion of a job
*/
constructor(
address _initializer,
TokenEscrowMarketplace _tokenEscrowMarketplace
) Initializable(_initializer) SigningLogic("Bloom Attestation Logic", "2", 1) public {
tokenEscrowMarketplace = _tokenEscrowMarketplace;
}
event TraitAttested(
address subject,
address attester,
address requester,
bytes32 dataHash
);
event AttestationRejected(address indexed attester, address indexed requester);
event AttestationRevoked(bytes32 link, address attester);
event TokenEscrowMarketplaceChanged(address oldTokenEscrowMarketplace, address newTokenEscrowMarketplace);
/**
* @notice Function for attester to submit attestation from their own account)
* @dev Wrapper for attestForUser using msg.sender
* @param _subject User this attestation is about
* @param _requester User requesting and paying for this attestation in BLT
* @param _reward Payment to attester from requester in BLT
* @param _requesterSig Signature authorizing payment from requester to attester
* @param _dataHash Hash of data being attested and nonce
* @param _requestNonce Nonce in sig signed by subject and requester so they can't be replayed
* @param _subjectSig Signed authorization from subject with attestation agreement
*/
function attest(
address _subject,
address _requester,
uint256 _reward,
bytes _requesterSig,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _subjectSig // Sig of subject with requester, attester, dataHash, requestNonce
) external {
attestForUser(
_subject,
msg.sender,
_requester,
_reward,
_requesterSig,
_dataHash,
_requestNonce,
_subjectSig
);
}
/**
* @notice Submit attestation for a user in order to pay the gas costs
* @dev Recover signer of delegation message. If attester matches delegation signature, add the attestation
* @param _subject user this attestation is about
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requesterSig signature authorizing payment from requester to attester
* @param _dataHash hash of data being attested and nonce
* @param _requestNonce Nonce in sig signed by subject and requester so they can't be replayed
* @param _subjectSig signed authorization from subject with attestation agreement
* @param _delegationSig signature authorizing attestation on behalf of attester
*/
function attestFor(
address _subject,
address _attester,
address _requester,
uint256 _reward,
bytes _requesterSig,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _subjectSig, // Sig of subject with dataHash and requestNonce
bytes _delegationSig
) external {
// Confirm attester address matches recovered address from signature
validateAttestForSig(_subject, _attester, _requester, _reward, _dataHash, _requestNonce, _delegationSig);
attestForUser(
_subject,
_attester,
_requester,
_reward,
_requesterSig,
_dataHash,
_requestNonce,
_subjectSig
);
}
/**
* @notice Perform attestation
* @dev Verify valid certainty level and user addresses
* @param _subject user this attestation is about
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requesterSig signature authorizing payment from requester to attester
* @param _dataHash hash of data being attested and nonce
* @param _requestNonce Nonce in sig signed by subject and requester so they can't be replayed
* @param _subjectSig signed authorization from subject with attestation agreement
*/
function attestForUser(
address _subject,
address _attester,
address _requester,
uint256 _reward,
bytes _requesterSig,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _subjectSig
) private {
validateSubjectSig(
_subject,
_dataHash,
_requestNonce,
_subjectSig
);
emit TraitAttested(
_subject,
_attester,
_requester,
_dataHash
);
if (_reward > 0) {
tokenEscrowMarketplace.requestTokenPayment(_requester, _attester, _reward, _requestNonce, _requesterSig);
}
}
/**
* @notice Function for attester to reject an attestation and receive payment
* without associating the negative attestation with the subject's bloomId
* @param _requester User requesting and paying for this attestation in BLT
* @param _reward Payment to attester from requester in BLT
* @param _requestNonce Nonce in sig signed by requester so it can't be replayed
* @param _requesterSig Signature authorizing payment from requester to attester
*/
function contest(
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes _requesterSig
) external {
contestForUser(
msg.sender,
_requester,
_reward,
_requestNonce,
_requesterSig
);
}
/**
* @notice Function for attester to reject an attestation and receive payment
* without associating the negative attestation with the subject's bloomId
* Perform on behalf of attester to pay gas fees
* @param _requester User requesting and paying for this attestation in BLT
* @param _attester user completing the attestation
* @param _reward Payment to attester from requester in BLT
* @param _requestNonce Nonce in sig signed by requester so it can't be replayed
* @param _requesterSig Signature authorizing payment from requester to attester
*/
function contestFor(
address _attester,
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes _requesterSig,
bytes _delegationSig
) external {
validateContestForSig(
_attester,
_requester,
_reward,
_requestNonce,
_delegationSig
);
contestForUser(
_attester,
_requester,
_reward,
_requestNonce,
_requesterSig
);
}
/**
* @notice Private function for attester to reject an attestation and receive payment
* without associating the negative attestation with the subject's bloomId
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requestNonce Nonce in sig signed by requester so it can't be replayed
* @param _requesterSig signature authorizing payment from requester to attester
*/
function contestForUser(
address _attester,
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes _requesterSig
) private {
if (_reward > 0) {
tokenEscrowMarketplace.requestTokenPayment(_requester, _attester, _reward, _requestNonce, _requesterSig);
}
emit AttestationRejected(_attester, _requester);
}
/**
* @notice Verify subject signature is valid
* @param _subject user this attestation is about
* @param _dataHash hash of data being attested and nonce
* param _requestNonce Nonce in sig signed by subject so it can't be replayed
* @param _subjectSig Signed authorization from subject with attestation agreement
*/
function validateSubjectSig(
address _subject,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _subjectSig
) private {
bytes32 _signatureDigest = generateRequestAttestationSchemaHash(_dataHash, _requestNonce);
require(_subject == recoverSigner(_signatureDigest, _subjectSig));
burnSignatureDigest(_signatureDigest, _subject);
}
/**
* @notice Verify attester delegation signature is valid
* @param _subject user this attestation is about
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _dataHash hash of data being attested and nonce
* @param _requestNonce nonce in sig signed by subject so it can't be replayed
* @param _delegationSig signature authorizing attestation on behalf of attester
*/
function validateAttestForSig(
address _subject,
address _attester,
address _requester,
uint256 _reward,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _delegationSig
) private {
bytes32 _delegationDigest = generateAttestForDelegationSchemaHash(_subject, _requester, _reward, _dataHash, _requestNonce);
require(_attester == recoverSigner(_delegationDigest, _delegationSig), 'Invalid AttestFor Signature');
burnSignatureDigest(_delegationDigest, _attester);
}
/**
* @notice Verify attester delegation signature is valid
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requestNonce nonce referenced in TokenEscrowMarketplace so payment sig can't be replayed
* @param _delegationSig signature authorizing attestation on behalf of attester
*/
function validateContestForSig(
address _attester,
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes _delegationSig
) private {
bytes32 _delegationDigest = generateContestForDelegationSchemaHash(_requester, _reward, _requestNonce);
require(_attester == recoverSigner(_delegationDigest, _delegationSig), 'Invalid ContestFor Signature');
burnSignatureDigest(_delegationDigest, _attester);
}
/**
* @notice Submit attestation completed prior to deployment of this contract
* @dev Gives initializer privileges to write attestations during the initialization period without signatures
* @param _requester user requesting this attestation be completed
* @param _attester user completing the attestation
* @param _subject user this attestation is about
* @param _dataHash hash of data being attested
*/
function migrateAttestation(
address _requester,
address _attester,
address _subject,
bytes32 _dataHash
) public onlyDuringInitialization {
emit TraitAttested(
_subject,
_attester,
_requester,
_dataHash
);
}
/**
* @notice Revoke an attestation
* @dev Link is included in dataHash and cannot be directly connected to a BloomID
* @param _link bytes string embedded in dataHash to link revocation
*/
function revokeAttestation(
bytes32 _link
) external {
revokeAttestationForUser(_link, msg.sender);
}
/**
* @notice Revoke an attestation
* @dev Link is included in dataHash and cannot be directly connected to a BloomID
* @param _link bytes string embedded in dataHash to link revocation
*/
function revokeAttestationFor(
address _sender,
bytes32 _link,
bytes32 _nonce,
bytes _delegationSig
) external {
validateRevokeForSig(_sender, _link, _nonce, _delegationSig);
revokeAttestationForUser(_link, _sender);
}
/**
* @notice Verify revocation signature is valid
* @param _link bytes string embedded in dataHash to link revocation
* @param _sender user revoking attestation
* @param _delegationSig signature authorizing revocation on behalf of revoker
*/
function validateRevokeForSig(
address _sender,
bytes32 _link,
bytes32 _nonce,
bytes _delegationSig
) private {
bytes32 _delegationDigest = generateRevokeAttestationForDelegationSchemaHash(_link, _nonce);
require(_sender == recoverSigner(_delegationDigest, _delegationSig), 'Invalid RevokeFor Signature');
burnSignatureDigest(_delegationDigest, _sender);
}
/**
* @notice Revoke an attestation
* @dev Link is included in dataHash and cannot be directly connected to a BloomID
* @param _link bytes string embedded in dataHash to link revocation
* @param _sender address identify revoker
*/
function revokeAttestationForUser(
bytes32 _link,
address _sender
) private {
emit AttestationRevoked(_link, _sender);
}
/**
* @notice Set the implementation of the TokenEscrowMarketplace contract by setting a new address
* @dev Restricted to initializer
* @param _newTokenEscrowMarketplace Address of new SigningLogic implementation
*/
function setTokenEscrowMarketplace(TokenEscrowMarketplace _newTokenEscrowMarketplace) external onlyDuringInitialization {
address oldTokenEscrowMarketplace = tokenEscrowMarketplace;
tokenEscrowMarketplace = _newTokenEscrowMarketplace;
emit TokenEscrowMarketplaceChanged(oldTokenEscrowMarketplace, tokenEscrowMarketplace);
}
} | Verify subject signature is valid _subject user this attestation is about _dataHash hash of data being attested and nonce param _requestNonce Nonce in sig signed by subject so it can't be replayed _subjectSig Signed authorization from subject with attestation agreement/ | function validateSubjectSig(
address _subject,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _subjectSig
) private {
bytes32 _signatureDigest = generateRequestAttestationSchemaHash(_dataHash, _requestNonce);
require(_subject == recoverSigner(_signatureDigest, _subjectSig));
burnSignatureDigest(_signatureDigest, _subject);
}
| 880,701 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "./interfaces/IDappState.sol";
import "./DappLib.sol";
import "./interfaces/IERC1155.sol";
import "./interfaces/IERC1155Receiver.sol";
import "./interfaces/IERC1155MetadataURI.sol";
import "./imports/custom_nft/Address.sol";
import "./imports/custom_nft/Context.sol";
import "./imports/custom_nft/ERC165.sol";
import "./imports/custom_nft/generator/generator.sol";
/********************************************************************************************/
/* This contract is auto-generated based on your choices in DappStarter. You can make */
/* changes, but be aware that generating a new DappStarter project will require you to */
/* merge changes. One approach you can take is to make changes in Dapp.sol and have it */
/* call into this one. You can maintain all your data in this contract and your app logic */
/* in Dapp.sol. This lets you update and deploy Dapp.sol with revised code and still */
/* continue using this one. */
/********************************************************************************************/
contract DappState is IDappState
,Context, ERC165, IERC1155, IERC1155MetadataURI
{
// Allow DappLib(SafeMath) functions to be called for all uint256 types
// (similar to "prototype" in Javascript)
using DappLib for uint256;
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FILE STORAGE: IPFS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
using DappLib for DappLib.Multihash;
using Address for address;
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ S T A T E @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
// Account used to deploy contract
address private contractOwner;
/*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/
// Track authorized admins count to prevent lockout
uint256 private authorizedAdminsCount = 1;
// Admins authorized to manage contract
mapping(address => uint256) private authorizedAdmins;
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT ACCESS <<<<<<<<<<<<<<<<<<<<<<<<<<<*/
// Contracts authorized to call this one
mapping(address => uint256) private authorizedContracts;
/*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT RUN STATE <<<<<<<<<<<<<<<<<<<<<<<<<<*/
// Contract run state
bool private contractRunState = true;
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ASSET VALUE TRACKING: TOKEN <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
string public name;
string public symbol;
uint256 public decimals;
// Token balance for each address
mapping(address => uint256) balances;
// Approval granted to transfer tokens by one address to another address
mapping (address => mapping (address => uint256)) internal allowed;
// Tokens currently in circulation (you'll need to update this if you create more tokens)
uint256 public total;
// Tokens created when contract was deployed
uint256 public initialSupply;
// Multiplier to convert to smallest unit
uint256 public UNIT_MULTIPLIER;
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FILE STORAGE: IPFS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
struct IpfsDocument {
// Unique identifier -- defaults to multihash digest of file
bytes32 docId;
bytes32 label;
// Registration timestamp
uint256 timestamp;
// Owner of document
address owner;
// External Document reference
DappLib.Multihash docRef;
}
// All added documents
mapping(bytes32 => IpfsDocument) ipfsDocs;
uint constant IPFS_DOCS_PAGE_SIZE = 50;
uint256 public ipfsLastPage = 0;
// All documents organized by page
mapping(uint256 => bytes32[]) public ipfsDocsByPage;
// All documents for which an account is the owner
mapping(address => bytes32[]) public ipfsDocsByOwner;
// 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;
// Mapping from token ID to metadata
mapping (uint256 => Generator.MetaData) public metadata;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private uri;
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ C O N S T R U C T O R @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
constructor()
{
contractOwner = msg.sender;
/*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/
// Add account that deployed contract as an authorized admin
authorizedAdmins[msg.sender] = 1;
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ASSET VALUE TRACKING: TOKEN <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
name = "Achievements";
symbol = "ACVM";
decimals = 2;
// Multiplier to convert to smallest unit
UNIT_MULTIPLIER = 10 ** uint256(decimals);
uint256 supply = 10000000;
// Convert supply to smallest unit
total = supply.mul(UNIT_MULTIPLIER);
initialSupply = total;
// Assign entire initial supply to contract owner
balances[contractOwner] = total;
}
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ E V E N T S @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT RUN STATE <<<<<<<<<<<<<<<<<<<<<<<<<<*/
// Event fired when status is changed
event ChangeContractRunState
(
bool indexed mode,
address indexed account,
uint256 timestamp
);
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ASSET VALUE TRACKING: TOKEN <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
// Fired when an account authorizes another account to spend tokens on its behalf
event Approval
(
address indexed owner,
address indexed spender,
uint256 value
);
// Fired when tokens are transferred from one account to another
event Transfer
(
address indexed from,
address indexed to,
uint256 value
);
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FILE STORAGE: IPFS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
// Event fired when doc is added
event AddIpfsDocument
(
bytes32 indexed docId,
address indexed owner,
uint256 timestamp
);
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ M O D I F I E R S @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/
/**
* @dev Modifier that requires the function caller to be a contract admin
*/
modifier requireContractAdmin()
{
require(isContractAdmin(msg.sender), "Caller is not a contract administrator");
// Modifiers require an "_" which indicates where the function body will be added
_;
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT ACCESS <<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/**
* @dev Modifier that requires the calling contract to be authorized
*/
modifier requireContractAuthorized()
{
require(isContractAuthorized(msg.sender), "Calling contract not authorized");
// Modifiers require an "_" which indicates where the function body will be added
_;
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT RUN STATE <<<<<<<<<<<<<<<<<<<<<<<<<<*/
/**
* @dev Modifier that requires the "contractRunState" 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 requireContractRunStateActive()
{
require(contractRunState, "Contract is currently not active");
// Modifiers require an "_" which indicates where the function body will be added
_;
}
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ F U N C T I O N S @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/
/**
* @dev Checks if an account is an admin
*
* @param account Address of the account to check
*/
function isContractAdmin
(
address account
)
public
view
returns(bool)
{
return authorizedAdmins[account] == 1;
}
/**
* @dev Adds a contract admin
*
* @param account Address of the admin to add
*/
function addContractAdmin
(
address account
)
external
requireContractAdmin
{
require(account != address(0), "Invalid address");
require(authorizedAdmins[account] < 1, "Account is already an administrator");
authorizedAdmins[account] = 1;
authorizedAdminsCount++;
}
/**
* @dev Removes a previously added admin
*
* @param account Address of the admin to remove
*/
function removeContractAdmin
(
address account
)
external
requireContractAdmin
{
require(account != address(0), "Invalid address");
require(authorizedAdminsCount >= 2, "Cannot remove last admin");
delete authorizedAdmins[account];
authorizedAdminsCount--;
}
/**
* @dev Removes the last admin fully decentralizing the contract
*
* @param account Address of the admin to remove
*/
function removeLastContractAdmin
(
address account
)
external
requireContractAdmin
{
require(account != address(0), "Invalid address");
require(authorizedAdminsCount == 1, "Not the last admin");
delete authorizedAdmins[account];
authorizedAdminsCount--;
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT ACCESS <<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/**
* @dev Authorizes a smart contract to call this contract
*
* @param account Address of the calling smart contract
*/
function authorizeContract
(
address account
)
public
requireContractAdmin
{
require(account != address(0), "Invalid address");
authorizedContracts[account] = 1;
}
/**
* @dev Deauthorizes a previously authorized smart contract from calling this contract
*
* @param account Address of the calling smart contract
*/
function deauthorizeContract
(
address account
)
external
requireContractAdmin
{
require(account != address(0), "Invalid address");
delete authorizedContracts[account];
}
/**
* @dev Checks if a contract is authorized to call this contract
*
* @param account Address of the calling smart contract
*/
function isContractAuthorized
(
address account
)
public
view
returns(bool)
{
return authorizedContracts[account] == 1;
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT RUN STATE <<<<<<<<<<<<<<<<<<<<<<<<<<*/
/**
* @dev Get active status of contract
*
* @return A bool that is the current active status
*/
function isContractRunStateActive()
external
view
returns(bool)
{
return contractRunState;
}
/**
* @dev Sets contract active status on/off
*
* When active status is off, all write transactions except for this one will fail
*/
function setContractRunState
(
bool mode
)
external
// **** WARNING: Adding requireContractRunStateActive modifier will result in contract lockout ****
requireContractAdmin // Administrator Role block is required to ensure only authorized individuals can pause contract
{
require(mode != contractRunState, "Run state is already set to the same value");
contractRunState = mode;
emit ChangeContractRunState(mode, msg.sender, block.timestamp);
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ASSET VALUE TRACKING: TOKEN <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/**
* @dev Total supply of tokens
*/
function totalSupply()
external
view
returns (uint256)
{
return total;
}
/**
* @dev Gets the balance of the calling address.
*
* @return An uint256 representing the amount owned by the calling address
*/
function balance()
public
view
returns (uint256)
{
return balanceOf(msg.sender);
}
/**
* @dev Gets the balance of the specified address.
*
* @param owner The address to query the balance of
* @return An uint256 representing the amount owned by the passed address
*/
function balanceOf
(
address owner
)
public
view
returns (uint256)
{
return balances[owner];
}
/**
* @dev Transfers token for a specified address
*
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return A bool indicating if the transfer was successful.
*/
function transfer
(
address to,
uint256 value
)
public
returns (bool)
{
require(to != address(0));
require(to != msg.sender);
require(value <= balanceOf(msg.sender));
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Transfers tokens from one address to another
*
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
* @return A bool indicating if the transfer was successful.
*/
function transferFrom
(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(from != address(0));
require(value <= allowed[from][msg.sender]);
require(value <= balanceOf(from));
require(to != address(0));
require(from != to);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Checks the amount of tokens that an owner allowed to a spender.
*
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance
(
address owner,
address spender
)
public
view
returns (uint256)
{
return allowed[owner][spender];
}
/**
* @dev Approves the passed address to spend the specified amount of tokens
* on behalf of msg.sender.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A bool indicating success (always returns true)
*/
function approve
(
address spender,
uint256 value
)
public
returns (bool)
{
allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FILE STORAGE: IPFS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/**
* @dev Adds a new IPFS doc
*
* @param docId Unique identifier (multihash digest of doc)
* @param label Short, descriptive label for document
* @param digest Digest of folder with doc binary and metadata
* @param hashFunction Function used for generating doc folder hash
* @param digestLength Length of doc folder hash
*/
function addIpfsDocument
(
bytes32 docId,
bytes32 label,
bytes32 digest,
uint8 hashFunction,
uint8 digestLength
)
external
{
// Prevent empty string for docId
require(docId[0] != 0, "Invalid docId");
// Prevent empty string for digest
require(digest[0] != 0, "Invalid ipfsDoc folder digest");
// Prevent duplicate docIds
require(ipfsDocs[docId].timestamp == 0, "Document already exists");
ipfsDocs[docId] = IpfsDocument({
docId: docId,
label: label,
timestamp: block.timestamp,
owner: msg.sender,
docRef: DappLib.Multihash({
digest: digest,
hashFunction: hashFunction,
digestLength: digestLength
})
});
ipfsDocsByOwner[msg.sender].push(docId);
if (ipfsDocsByPage[ipfsLastPage].length == IPFS_DOCS_PAGE_SIZE) {
ipfsLastPage++;
}
ipfsDocsByPage[ipfsLastPage].push(docId);
emit AddIpfsDocument(docId, msg.sender, ipfsDocs[docId].timestamp);
}
/**
* @dev Gets individual IPFS doc by docId
*
* @param id DocumentId of doc
*/
function getIpfsDocument
(
bytes32 id
)
external
view
returns(
bytes32 docId,
bytes32 label,
uint256 timestamp,
address owner,
bytes32 docDigest,
uint8 docHashFunction,
uint8 docDigestLength
)
{
IpfsDocument memory ipfsDoc = ipfsDocs[id];
docId = ipfsDoc.docId;
label = ipfsDoc.label;
timestamp = ipfsDoc.timestamp;
owner = ipfsDoc.owner;
docDigest = ipfsDoc.docRef.digest;
docHashFunction = ipfsDoc.docRef.hashFunction;
docDigestLength = ipfsDoc.docRef.digestLength;
}
/**
* @dev Gets docs where account is/was an owner
*
* @param account Address of owner
*/
function getIpfsDocumentsByOwner
(
address account
)
external
view
returns(bytes32[] memory)
{
require(account != address(0), "Invalid account");
return ipfsDocsByOwner[account];
}
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 getURI() public view virtual override returns (string memory) {
return uri;
}
/**
@notice Transfers `amount` amount of an `id` from the `from` address to the `to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `from` account (see "Approval" section of the standard).
MUST revert if `to` is the zero address.
MUST revert if balance of holder for token `id` is lower than the `amount` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param from Source address
@param to Target address
@param id ID of the token type
@param amount Transfer amount
@param data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `to`
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == msgSender() || isApprovedForAll(from, msgSender()),
"ERC1155: caller is not owner nor approved"
);
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");
balances[id][from] = fromBalance - amount;
balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
@notice Transfers `amounts` amount(s) of `ids` from the `from` address to the `to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `from` account (see "Approval" section of the standard).
MUST revert if `to` is the zero address.
MUST revert if length of `ids` is not the same as length of `amounts`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `ids` is lower than the respective amount(s) in `amounts` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param from Source address
@param to Target address
@param ids IDs of each token type (order and length must match _values array)
@param amounts Transfer amounts per token type (order and length must match _ids array)
@param data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `to`
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == msgSender() || isApprovedForAll(from, msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
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");
balances[id][from] = fromBalance - amount;
balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
@notice Get the balance of an account's Tokens.
@param account The address of the token holder
@param id ID of the Token
@return The _owner's balance of the Token type requested
*/
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];
}
/**
@notice Get the balance of multiple account/token pairs
@param accounts The addresses of the token holders
@param ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
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;
}
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param operator Address to add to the set of authorized operators
@param approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(msgSender() != operator, "ERC1155: setting approval status for self");
operatorApprovals[msgSender()][operator] = approved;
emit ApprovalForAll(msgSender(), operator, approved);
}
/**
@notice Queries the approval status of an operator for a given owner.
@param account The owner of the Tokens
@param operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return operatorApprovals[account][operator];
}
/**
* @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) external virtual requireContractAdmin {
uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function mint(address account, uint256 id, uint256 amount, bytes memory data) public virtual requireContractAdmin {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = msgSender();
beforeTokenTransfer(operator, address(0), account, asSingletonArray(id), asSingletonArray(amount), data);
balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
function mintNFT(address account, uint256 id, uint256 amount, Generator.MetaData memory metaData) external virtual requireContractAdmin {
mint(account, id, amount, "");
metadata[id] = metaData;
}
/**
* @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) external virtual requireContractAdmin {
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 (uint 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 `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function burn(address account, uint256 id, uint256 amount) external virtual requireContractAdmin {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = msgSender();
beforeTokenTransfer(operator, account, address(0), asSingletonArray(id), asSingletonArray(amount), "");
uint256 accountBalance = balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
balances[id][account] = accountBalance - amount;
emit TransferSingle(operator, account, 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 account, uint256[] memory ids, uint256[] memory amounts) external virtual requireContractAdmin {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = msgSender();
beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @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(to).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(to).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;
}
// Example functions that demonstrate how to call into this contract that holds state from
// another contract. Look in ~/interfaces/IDappState.sol for the interface definitions and
// in Dapp.sol for the actual calls into this contract.
/**
* @dev This is an EXAMPLE function that illustrates how functions in this contract can be
* called securely from another contract to READ state data. Using the Contract Access
* block will enable you to make your contract more secure by restricting which external
* contracts can call functions in this contract.
*/
function getContractOwner()
external
view
override
returns(address)
{
return contractOwner;
}
uint256 counter; // This is an example variable used only to demonstrate calling
// a function that writes state from an external contract. It and
// "incrementCounter" and "getCounter" functions can (should?) be deleted.
/**
* @dev This is an EXAMPLE function that illustrates how functions in this contract can be
* called securely from another contract to WRITE state data. Using the Contract Access
* block will enable you to make your contract more secure by restricting which external
* contracts can call functions in this contract.
*/
function incrementCounter
(
uint256 increment
)
external
override
// Enable the modifier below if using the Contract Access feature
// requireContractAuthorized
{
// NOTE: If another contract is calling this function, then msg.sender will be the address
// of the calling contract and NOT the address of the user who initiated the
// transaction. It is possible to get the address of the user, but this is
// spoofable and therefore not recommended.
require(increment > 0 && increment < 10, "Invalid increment value");
counter = counter.add(increment); // Demonstration of using SafeMath to add to a number
// While verbose, using SafeMath everywhere that you
// add/sub/div/mul will ensure your contract does not
// have weird overflow bugs.
}
/**
* @dev This is an another EXAMPLE function that illustrates how functions in this contract can be
* called securely from another contract to READ state data. Using the Contract Access
* block will enable you to make your contract more secure by restricting which external
* contracts can call functions in this contract.
*/
function getCounter()
external
view
override
returns(uint256)
{
return counter;
}
}
| Sets a new URI for all token types, by relying on the token type ID substitution mechanism 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. interpreted by clients as 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) external virtual requireContractAdmin {
uri = newuri;
}
| 7,214,174 |
./full_match/80001/0x6223daEbE1E15690B5443dEf4Ea36393A8B32960/sources/contracts/DID-NFT.sol | this function will return Encrypted VC URL from every dapps publickey to every nft id _tokenId is nft token id _publicKey is dapps public key/ | function getEncryptedVCURL(
uint256 _tokenId,
bytes memory _publicKey
) public view returns (string memory) {
require(
ownerOf(_tokenId) != address(0) &&
publicKeyUsed[_tokenId][_publicKey] == true &&
keccak256(bytes(optData[_tokenId][_publicKey])) !=
keccak256(bytes("")),
"!EXIST"
);
return
string(
abi.encodePacked(
_tokenId.toString(),
"/",
_publicKey.toHexString(),
".json"
)
);
}
| 837,689 |
pragma solidity ^0.4.21;
/// @title A mortality base contract for destroyable contracts.
/// @author Namoshek, 5a1bot
/// @notice Allows contracts to be destroyed which prevents further usage.
/// @dev The creator of a contract is also the owner. Ownership cannot be transferred. Only the owner can destroy a contract.
contract Mortal {
address owner;
/// @dev Sets the transaction sender as owner of the contract.
constructor() public {
owner = msg.sender;
}
event ContractOwnershipChanged(address indexed oldOwner, address indexed newOwner);
modifier isOwner {
require(msg.sender == owner);
_;
}
modifier noBalance {
require(address(this).balance == 0);
_;
}
/// @notice Can be used to destroy the contract.
/// @dev Can only be executed by the owner of the contract. The contract may not hold any Ether.
function kill() public isOwner noBalance {
selfdestruct(owner);
}
/// @notice Can be used to transfer ownership of the contract to another wallet.
/// @dev Can only be executed by the owner of the contract. Once the ownership is transfered, the old
/// owner does not have access to the contract anymore.
function transferOwnership(address newOwner) public isOwner {
owner = newOwner;
emit ContractOwnershipChanged(msg.sender, newOwner);
}
}
/// @title A coffee economy contract to manage customers, coffee makers and transactions in between them.
/// @author Namoshek, 5a1bot
/// @notice Offers functionality to add wallets as customer and coffee maker, to add coffee programs to coffee makers,
/// to buy tokens and to buy coffee for these tokens. Also token transfers in between parties are possible.
/// @dev Expects to be run in an environment with infinite Ether due to high transaction costs. Also expects some
/// trusted parties are available that will be able to trade real-world money for coffee tokens and the other way round.
contract CoffeeMakerEconomy is Mortal {
enum MachineType { Capsules, Pads, Filter, Pulver, FullyAutomatic, VendingMachine }
struct Location {
string descriptive;
string department;
string latitude;
string longitude;
}
struct MachineInfo {
MachineType machineType;
string description;
}
struct CoffeeProgram {
string name;
uint price;
}
struct CoffeeMaker {
bool exists;
address owner;
string name;
Location location;
MachineInfo machineInfo;
mapping(uint8 => CoffeeProgram) programs;
uint8 programCounter;
}
struct Customer {
bool exists;
string name;
string department;
string telephone;
string email;
}
/// @dev Sets the transaction sender as the initially only available authorized exchange party.
constructor() public {
authorizedExchangeWallets[msg.sender] = true;
}
uint constant tokensPerEther = 100;
mapping(address => uint) tokenStore;
mapping(address => CoffeeMaker) private coffeeMakers;
mapping(address => Customer) private customers;
mapping(address => bool) private authorizedExchangeWallets;
event ExchangeWalletAuthorized(address indexed wallet);
event CustomerAdded(address indexed wallet);
event CoffeeMakerAdded(address indexed wallet, address indexed owner);
event CoffeeMakerProgramAdded(address indexed coffeeMaker, string indexed name, uint indexed price);
event CoffeeBought(address indexed coffeeMaker, uint8 indexed program, uint8 indexed amount);
event TokensBought(address indexed customer, uint indexed tokens);
event TokensSold(address indexed customer, uint indexed tokens);
event TokensTransfered(address indexed sender, address indexed recipient, uint indexed tokens);
modifier isAuthorizedWallet {
require(authorizedExchangeWallets[msg.sender] == true);
_;
}
modifier walletIsKnown(address wallet) {
require(customers[wallet].exists == true || coffeeMakers[wallet].exists == true);
_;
}
/// @notice Adds a wallet as authorized exchange wallet, which allows the wallet to trade real-world money for tokens.
/// @dev A wallet should only be authorized as exchange wallet if the owner is trusted. Otherwise, an infinite amount of
/// coffee tokens could be created.
/// @param wallet The wallet to be added as authorized exchange wallet.
function addAuthorizedExchangeWallet(address wallet) public {
require(msg.sender == owner);
authorizedExchangeWallets[wallet] = true;
emit ExchangeWalletAuthorized(wallet);
}
/// @notice Adds a customer for the given wallet with some basic personal information like name and contact details.
/// @dev This function may only be called if no customer exists yet for the given wallet.
/// @param wallet The wallet to be added as customer.
/// @param name The customers name.
/// @param telephone The customers telephone number.
/// @param email The customers email address.
function addCustomer(address wallet, string name, string department, string telephone, string email) public {
require(wallet != 0x0);
require(customers[wallet].exists == false);
Customer memory details;
details.exists = true;
details.name = name;
details.department = department;
details.telephone = telephone;
details.email = email;
customers[wallet] = details;
emit CustomerAdded(wallet);
}
/// @notice Adds a coffee maker for the given wallet with some basic machine information like location and machine type.
/// @dev This function may only be called if no coffee maker exists yet for the given wallet. The message sender must be a customer.
/// @param wallet The wallet to be added as coffee maker.
/// @param name The coffee makers name.
/// @param locDescriptive A description of the coffee makers location.
/// @param locDepartment The department name where the coffee maker is located.
/// @param locLatitude The latitude of the coffee makers location.
/// @param locLongitude The longitude of the coffee makers location.
/// @param infoMachineType The machine type of the coffee maker.
/// @param infoDescription An additional description.
function addCoffeemaker(
address wallet,
string name,
string locDescriptive,
string locDepartment,
string locLatitude,
string locLongitude,
MachineType infoMachineType,
string infoDescription
) public {
require(wallet != 0x0);
require(coffeeMakers[wallet].exists == false);
require(customers[msg.sender].exists == true);
CoffeeMaker memory details;
details.exists = true;
details.owner = msg.sender;
details.name = name;
details.location.descriptive = locDescriptive;
details.location.department = locDepartment;
details.location.latitude = locLatitude;
details.location.longitude = locLongitude;
details.machineInfo.machineType = infoMachineType;
details.machineInfo.description = infoDescription;
coffeeMakers[wallet] = details;
emit CoffeeMakerAdded(wallet, details.owner);
}
/// @notice Adds a coffee program to an existing coffee maker.
/// @dev This function may only be called for existing coffee makers. Only 256 programs per coffee maker are possible.
/// @param coffeeMaker The address of a coffee maker.
/// @param name The coffee program name (e.g. Espresso).
/// @param price The price for the coffee program.
function addCoffeeMakerProgram(address coffeeMaker, string name, uint price) public {
require(coffeeMakers[coffeeMaker].exists == true);
require(coffeeMakers[coffeeMaker].programCounter < 256);
uint8 programCounter = coffeeMakers[coffeeMaker].programCounter;
coffeeMakers[coffeeMaker].programs[programCounter] = CoffeeProgram({name: name, price: price});
coffeeMakers[coffeeMaker].programCounter += 1;
emit CoffeeMakerProgramAdded(coffeeMaker, name, price);
}
/// @notice Sends Ether to the contract and adds an equal amount of tokens to the buyers wallet.
/// @dev At least one Ether has to be sent to this function. Also the tokens are calculated based on the sent Ether,
/// but with a tokens-per-ether factor taken into account.
/// @param buyer The address of the buyers wallet. To this wallet, the tokens will be added.
/// @return The amount of tokens the buyer received.
function buyTokens(address buyer) public payable isAuthorizedWallet walletIsKnown(buyer) returns (uint receivedTokens) {
require(msg.value >= 1 ether);
uint etherValue = msg.value / (1 ether);
require(etherValue * (1 ether) == msg.value);
uint tokens = etherValue * tokensPerEther;
tokenStore[buyer] += tokens;
emit TokensBought(buyer, tokens);
return tokens;
}
/// @notice Sends Ether from the contract to the message sender and removes an equal amount of tokens from the sellers wallet.
/// @dev If less tokens than required for selling are available, all available tokens will be sold.
/// @param seller The address of the sellers wallet. From this wallet, the tokens will be subtracted.
/// @param tokens The amount of tokens to sell.
/// @return The amount of tokens that have actually be sold.
function sellTokens(address seller, uint tokens) public isAuthorizedWallet walletIsKnown(seller) returns (uint soldTokens) {
require(tokens > 0);
require(tokenStore[seller] > 0);
uint tokensToSell = tokens;
if (tokenStore[seller] < tokensToSell) {
tokensToSell = tokenStore[seller];
}
tokenStore[seller] -= tokensToSell;
uint weiValue = (tokensToSell / tokensPerEther) * (1 ether);
msg.sender.transfer(weiValue);
emit TokensSold(seller, tokensToSell);
return tokensToSell;
}
/// @notice Sends tokens from one wallet to another.
/// @dev The message sender is the source wallet. The function can only be executed for known wallets.
/// @param receiver The wallet to receive the sent tokens.
/// @param tokens The amount of tokens to transfer.
/// @return The amount of tokens that have actually be transferred.
function transferTokens(
address receiver,
uint tokens
) public walletIsKnown(receiver) walletIsKnown(msg.sender) returns (uint transferedTokens) {
require(tokens > 0);
require(tokenStore[msg.sender] > 0);
uint tokensToTransfer = tokens;
if (tokenStore[msg.sender] < tokensToTransfer) {
tokensToTransfer = tokenStore[msg.sender];
}
tokenStore[msg.sender] -= tokensToTransfer;
tokenStore[receiver] += tokensToTransfer;
emit TokensTransfered(msg.sender, receiver, tokensToTransfer);
return tokensToTransfer;
}
/// @notice Buys a coffee with tokens using the given program and amount.
/// @dev Requires enough tokens to be available to buy the coffee program the given amount of times.
/// @param coffeeMaker The coffee maker at which coffee is bought.
/// @param program The program which is selected.
/// @param amount The number of times the selected program is bought.
/// @return The amount of tokens that have been billed.
function buyCoffee(address coffeeMaker, uint8 program, uint8 amount) public returns (uint transferedTokens) {
require(customers[msg.sender].exists == true);
require(coffeeMakers[coffeeMaker].exists == true);
require(coffeeMakers[coffeeMaker].programCounter > program);
uint totalPrice = coffeeMakers[coffeeMaker].programs[program].price * amount;
require(tokenStore[msg.sender] >= totalPrice);
tokenStore[msg.sender] -= totalPrice;
tokenStore[coffeeMaker] += totalPrice;
emit CoffeeBought(coffeeMaker, program, amount);
return amount;
}
/// @notice Getter for the tokens on a wallet.
/// @dev Does not perform any kind of access control.
/// @param wallet The wallet to check the token balance for.
/// @return The amount of tokens available for the given wallet.
function getTokens(address wallet) public view returns (uint tokens) {
return tokenStore[wallet];
}
/// @notice Getter to check if a wallet is registered as customer.
/// @dev Does not perform any kind of access control.
/// @param wallet The wallet to check for a customer registration.
/// @return If a customer exists for the given wallet or not.
function isCustomer(address wallet) public view returns (bool trueOrFalse) {
return customers[wallet].exists;
}
/// @notice Getter to check if a wallet is registered as coffee maker.
/// @dev Does not perform any kind of access control.
/// @param wallet The wallet to check for a coffee maker registration.
/// @return If a coffee maker exists for the given wallet or not.
function isCoffeeMaker(address wallet) public view returns (bool trueOrFalse) {
return coffeeMakers[wallet].exists;
}
/// @notice Getter to check if a wallet is an authorized exchange wallet.
/// @dev Does not perform any kind of access control.
/// @param wallet The wallet to check for being an authorized exchange wallet.
/// @return If the given wallt is an authorized exchange wallet or not.
function isAuthorizedExchangeWallet(address wallet) public view returns (bool trueOrFalse) {
return authorizedExchangeWallets[wallet];
}
/// @notice Getter for customer data on a wallet.
/// @dev Does not perform any kind of access control. But does only work for known wallets.
/// @param wallet The wallet to check for customer data.
/// @return {
/// "name": "The customers name.",
/// "department": "The customers department.",
/// "telephone": "The customers telephone number.",
/// "email": "The customers email address."
/// }
function getCustomerData(address wallet) public view returns (string name, string department,
string telephone, string email) {
require(customers[wallet].exists == true);
Customer memory customer = customers[wallet];
return (customer.name, customer.department, customer.telephone, customer.email);
}
/// @notice Getter for coffee maker data on a wallet.
/// @dev Does not perform any kind of access control. But does only work for known wallets.
/// @param wallet The wallet to check for coffee maker data.
/// @return {
/// "owner": "Address of the owner.",
/// "name": "The coffee makers name.",
/// "descriptiveLocation": "A description of the coffee makers location.",
/// "department": "The department where the coffee maker is located at.",
/// "latitude": "The latitude of the coffee makers location.",
/// "longitude": "The longitude of the coffee makers location.",
/// "machineType": "The machine type of the coffee maker.",
/// "description": "Additional information."
/// }
function getCoffeeMakerData(address wallet) public view returns (address owner, string name,
string descriptiveLocation, string department, string latitude, string longitude,
MachineType machineType, string description) {
require(coffeeMakers[wallet].exists == true);
CoffeeMaker memory coffeeMaker = coffeeMakers[wallet];
return (
coffeeMaker.owner,
coffeeMaker.name,
coffeeMaker.location.descriptive,
coffeeMaker.location.department,
coffeeMaker.location.latitude,
coffeeMaker.location.longitude,
coffeeMaker.machineInfo.machineType,
coffeeMaker.machineInfo.description
);
}
/// @notice Getter for the number of available programs of a coffee maker.
/// @dev Does not perform any kind of access control.
/// @param wallet The coffee maker to check for programs.
/// @return The number of available programs.
function getCoffeeMakerProgramCount(address wallet) public view returns (uint8 programCount) {
return coffeeMakers[wallet].programCounter;
}
/// @notice Getter for program details of a coffee maker.
/// @dev Does not perform any kind of access control. But does only work for known coffee makers.
/// @param wallet The coffee maker to check for a program.
/// @param program The program to get additional information for.
/// @return {
/// "name": "The name of the coffee program (e.g. Espresso).",
/// "price": "The price of the coffee program."
/// }
function getCoffeeMakerProgramDetails(address wallet, uint8 program) public view returns (string name, uint price) {
return (coffeeMakers[wallet].programs[program].name, coffeeMakers[wallet].programs[program].price);
}
}
| Getter for program details of a coffee maker. Does not perform any kind of access control. But does only work for known coffee makers. wallet The coffee maker to check for a program. program The program to get additional information for. return { "name": "The name of the coffee program (e.g. Espresso).", "price": "The price of the coffee program." } | function getCoffeeMakerProgramDetails(address wallet, uint8 program) public view returns (string name, uint price) {
return (coffeeMakers[wallet].programs[program].name, coffeeMakers[wallet].programs[program].price);
}
| 1,799,755 |
./full_match/80001/0x5441Ff3B88f85d8BCb50A92e192e16cF07B93651/sources/SentiPrice.sol | Check that the calling account has the ORDERBOOK_ROLE | function addOrderbookByAdmin(address _orderbook) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Not an admin");
grantRole(ORDERBOOK_ROLE, _orderbook);
}
| 5,680,661 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
/// @title EthicOnChainLib
/// @author Lahcen E. Dev / Jérôme Gauthier
/// @notice EthicOnChain library to manage struct and getters
library EthicOnChainLib {
struct NPO {
uint npoId;
address npoErc20Address;
string denomination;
string postalAddress;
string object;
string npoType;
uint[] projectIds;
uint[] withdrawalIds;
}
struct Donor {
uint donorId;
address donorErc20Address;
string name;
string surName;
string postalAddress;
uint[] donationIds;
}
struct Project {
uint projectId; // primary key
uint startDate;
uint endDate;
uint campaignStartDate;
uint campaignDurationInDays;
uint minAmount;
uint maxAmount;
uint projectBalance;
uint projectTotalDonations;
address npoErc20Address;
ProjectCause cause;
ProjectStatus status;
string title;
string description;
string geographicalArea;
uint[] donationIds;
uint[] withdrawalIds;
}
struct Donation {
uint donationId; // primary key
uint projectId;
uint donorId;
uint donationDate;
uint donationAmount;
}
struct Withdrawal {
uint withdrawalId; // primary key
uint projectId;
uint amount;
uint withdrawalDate;
string title;
string description;
}
enum ProjectCause {
LutteContreLaPauvreteEtExclusion,
EnvironnementEtLesAnimaux,
Education,
ArtEtLaCulture,
SanteEtLaRecherche,
DroitsDeLHomme,
InfrastructureRoutiere
}
enum ProjectStatus {
Undefined,
UnderCreation,
UnderCampaign,
InProgress,
Cancelled,
Closed
}
/// @dev Get an NPO via its erc20 address
/// @param _npoAddresses mapping of NPO addresses to NPO Struct
/// @param _npoErc20Address erc20 address of the NPO Struct
/// @return returns the corresponding NPO struct
function libGetNpo(mapping (address => NPO) storage _npoAddresses, address _npoErc20Address) external view returns(NPO memory) {
return _npoAddresses[_npoErc20Address];
}
/// @dev Get an NPO via its id
/// @param _npoAddresses mapping of NPO addresses to NPO Struct
/// @param _npoMap mapping of NPO id to NPO Struct
/// @param _npoId id of the NPO
/// @return returns the corresponding NPO struct
function libGetNpoByIndex(mapping (address => NPO) storage _npoAddresses, mapping (uint => address) storage _npoMap, uint _npoId) internal view returns(NPO memory) {
return _npoAddresses[_npoMap[_npoId]];
}
/// @dev Get all NPOs
/// @param _npoAddresses mapping of NPO addresses to NPO Struct
/// @param _npoMap mapping of NPO id to NPO Struct
/// @param _npoCount current index for NPO = total count of NPOs
/// @return returns an array of all NPOs
function libGetNpos(mapping (address => NPO) storage _npoAddresses, mapping (uint => address) storage _npoMap, uint _npoCount) external view returns(NPO [] memory) {
uint arraySize = _npoCount;
NPO [] memory result= new NPO[](arraySize);
for(uint i; i < arraySize; i++) {
result[i] = libGetNpoByIndex(_npoAddresses, _npoMap, i);
}
return result;
}
/// @dev get a Donor via its erc20 address
/// @param _donorAddresses mapping of Donors addresses to Donor Struct
/// @param _donorErc20Address erc20 address of the Donor
/// @return returns the corresponding Donor struct
function libGetDonor(mapping (address => Donor) storage _donorAddresses, address _donorErc20Address) external view returns(Donor memory) {
return _donorAddresses[_donorErc20Address];
}
/// @dev get a Donor via its id
/// @param _donorAddresses mapping of Donors addresses to Donor Struct
/// @param _donorMap mapping of Donor id to Donor Struct
/// @param _donorId id of the Donor
/// @return returns the corresponding Donor struct
function libGetDonorByIndex(mapping (address => Donor) storage _donorAddresses, mapping (uint => address) storage _donorMap, uint _donorId) internal view returns(Donor memory) {
return _donorAddresses[_donorMap[_donorId]];
}
/// @dev get all Donors
/// @param _donorAddresses mapping of Donors addresses to Donor Struct
/// @param _donorMap mapping of Donor id to Donor Struct
/// @param _donorCount current index for Donor = total count of Donors
/// @return returns an array of all Donors
function libGetDonors(mapping (address => Donor) storage _donorAddresses, mapping (uint => address) storage _donorMap, uint _donorCount) external view returns(Donor [] memory) {
uint arraySize = _donorCount;
Donor [] memory result = new Donor[](arraySize);
for(uint i; i < arraySize; i++) {
result[i] = libGetDonorByIndex(_donorAddresses, _donorMap, i);
}
return result;
}
/// @dev Returns a single Project
/// @param _projectMap mapping of Project id to Project Struct
/// @param _projectId project unique id
/// @return the Project struct instance corresponding to _projectId
function libGetProject(mapping (uint => Project) storage _projectMap, uint _projectId) public view returns(Project memory) {
Project memory returnedProject;
returnedProject = _projectMap[_projectId];
returnedProject.status = getProjectStatus(returnedProject);
return returnedProject;
}
/// @dev get all projects
/// @param _projectMap mapping of Project id to Project Struct
/// @param _projectCount current index for Project = total count of Projects
/// @return returns an array of all Project
function libGetProjects(mapping (uint => Project) storage _projectMap, uint _projectCount) external view returns(Project [] memory) {
uint arraySize = _projectCount;
Project [] memory result= new Project[](arraySize);
for(uint i; i < arraySize; i++) {
result[i] = libGetProject(_projectMap, i);
}
return result;
}
/// @dev Allows to know all the projects of an NPO
/// @param _npoAddresses mapping of NPO addresses to NPO Struct
/// @param _projectMap mapping of Project id to Project Struct
/// @param _addressNpo ERC20 address of the NPO
/// @return Returns an array of projects
function libGetProjectsPerNpo(mapping (address => NPO) storage _npoAddresses, mapping (uint => Project) storage _projectMap, address _addressNpo) external view returns(Project [] memory ) {
uint arraySize = _npoAddresses[_addressNpo].projectIds.length;
Project [] memory result = new Project[](arraySize);
for(uint i; i < arraySize; i++) {
uint index = _npoAddresses[_addressNpo].projectIds[i];
result[i] = libGetProject(_projectMap, index);
}
return result;
}
/// @dev get Donation by id
/// @param _donationMap mapping of Donation id to Donation Struct
/// @param _id index pour retrouver la donation a retourner
/// @return a struct donation
function libGetDonation(mapping (uint => Donation) storage _donationMap, uint _id) public view returns(Donation memory) {
return _donationMap[_id];
}
/// @dev Allows to know all the donations of a single donor
/// @param _donorAddresses mapping of Donors addresses to Donor Struct
/// @param _donationMap mapping of Donation id to Donation Struct
/// @param _donorAddress id which represents the index
/// @return Returns an array of all donation of a single donor
function libGetDonationPerDonor(mapping (address => Donor) storage _donorAddresses, mapping (uint => Donation) storage _donationMap, address _donorAddress) external view returns(Donation [] memory ) {
uint arraySize = _donorAddresses[_donorAddress].donationIds.length;
Donation [] memory result= new Donation[](arraySize);
for(uint i; i < arraySize; i++) {
uint index = _donorAddresses[_donorAddress].donationIds[i];
result[i] = libGetDonation(_donationMap, index);
}
return result;
}
/// @dev list all the donations made in the contract, whatever the Donor and the NPO
/// @param _donationMap mapping of Donation id to Donation Struct
/// @param _donationCount total number of donations
/// @return Returns an array of all donation of a single donor
function libGetDonations(mapping (uint => Donation) storage _donationMap, uint _donationCount) public view returns(Donation [] memory ) {
uint arraySize = _donationCount;
Donation [] memory result = new Donation[](arraySize);
for(uint i; i < arraySize; i++) {
result[i] = libGetDonation(_donationMap, i);
}
return result;
}
/// @dev get Withdrawal by id
/// @param _withdrawalMap mapping of Withdrawal id to Withdrawal Struct
/// @param _id index pour retrouver le withdrawal a retourner
/// @return a struct retait
function libGetWithdrawal(mapping (uint => Withdrawal) storage _withdrawalMap, uint _id) public view returns(Withdrawal memory) {
return _withdrawalMap[_id];
}
/// @dev Allows to know all the donations of a single donor
/// @param _npoAddresses mapping of NPO addresses to NPO Struct
/// @param _withdrawalMap mapping of Withdrawal id to Withdrawal Struct
/// @param _addressNpo id which represents the index
/// @return Returns an array of all donation of a single donor
function libGetWithdrawalPerNpo(mapping (address => NPO) storage _npoAddresses, mapping (uint => Withdrawal) storage _withdrawalMap, address _addressNpo) external view returns(Withdrawal [] memory ) {
uint arraySize = _npoAddresses[_addressNpo].withdrawalIds.length;
Withdrawal [] memory result= new Withdrawal[](arraySize);
for(uint i; i < arraySize; i++) {
uint index = _npoAddresses[_addressNpo].withdrawalIds[i];
result[i] = libGetWithdrawal(_withdrawalMap, index);
}
return result;
}
/// @dev get the project status
/// @param _project Project
/// @return _status the Project status based on Project information
function getProjectStatus(Project memory _project) private view returns(ProjectStatus _status) {
ProjectStatus returnedStatus;
uint campaignEndDate = _project.campaignStartDate + _project.campaignDurationInDays * 1 days;
// Under Creation
if (_project.campaignStartDate > block.timestamp) {
returnedStatus = ProjectStatus.UnderCreation;
}
// Under Campaign
else if (_project.campaignStartDate <= block.timestamp && block.timestamp <= campaignEndDate) {
returnedStatus = ProjectStatus.UnderCampaign;
}
// In Progress
else if (block.timestamp > campaignEndDate && _project.projectTotalDonations >= _project.minAmount &&
_project.startDate <= block.timestamp && block.timestamp <= _project.endDate) {
returnedStatus = ProjectStatus.InProgress;
}
// Cancelled
else if (block.timestamp > campaignEndDate && _project.projectTotalDonations < _project.minAmount) {
returnedStatus = ProjectStatus.Cancelled;
}
// Closed
else if (block.timestamp > _project.endDate && _project.projectTotalDonations >= _project.minAmount) {
returnedStatus = ProjectStatus.Closed;
}
// otherwise Undefined
else {
returnedStatus = ProjectStatus.Undefined;
}
return returnedStatus;
}
}
| Allows to know all the donations of a single donor _donorAddresses mapping of Donors addresses to Donor Struct _donationMap mapping of Donation id to Donation Struct _donorAddress id which represents the index return Returns an array of all donation of a single donor | function libGetDonationPerDonor(mapping (address => Donor) storage _donorAddresses, mapping (uint => Donation) storage _donationMap, address _donorAddress) external view returns(Donation [] memory ) {
uint arraySize = _donorAddresses[_donorAddress].donationIds.length;
Donation [] memory result= new Donation[](arraySize);
for(uint i; i < arraySize; i++) {
uint index = _donorAddresses[_donorAddress].donationIds[i];
result[i] = libGetDonation(_donationMap, index);
}
return result;
}
| 6,474,860 |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./StateUtils.sol";
import "./interfaces/IGetterUtils.sol";
/// @title Contract that implements getters
abstract contract GetterUtils is StateUtils, IGetterUtils {
string private constant CHECKPOINT_NOT_FOUND = "API3DAO.GetterUtils: Value cannot be found after provided checkpoint";
/// @notice Called to get the voting power of a user at a checkpoint,
/// closest to the provided block
/// @dev This method is used to implement the MiniMe interface for the
/// Api3Voting app
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Voting power of the user at the block
function balanceOfAt(
address userAddress,
uint256 _block
)
public
view
override
returns(uint256)
{
// Users that delegate have no voting power
if (getUserDelegateAt(userAddress, _block) != address(0))
{
return 0;
}
uint256 userSharesThen = userSharesAt(userAddress, _block);
uint256 delegatedToUserThen = getReceivedDelegationAt(userAddress, _block);
return userSharesThen + delegatedToUserThen;
}
/// @notice Called to get the current voting power of a user
/// @dev This method is used to implement the MiniMe interface for the
/// Api3Voting app
/// @param userAddress User address
/// @return Current voting power of the user
function balanceOf(address userAddress)
public
view
override
returns(uint256)
{
return balanceOfAt(userAddress, block.number);
}
/// @notice Called to get the total voting power one block ago
/// @dev This method is used to implement the MiniMe interface for the
/// Api3Voting app
/// @return Total voting power one block ago
function totalSupplyOneBlockAgo()
public
view
override
returns(uint256)
{
return totalSharesOneBlockAgo();
}
/// @notice Called to get the current total voting power
/// @dev This method is used to implement the MiniMe interface for the
/// Aragon Voting app
/// @return Current total voting power
function totalSupply()
public
view
override
returns(uint256)
{
return totalShares();
}
/// @notice Called to get the pool shares of a user at a checkpoint,
/// closest to the provided block
/// @dev Starts from the most recent value in `user.shares` and searches
/// backwards one element at a time
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Pool shares of the user at the block
function userSharesAt(
address userAddress,
uint256 _block
)
public
view
override
returns(uint256)
{
return getValueAt(users[userAddress].shares, _block, 0);
}
/// @notice Called to get the current pool shares of a user
/// @param userAddress User address
/// @return Current pool shares of the user
function userShares(address userAddress)
public
view
override
returns(uint256)
{
return userSharesAt(userAddress, block.number);
}
/// @notice Called to get the pool shares of a user at checkpoint,
/// closest to specific block using binary search
/// @dev This method is not used by the current iteration of the DAO/pool
/// and is implemented for future external contracts to use to get the user
/// shares at an arbitrary block.
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Pool shares of the user at the block
function userSharesAtWithBinarySearch(
address userAddress,
uint256 _block
)
external
view
override
returns(uint256)
{
return getValueAtWithBinarySearch(
users[userAddress].shares,
_block,
0
);
}
/// @notice Called to get the current staked tokens of the user
/// @param userAddress User address
/// @return Current staked tokens of the user
function userStake(address userAddress)
public
view
override
returns(uint256)
{
return userShares(userAddress) * totalStake / totalShares();
}
/// @notice Called to get the voting power delegated to a user at a
/// checkpoint, closest to specific block
/// @dev `user.delegatedTo` cannot have grown more than 1000 checkpoints
/// in the last epoch due to `proposalVotingPowerThreshold` having a lower
/// limit of 0.1%.
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Voting power delegated to the user at the block
function getReceivedDelegationAt(
address userAddress,
uint256 _block
)
public
view
override
returns(uint256)
{
// Binary searching a 1000-long array takes up to 10 storage reads
// (2^10 = 1024). If we approximate the average number of reads
// required to be 5 and consider that it is much more likely for the
// value we are looking for will be at the end of the array (because
// not many proposals will be made per epoch), it is preferable to do
// a linear search at the end of the array if possible. Here, the
// length of "the end of the array" is specified to be 5 (which was the
// expected number of iterations we will need for a binary search).
uint256 maximumLengthToLinearSearch = 5;
// If the value we are looking for is not among the last
// `maximumLengthToLinearSearch`, we will fall back to binary search.
// Here, we will only search through the last 1000 checkpoints because
// `user.delegatedTo` cannot have grown more than 1000 checkpoints in
// the last epoch due to `proposalVotingPowerThreshold` having a lower
// limit of 0.1%.
uint256 maximumLengthToBinarySearch = 1000;
Checkpoint[] storage delegatedTo = users[userAddress].delegatedTo;
if (delegatedTo.length < maximumLengthToLinearSearch) {
return getValueAt(delegatedTo, _block, 0);
}
uint256 minimumCheckpointIndexLinearSearch = delegatedTo.length - maximumLengthToLinearSearch;
if (delegatedTo[minimumCheckpointIndexLinearSearch].fromBlock < _block) {
return getValueAt(delegatedTo, _block, minimumCheckpointIndexLinearSearch);
}
// It is very unlikely for the method to not have returned until here
// because it means there have been `maximumLengthToLinearSearch`
// proposals made in the current epoch.
uint256 minimumCheckpointIndexBinarySearch = delegatedTo.length > maximumLengthToBinarySearch
? delegatedTo.length - maximumLengthToBinarySearch
: 0;
// The below will revert if the value being searched is not within the
// last `minimumCheckpointIndexBinarySearch` (which is not possible if
// `_block` is the snapshot block of an open vote of Api3Voting,
// because its vote duration is `EPOCH_LENGTH`).
return getValueAtWithBinarySearch(delegatedTo, _block, minimumCheckpointIndexBinarySearch);
}
/// @notice Called to get the current voting power delegated to a user
/// @param userAddress User address
/// @return Current voting power delegated to the user
function userReceivedDelegation(address userAddress)
public
view
override
returns(uint256)
{
return getReceivedDelegationAt(userAddress, block.number);
}
/// @notice Called to get the delegate of the user at a checkpoint,
/// closest to specified block
/// @dev Starts from the most recent value in `user.delegates` and
/// searches backwards one element at a time. If `_block` is within
/// `EPOCH_LENGTH`, this call is guaranteed to find the value among
/// the last 2 elements because a user cannot update delegate more
/// frequently than once an `EPOCH_LENGTH`.
/// @param userAddress User address
/// @param _block Block number
/// @return Delegate of the user at the specific block
function getUserDelegateAt(
address userAddress,
uint256 _block
)
public
view
override
returns(address)
{
AddressCheckpoint[] storage delegates = users[userAddress].delegates;
for (uint256 i = delegates.length; i > 0; i--)
{
if (delegates[i - 1].fromBlock <= _block)
{
return delegates[i - 1]._address;
}
}
return address(0);
}
/// @notice Called to get the current delegate of the user
/// @param userAddress User address
/// @return Current delegate of the user
function getUserDelegate(address userAddress)
public
view
override
returns(address)
{
return getUserDelegateAt(userAddress, block.number);
}
/// @notice Called to get the current locked tokens of the user
/// @param userAddress User address
/// @return locked Current locked tokens of the user
function getUserLocked(address userAddress)
public
view
override
returns(uint256 locked)
{
Checkpoint[] storage _userShares = users[userAddress].shares;
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
uint256 oldestLockedEpoch = currentEpoch - REWARD_VESTING_PERIOD > genesisEpoch
? currentEpoch - REWARD_VESTING_PERIOD + 1
: genesisEpoch + 1;
if (_userShares.length == 0)
{
return 0;
}
uint256 indUserShares = _userShares.length - 1;
for (
uint256 indEpoch = currentEpoch;
indEpoch >= oldestLockedEpoch;
indEpoch--
)
{
Reward storage lockedReward = epochIndexToReward[indEpoch];
if (lockedReward.atBlock != 0)
{
for (; indUserShares >= 0; indUserShares--)
{
Checkpoint storage userShare = _userShares[indUserShares];
if (userShare.fromBlock <= lockedReward.atBlock)
{
locked += lockedReward.amount * userShare.value / lockedReward.totalSharesThen;
break;
}
}
}
}
}
/// @notice Called to get the details of a user
/// @param userAddress User address
/// @return unstaked Amount of unstaked API3 tokens
/// @return vesting Amount of API3 tokens locked by vesting
/// @return unstakeShares Shares scheduled to unstake
/// @return unstakeAmount Amount scheduled to unstake
/// @return unstakeScheduledFor Time unstaking is scheduled for
/// @return mostRecentProposalTimestamp Time when the user made their most
/// recent proposal
/// @return mostRecentVoteTimestamp Time when the user cast their most
/// recent vote
/// @return mostRecentDelegationTimestamp Time when the user made their
/// most recent delegation
/// @return mostRecentUndelegationTimestamp Time when the user made their
/// most recent undelegation
function getUser(address userAddress)
external
view
override
returns(
uint256 unstaked,
uint256 vesting,
uint256 unstakeShares,
uint256 unstakeAmount,
uint256 unstakeScheduledFor,
uint256 mostRecentProposalTimestamp,
uint256 mostRecentVoteTimestamp,
uint256 mostRecentDelegationTimestamp,
uint256 mostRecentUndelegationTimestamp
)
{
User storage user = users[userAddress];
unstaked = user.unstaked;
vesting = user.vesting;
unstakeShares = user.unstakeShares;
unstakeAmount = user.unstakeAmount;
unstakeScheduledFor = user.unstakeScheduledFor;
mostRecentProposalTimestamp = user.mostRecentProposalTimestamp;
mostRecentVoteTimestamp = user.mostRecentVoteTimestamp;
mostRecentDelegationTimestamp = user.mostRecentDelegationTimestamp;
mostRecentUndelegationTimestamp = user.mostRecentUndelegationTimestamp;
}
/// @notice Called to get the value of a checkpoint array closest to
/// the specific block
/// @param checkpoints Checkpoints array
/// @param _block Block number for which the query is being made
/// @return Value of the checkpoint array at the block
function getValueAt(
Checkpoint[] storage checkpoints,
uint256 _block,
uint256 minimumCheckpointIndex
)
internal
view
returns(uint256)
{
uint256 i = checkpoints.length;
for (; i > minimumCheckpointIndex; i--)
{
if (checkpoints[i - 1].fromBlock <= _block)
{
return checkpoints[i - 1].value;
}
}
// Revert if the value being searched for comes before
// `minimumCheckpointIndex`
require(i == 0, CHECKPOINT_NOT_FOUND);
return 0;
}
/// @notice Called to get the value of the checkpoint array closest to the
/// specific block
/// @dev Adapted from
/// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431
/// Allows the caller to specify the portion of the array that will be
/// searched. This allows us to avoid having to search arrays that can grow
/// unboundedly.
/// @param checkpoints Checkpoint array
/// @param _block Block number for which the query is being made
/// @param minimumCheckpointIndex Index of the earliest checkpoint that may
/// be keeping the value we are looking for
/// @return Value of the checkpoint array at `_block`
function getValueAtWithBinarySearch(
Checkpoint[] storage checkpoints,
uint256 _block,
uint256 minimumCheckpointIndex
)
internal
view
returns(uint256)
{
if (checkpoints.length == 0)
return 0;
assert(checkpoints.length > minimumCheckpointIndex);
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length - 1].fromBlock) {
return checkpoints[checkpoints.length - 1].value;
}
// Revert if the value being searched for comes before
// `minimumCheckpointIndex`
if (_block < checkpoints[minimumCheckpointIndex].fromBlock) {
if (minimumCheckpointIndex == 0) {
return 0;
}
else {
revert(CHECKPOINT_NOT_FOUND);
}
}
// Binary search of the value in the array
uint min = minimumCheckpointIndex;
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
}
| Called to get the value of the checkpoint array closest to the specific block Adapted from https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.solL431 Allows the caller to specify the portion of the array that will be searched. This allows us to avoid having to search arrays that can grow unboundedly. checkpoints Checkpoint array _block Block number for which the query is being made minimumCheckpointIndex Index of the earliest checkpoint that may be keeping the value we are looking for return Value of the checkpoint array at `_block` Shortcut for the actual value Revert if the value being searched for comes before `minimumCheckpointIndex` | function getValueAtWithBinarySearch(
Checkpoint[] storage checkpoints,
uint256 _block,
uint256 minimumCheckpointIndex
)
internal
view
returns(uint256)
{
if (checkpoints.length == 0)
return 0;
assert(checkpoints.length > minimumCheckpointIndex);
if (_block >= checkpoints[checkpoints.length - 1].fromBlock) {
return checkpoints[checkpoints.length - 1].value;
}
if (_block < checkpoints[minimumCheckpointIndex].fromBlock) {
if (minimumCheckpointIndex == 0) {
return 0;
}
else {
revert(CHECKPOINT_NOT_FOUND);
}
}
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
max = mid - 1;
}
}
return checkpoints[min].value;
}
| 13,041,913 |
pragma solidity 0.4.18;
// File: contracts/ERC20Interface.sol
// https://github.com/ethereum/EIPs/issues/20
interface ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf(address _owner) public view returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint remaining);
function decimals() public view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
// File: contracts/KyberReserveInterface.sol
/// @title Kyber Reserve contract
interface KyberReserveInterface {
function trade(
ERC20 srcToken,
uint srcAmount,
ERC20 destToken,
address destAddress,
uint conversionRate,
bool validate
)
public
payable
returns(bool);
function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint);
}
// File: contracts/Utils.sol
/// @title Kyber constants contract
contract Utils {
ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant internal PRECISION = (10**18);
uint constant internal MAX_QTY = (10**28); // 10B tokens
uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH
uint constant internal MAX_DECIMALS = 18;
uint constant internal ETH_DECIMALS = 18;
mapping(address=>uint) internal decimals;
function setDecimals(ERC20 token) internal {
if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
else decimals[token] = token.decimals();
}
function getDecimals(ERC20 token) internal view returns(uint) {
if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
uint tokenDecimals = decimals[token];
// technically, there might be token with decimals 0
// moreover, very possible that old tokens have decimals 0
// these tokens will just have higher gas fees.
if(tokenDecimals == 0) return token.decimals();
return tokenDecimals;
}
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(srcQty <= MAX_QTY);
require(rate <= MAX_RATE);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(dstQty <= MAX_QTY);
require(rate <= MAX_RATE);
//source quantity is rounded up. to avoid dest quantity being too low.
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}
}
// File: contracts/Utils2.sol
contract Utils2 is Utils {
/// @dev get the balance of a user.
/// @param token The token type
/// @return The balance
function getBalance(ERC20 token, address user) public view returns(uint) {
if (token == ETH_TOKEN_ADDRESS)
return user.balance;
else
return token.balanceOf(user);
}
function getDecimalsSafe(ERC20 token) internal returns(uint) {
if (decimals[token] == 0) {
setDecimals(token);
}
return decimals[token];
}
function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) {
return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) {
return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals)
internal pure returns(uint)
{
require(srcAmount <= MAX_QTY);
require(destAmount <= MAX_QTY);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);
}
}
}
// File: contracts/permissionless/OrderIdManager.sol
contract OrderIdManager {
struct OrderIdData {
uint32 firstOrderId;
uint takenBitmap;
}
uint constant public NUM_ORDERS = 32;
function fetchNewOrderId(OrderIdData storage freeOrders)
internal
returns(uint32)
{
uint orderBitmap = freeOrders.takenBitmap;
uint bitPointer = 1;
for (uint i = 0; i < NUM_ORDERS; ++i) {
if ((orderBitmap & bitPointer) == 0) {
freeOrders.takenBitmap = orderBitmap | bitPointer;
return(uint32(uint(freeOrders.firstOrderId) + i));
}
bitPointer *= 2;
}
revert();
}
/// @dev mark order as free to use.
function releaseOrderId(OrderIdData storage freeOrders, uint32 orderId)
internal
returns(bool)
{
require(orderId >= freeOrders.firstOrderId);
require(orderId < (freeOrders.firstOrderId + NUM_ORDERS));
uint orderBitNum = uint(orderId) - uint(freeOrders.firstOrderId);
uint bitPointer = uint(1) << orderBitNum;
require(bitPointer & freeOrders.takenBitmap > 0);
freeOrders.takenBitmap &= ~bitPointer;
return true;
}
function allocateOrderIds(
OrderIdData storage makerOrders,
uint32 firstAllocatedId
)
internal
returns(bool)
{
if (makerOrders.firstOrderId > 0) {
return false;
}
makerOrders.firstOrderId = firstAllocatedId;
makerOrders.takenBitmap = 0;
return true;
}
function orderAllocationRequired(OrderIdData storage freeOrders) internal view returns (bool) {
if (freeOrders.firstOrderId == 0) return true;
return false;
}
function getNumActiveOrderIds(OrderIdData storage makerOrders) internal view returns (uint numActiveOrders) {
for (uint i = 0; i < NUM_ORDERS; ++i) {
if ((makerOrders.takenBitmap & (uint(1) << i)) > 0) numActiveOrders++;
}
}
}
// File: contracts/permissionless/OrderListInterface.sol
interface OrderListInterface {
function getOrderDetails(uint32 orderId) public view returns (address, uint128, uint128, uint32, uint32);
function add(address maker, uint32 orderId, uint128 srcAmount, uint128 dstAmount) public returns (bool);
function remove(uint32 orderId) public returns (bool);
function update(uint32 orderId, uint128 srcAmount, uint128 dstAmount) public returns (bool);
function getFirstOrder() public view returns(uint32 orderId, bool isEmpty);
function allocateIds(uint32 howMany) public returns(uint32);
function findPrevOrderId(uint128 srcAmount, uint128 dstAmount) public view returns(uint32);
function addAfterId(address maker, uint32 orderId, uint128 srcAmount, uint128 dstAmount, uint32 prevId) public
returns (bool);
function updateWithPositionHint(uint32 orderId, uint128 srcAmount, uint128 dstAmount, uint32 prevId) public
returns(bool, uint);
}
// File: contracts/permissionless/OrderListFactoryInterface.sol
interface OrderListFactoryInterface {
function newOrdersContract(address admin) public returns(OrderListInterface);
}
// File: contracts/permissionless/OrderbookReserveInterface.sol
interface OrderbookReserveInterface {
function init() public returns(bool);
function kncRateBlocksTrade() public view returns(bool);
}
// File: contracts/permissionless/OrderbookReserve.sol
contract FeeBurnerRateInterface {
uint public kncPerEthRatePrecision;
}
interface MedianizerInterface {
function peek() public view returns (bytes32, bool);
}
contract OrderbookReserve is OrderIdManager, Utils2, KyberReserveInterface, OrderbookReserveInterface {
uint public constant BURN_TO_STAKE_FACTOR = 5; // stake per order must be xfactor expected burn amount.
uint public constant MAX_BURN_FEE_BPS = 100; // 1%
uint public constant MIN_REMAINING_ORDER_RATIO = 2; // Ratio between min new order value and min order value.
uint public constant MAX_USD_PER_ETH = 100000; // Above this value price is surely compromised.
uint32 constant public TAIL_ID = 1; // tail Id in order list contract
uint32 constant public HEAD_ID = 2; // head Id in order list contract
struct OrderLimits {
uint minNewOrderSizeUsd; // Basis for setting min new order size Eth
uint maxOrdersPerTrade; // Limit number of iterated orders per trade / getRate loops.
uint minNewOrderSizeWei; // Below this value can't create new order.
uint minOrderSizeWei; // below this value order will be removed.
}
uint public kncPerEthBaseRatePrecision; // according to base rate all stakes are calculated.
struct ExternalContracts {
ERC20 kncToken; // not constant. to enable testing while not on main net
ERC20 token; // only supported token.
FeeBurnerRateInterface feeBurner;
address kyberNetwork;
MedianizerInterface medianizer; // price feed Eth - USD from maker DAO.
OrderListFactoryInterface orderListFactory;
}
//struct for getOrderData() return value. used only in memory.
struct OrderData {
address maker;
uint32 nextId;
bool isLastOrder;
uint128 srcAmount;
uint128 dstAmount;
}
OrderLimits public limits;
ExternalContracts public contracts;
// sorted lists of orders. one list for token to Eth, other for Eth to token.
// Each order is added in the correct position in the list to keep it sorted.
OrderListInterface public tokenToEthList;
OrderListInterface public ethToTokenList;
//funds data
mapping(address => mapping(address => uint)) public makerFunds; // deposited maker funds.
mapping(address => uint) public makerKnc; // for knc staking.
mapping(address => uint) public makerTotalOrdersWei; // per maker how many Wei in orders, for stake calculation.
uint public makerBurnFeeBps; // knc burn fee per order that is taken.
//each maker will have orders that will be reused.
mapping(address => OrderIdData) public makerOrdersTokenToEth;
mapping(address => OrderIdData) public makerOrdersEthToToken;
function OrderbookReserve(
ERC20 knc,
ERC20 reserveToken,
address burner,
address network,
MedianizerInterface medianizer,
OrderListFactoryInterface factory,
uint minNewOrderUsd,
uint maxOrdersPerTrade,
uint burnFeeBps
)
public
{
require(knc != address(0));
require(reserveToken != address(0));
require(burner != address(0));
require(network != address(0));
require(medianizer != address(0));
require(factory != address(0));
require(burnFeeBps != 0);
require(burnFeeBps <= MAX_BURN_FEE_BPS);
require(maxOrdersPerTrade != 0);
require(minNewOrderUsd > 0);
contracts.kyberNetwork = network;
contracts.feeBurner = FeeBurnerRateInterface(burner);
contracts.medianizer = medianizer;
contracts.orderListFactory = factory;
contracts.kncToken = knc;
contracts.token = reserveToken;
makerBurnFeeBps = burnFeeBps;
limits.minNewOrderSizeUsd = minNewOrderUsd;
limits.maxOrdersPerTrade = maxOrdersPerTrade;
require(setMinOrderSizeEth());
require(contracts.kncToken.approve(contracts.feeBurner, (2**255)));
//can only support tokens with decimals() API
setDecimals(contracts.token);
kncPerEthBaseRatePrecision = contracts.feeBurner.kncPerEthRatePrecision();
}
///@dev separate init function for this contract, if this init is in the C'tor. gas consumption too high.
function init() public returns(bool) {
if ((tokenToEthList != address(0)) && (ethToTokenList != address(0))) return true;
if ((tokenToEthList != address(0)) || (ethToTokenList != address(0))) revert();
tokenToEthList = contracts.orderListFactory.newOrdersContract(this);
ethToTokenList = contracts.orderListFactory.newOrdersContract(this);
return true;
}
function setKncPerEthBaseRate() public {
uint kncPerEthRatePrecision = contracts.feeBurner.kncPerEthRatePrecision();
if (kncPerEthRatePrecision < kncPerEthBaseRatePrecision) {
kncPerEthBaseRatePrecision = kncPerEthRatePrecision;
}
}
function getConversionRate(ERC20 src, ERC20 dst, uint srcQty, uint blockNumber) public view returns(uint) {
require((src == ETH_TOKEN_ADDRESS) || (dst == ETH_TOKEN_ADDRESS));
require((src == contracts.token) || (dst == contracts.token));
require(srcQty <= MAX_QTY);
if (kncRateBlocksTrade()) return 0;
blockNumber; // in this reserve no order expiry == no use for blockNumber. here to avoid compiler warning.
//user order ETH -> token is matched with maker order token -> ETH
OrderListInterface list = (src == ETH_TOKEN_ADDRESS) ? tokenToEthList : ethToTokenList;
uint32 orderId;
OrderData memory orderData;
uint128 userRemainingSrcQty = uint128(srcQty);
uint128 totalUserDstAmount = 0;
uint maxOrders = limits.maxOrdersPerTrade;
for (
(orderId, orderData.isLastOrder) = list.getFirstOrder();
((userRemainingSrcQty > 0) && (!orderData.isLastOrder) && (maxOrders-- > 0));
orderId = orderData.nextId
) {
orderData = getOrderData(list, orderId);
// maker dst quantity is the requested quantity he wants to receive. user src quantity is what user gives.
// so user src quantity is matched with maker dst quantity
if (orderData.dstAmount <= userRemainingSrcQty) {
totalUserDstAmount += orderData.srcAmount;
userRemainingSrcQty -= orderData.dstAmount;
} else {
totalUserDstAmount += uint128(uint(orderData.srcAmount) * uint(userRemainingSrcQty) /
uint(orderData.dstAmount));
userRemainingSrcQty = 0;
}
}
if (userRemainingSrcQty != 0) return 0; //not enough tokens to exchange.
return calcRateFromQty(srcQty, totalUserDstAmount, getDecimals(src), getDecimals(dst));
}
event OrderbookReserveTrade(ERC20 srcToken, ERC20 dstToken, uint srcAmount, uint dstAmount);
function trade(
ERC20 srcToken,
uint srcAmount,
ERC20 dstToken,
address dstAddress,
uint conversionRate,
bool validate
)
public
payable
returns(bool)
{
require(msg.sender == contracts.kyberNetwork);
require((srcToken == ETH_TOKEN_ADDRESS) || (dstToken == ETH_TOKEN_ADDRESS));
require((srcToken == contracts.token) || (dstToken == contracts.token));
require(srcAmount <= MAX_QTY);
conversionRate;
validate;
if (srcToken == ETH_TOKEN_ADDRESS) {
require(msg.value == srcAmount);
} else {
require(msg.value == 0);
require(srcToken.transferFrom(msg.sender, this, srcAmount));
}
uint totalDstAmount = doTrade(
srcToken,
srcAmount,
dstToken
);
require(conversionRate <= calcRateFromQty(srcAmount, totalDstAmount, getDecimals(srcToken),
getDecimals(dstToken)));
//all orders were successfully taken. send to dstAddress
if (dstToken == ETH_TOKEN_ADDRESS) {
dstAddress.transfer(totalDstAmount);
} else {
require(dstToken.transfer(dstAddress, totalDstAmount));
}
OrderbookReserveTrade(srcToken, dstToken, srcAmount, totalDstAmount);
return true;
}
function doTrade(
ERC20 srcToken,
uint srcAmount,
ERC20 dstToken
)
internal
returns(uint)
{
OrderListInterface list = (srcToken == ETH_TOKEN_ADDRESS) ? tokenToEthList : ethToTokenList;
uint32 orderId;
OrderData memory orderData;
uint128 userRemainingSrcQty = uint128(srcAmount);
uint128 totalUserDstAmount = 0;
for (
(orderId, orderData.isLastOrder) = list.getFirstOrder();
((userRemainingSrcQty > 0) && (!orderData.isLastOrder));
orderId = orderData.nextId
) {
// maker dst quantity is the requested quantity he wants to receive. user src quantity is what user gives.
// so user src quantity is matched with maker dst quantity
orderData = getOrderData(list, orderId);
if (orderData.dstAmount <= userRemainingSrcQty) {
totalUserDstAmount += orderData.srcAmount;
userRemainingSrcQty -= orderData.dstAmount;
require(takeFullOrder({
maker: orderData.maker,
orderId: orderId,
userSrc: srcToken,
userDst: dstToken,
userSrcAmount: orderData.dstAmount,
userDstAmount: orderData.srcAmount
}));
} else {
uint128 partialDstQty = uint128(uint(orderData.srcAmount) * uint(userRemainingSrcQty) /
uint(orderData.dstAmount));
totalUserDstAmount += partialDstQty;
require(takePartialOrder({
maker: orderData.maker,
orderId: orderId,
userSrc: srcToken,
userDst: dstToken,
userPartialSrcAmount: userRemainingSrcQty,
userTakeDstAmount: partialDstQty,
orderSrcAmount: orderData.srcAmount,
orderDstAmount: orderData.dstAmount
}));
userRemainingSrcQty = 0;
}
}
require(userRemainingSrcQty == 0 && totalUserDstAmount > 0);
return totalUserDstAmount;
}
///@param srcAmount is the token amount that will be payed. must be deposited before hand in the makers account.
///@param dstAmount is the eth amount the maker expects to get for his tokens.
function submitTokenToEthOrder(uint128 srcAmount, uint128 dstAmount)
public
returns(bool)
{
return submitTokenToEthOrderWHint(srcAmount, dstAmount, 0);
}
function submitTokenToEthOrderWHint(uint128 srcAmount, uint128 dstAmount, uint32 hintPrevOrder)
public
returns(bool)
{
uint32 newId = fetchNewOrderId(makerOrdersTokenToEth[msg.sender]);
return addOrder(false, newId, srcAmount, dstAmount, hintPrevOrder);
}
///@param srcAmount is the Ether amount that will be payed, must be deposited before hand.
///@param dstAmount is the token amount the maker expects to get for his Ether.
function submitEthToTokenOrder(uint128 srcAmount, uint128 dstAmount)
public
returns(bool)
{
return submitEthToTokenOrderWHint(srcAmount, dstAmount, 0);
}
function submitEthToTokenOrderWHint(uint128 srcAmount, uint128 dstAmount, uint32 hintPrevOrder)
public
returns(bool)
{
uint32 newId = fetchNewOrderId(makerOrdersEthToToken[msg.sender]);
return addOrder(true, newId, srcAmount, dstAmount, hintPrevOrder);
}
///@dev notice here a batch of orders represented in arrays. order x is represented by x cells of all arrays.
///@dev all arrays expected to the same length.
///@param isEthToToken per each order. is order x eth to token (= src is Eth) or vice versa.
///@param srcAmount per each order. source amount for order x.
///@param dstAmount per each order. destination amount for order x.
///@param hintPrevOrder per each order what is the order it should be added after in ordered list. 0 for no hint.
///@param isAfterPrevOrder per each order, set true if should be added in list right after previous added order.
function addOrderBatch(bool[] isEthToToken, uint128[] srcAmount, uint128[] dstAmount,
uint32[] hintPrevOrder, bool[] isAfterPrevOrder)
public
returns(bool)
{
require(isEthToToken.length == hintPrevOrder.length);
require(isEthToToken.length == dstAmount.length);
require(isEthToToken.length == srcAmount.length);
require(isEthToToken.length == isAfterPrevOrder.length);
address maker = msg.sender;
uint32 prevId;
uint32 newId = 0;
for (uint i = 0; i < isEthToToken.length; ++i) {
prevId = isAfterPrevOrder[i] ? newId : hintPrevOrder[i];
newId = fetchNewOrderId(isEthToToken[i] ? makerOrdersEthToToken[maker] : makerOrdersTokenToEth[maker]);
require(addOrder(isEthToToken[i], newId, srcAmount[i], dstAmount[i], prevId));
}
return true;
}
function updateTokenToEthOrder(uint32 orderId, uint128 newSrcAmount, uint128 newDstAmount)
public
returns(bool)
{
require(updateTokenToEthOrderWHint(orderId, newSrcAmount, newDstAmount, 0));
return true;
}
function updateTokenToEthOrderWHint(
uint32 orderId,
uint128 newSrcAmount,
uint128 newDstAmount,
uint32 hintPrevOrder
)
public
returns(bool)
{
require(updateOrder(false, orderId, newSrcAmount, newDstAmount, hintPrevOrder));
return true;
}
function updateEthToTokenOrder(uint32 orderId, uint128 newSrcAmount, uint128 newDstAmount)
public
returns(bool)
{
return updateEthToTokenOrderWHint(orderId, newSrcAmount, newDstAmount, 0);
}
function updateEthToTokenOrderWHint(
uint32 orderId,
uint128 newSrcAmount,
uint128 newDstAmount,
uint32 hintPrevOrder
)
public
returns(bool)
{
require(updateOrder(true, orderId, newSrcAmount, newDstAmount, hintPrevOrder));
return true;
}
function updateOrderBatch(bool[] isEthToToken, uint32[] orderId, uint128[] newSrcAmount,
uint128[] newDstAmount, uint32[] hintPrevOrder)
public
returns(bool)
{
require(isEthToToken.length == orderId.length);
require(isEthToToken.length == newSrcAmount.length);
require(isEthToToken.length == newDstAmount.length);
require(isEthToToken.length == hintPrevOrder.length);
for (uint i = 0; i < isEthToToken.length; ++i) {
require(updateOrder(isEthToToken[i], orderId[i], newSrcAmount[i], newDstAmount[i],
hintPrevOrder[i]));
}
return true;
}
event TokenDeposited(address indexed maker, uint amount);
function depositToken(address maker, uint amount) public {
require(maker != address(0));
require(amount < MAX_QTY);
require(contracts.token.transferFrom(msg.sender, this, amount));
makerFunds[maker][contracts.token] += amount;
TokenDeposited(maker, amount);
}
event EtherDeposited(address indexed maker, uint amount);
function depositEther(address maker) public payable {
require(maker != address(0));
makerFunds[maker][ETH_TOKEN_ADDRESS] += msg.value;
EtherDeposited(maker, msg.value);
}
event KncFeeDeposited(address indexed maker, uint amount);
// knc will be staked per order. part of the amount will be used as fee.
function depositKncForFee(address maker, uint amount) public {
require(maker != address(0));
require(amount < MAX_QTY);
require(contracts.kncToken.transferFrom(msg.sender, this, amount));
makerKnc[maker] += amount;
KncFeeDeposited(maker, amount);
if (orderAllocationRequired(makerOrdersTokenToEth[maker])) {
require(allocateOrderIds(
makerOrdersTokenToEth[maker], /* makerOrders */
tokenToEthList.allocateIds(uint32(NUM_ORDERS)) /* firstAllocatedId */
));
}
if (orderAllocationRequired(makerOrdersEthToToken[maker])) {
require(allocateOrderIds(
makerOrdersEthToToken[maker], /* makerOrders */
ethToTokenList.allocateIds(uint32(NUM_ORDERS)) /* firstAllocatedId */
));
}
}
function withdrawToken(uint amount) public {
address maker = msg.sender;
uint makerFreeAmount = makerFunds[maker][contracts.token];
require(makerFreeAmount >= amount);
makerFunds[maker][contracts.token] -= amount;
require(contracts.token.transfer(maker, amount));
}
function withdrawEther(uint amount) public {
address maker = msg.sender;
uint makerFreeAmount = makerFunds[maker][ETH_TOKEN_ADDRESS];
require(makerFreeAmount >= amount);
makerFunds[maker][ETH_TOKEN_ADDRESS] -= amount;
maker.transfer(amount);
}
function withdrawKncFee(uint amount) public {
address maker = msg.sender;
require(makerKnc[maker] >= amount);
require(makerUnlockedKnc(maker) >= amount);
makerKnc[maker] -= amount;
require(contracts.kncToken.transfer(maker, amount));
}
function cancelTokenToEthOrder(uint32 orderId) public returns(bool) {
require(cancelOrder(false, orderId));
return true;
}
function cancelEthToTokenOrder(uint32 orderId) public returns(bool) {
require(cancelOrder(true, orderId));
return true;
}
function setMinOrderSizeEth() public returns(bool) {
//get eth to $ from maker dao;
bytes32 usdPerEthInWei;
bool valid;
(usdPerEthInWei, valid) = contracts.medianizer.peek();
require(valid);
// ensuring that there is no underflow or overflow possible,
// even if the price is compromised
uint usdPerEth = uint(usdPerEthInWei) / (1 ether);
require(usdPerEth != 0);
require(usdPerEth < MAX_USD_PER_ETH);
// set Eth order limits according to price
uint minNewOrderSizeWei = limits.minNewOrderSizeUsd * PRECISION * (1 ether) / uint(usdPerEthInWei);
limits.minNewOrderSizeWei = minNewOrderSizeWei;
limits.minOrderSizeWei = limits.minNewOrderSizeWei / MIN_REMAINING_ORDER_RATIO;
return true;
}
///@dev Each maker stakes per order KNC that is factor of the required burn amount.
///@dev If Knc per Eth rate becomes lower by more then factor, stake will not be enough and trade will be blocked.
function kncRateBlocksTrade() public view returns (bool) {
return (contracts.feeBurner.kncPerEthRatePrecision() > kncPerEthBaseRatePrecision * BURN_TO_STAKE_FACTOR);
}
function getTokenToEthAddOrderHint(uint128 srcAmount, uint128 dstAmount) public view returns (uint32) {
require(dstAmount >= limits.minNewOrderSizeWei);
return tokenToEthList.findPrevOrderId(srcAmount, dstAmount);
}
function getEthToTokenAddOrderHint(uint128 srcAmount, uint128 dstAmount) public view returns (uint32) {
require(srcAmount >= limits.minNewOrderSizeWei);
return ethToTokenList.findPrevOrderId(srcAmount, dstAmount);
}
function getTokenToEthUpdateOrderHint(uint32 orderId, uint128 srcAmount, uint128 dstAmount)
public
view
returns (uint32)
{
require(dstAmount >= limits.minNewOrderSizeWei);
uint32 prevId = tokenToEthList.findPrevOrderId(srcAmount, dstAmount);
address add;
uint128 noUse;
uint32 next;
if (prevId == orderId) {
(add, noUse, noUse, prevId, next) = tokenToEthList.getOrderDetails(orderId);
}
return prevId;
}
function getEthToTokenUpdateOrderHint(uint32 orderId, uint128 srcAmount, uint128 dstAmount)
public
view
returns (uint32)
{
require(srcAmount >= limits.minNewOrderSizeWei);
uint32 prevId = ethToTokenList.findPrevOrderId(srcAmount, dstAmount);
address add;
uint128 noUse;
uint32 next;
if (prevId == orderId) {
(add, noUse, noUse, prevId, next) = ethToTokenList.getOrderDetails(orderId);
}
return prevId;
}
function getTokenToEthOrder(uint32 orderId)
public view
returns (
address _maker,
uint128 _srcAmount,
uint128 _dstAmount,
uint32 _prevId,
uint32 _nextId
)
{
return tokenToEthList.getOrderDetails(orderId);
}
function getEthToTokenOrder(uint32 orderId)
public view
returns (
address _maker,
uint128 _srcAmount,
uint128 _dstAmount,
uint32 _prevId,
uint32 _nextId
)
{
return ethToTokenList.getOrderDetails(orderId);
}
function makerRequiredKncStake(address maker) public view returns (uint) {
return(calcKncStake(makerTotalOrdersWei[maker]));
}
function makerUnlockedKnc(address maker) public view returns (uint) {
uint requiredKncStake = makerRequiredKncStake(maker);
if (requiredKncStake > makerKnc[maker]) return 0;
return (makerKnc[maker] - requiredKncStake);
}
function calcKncStake(uint weiAmount) public view returns(uint) {
return(calcBurnAmount(weiAmount) * BURN_TO_STAKE_FACTOR);
}
function calcBurnAmount(uint weiAmount) public view returns(uint) {
return(weiAmount * makerBurnFeeBps * kncPerEthBaseRatePrecision / (10000 * PRECISION));
}
function calcBurnAmountFromFeeBurner(uint weiAmount) public view returns(uint) {
return(weiAmount * makerBurnFeeBps * contracts.feeBurner.kncPerEthRatePrecision() / (10000 * PRECISION));
}
///@dev This function is not fully optimized gas wise. Consider before calling on chain.
function getEthToTokenMakerOrderIds(address maker) public view returns(uint32[] orderList) {
OrderIdData storage makerOrders = makerOrdersEthToToken[maker];
orderList = new uint32[](getNumActiveOrderIds(makerOrders));
uint activeOrder = 0;
for (uint32 i = 0; i < NUM_ORDERS; ++i) {
if ((makerOrders.takenBitmap & (uint(1) << i) > 0)) orderList[activeOrder++] = makerOrders.firstOrderId + i;
}
}
///@dev This function is not fully optimized gas wise. Consider before calling on chain.
function getTokenToEthMakerOrderIds(address maker) public view returns(uint32[] orderList) {
OrderIdData storage makerOrders = makerOrdersTokenToEth[maker];
orderList = new uint32[](getNumActiveOrderIds(makerOrders));
uint activeOrder = 0;
for (uint32 i = 0; i < NUM_ORDERS; ++i) {
if ((makerOrders.takenBitmap & (uint(1) << i) > 0)) orderList[activeOrder++] = makerOrders.firstOrderId + i;
}
}
///@dev This function is not fully optimized gas wise. Consider before calling on chain.
function getEthToTokenOrderList() public view returns(uint32[] orderList) {
OrderListInterface list = ethToTokenList;
return getList(list);
}
///@dev This function is not fully optimized gas wise. Consider before calling on chain.
function getTokenToEthOrderList() public view returns(uint32[] orderList) {
OrderListInterface list = tokenToEthList;
return getList(list);
}
event NewLimitOrder(
address indexed maker,
uint32 orderId,
bool isEthToToken,
uint128 srcAmount,
uint128 dstAmount,
bool addedWithHint
);
function addOrder(bool isEthToToken, uint32 newId, uint128 srcAmount, uint128 dstAmount, uint32 hintPrevOrder)
internal
returns(bool)
{
require(srcAmount < MAX_QTY);
require(dstAmount < MAX_QTY);
address maker = msg.sender;
require(secureAddOrderFunds(maker, isEthToToken, srcAmount, dstAmount));
require(validateLegalRate(srcAmount, dstAmount, isEthToToken));
bool addedWithHint = false;
OrderListInterface list = isEthToToken ? ethToTokenList : tokenToEthList;
if (hintPrevOrder != 0) {
addedWithHint = list.addAfterId(maker, newId, srcAmount, dstAmount, hintPrevOrder);
}
if (!addedWithHint) {
require(list.add(maker, newId, srcAmount, dstAmount));
}
NewLimitOrder(maker, newId, isEthToToken, srcAmount, dstAmount, addedWithHint);
return true;
}
event OrderUpdated(
address indexed maker,
bool isEthToToken,
uint orderId,
uint128 srcAmount,
uint128 dstAmount,
bool updatedWithHint
);
function updateOrder(bool isEthToToken, uint32 orderId, uint128 newSrcAmount,
uint128 newDstAmount, uint32 hintPrevOrder)
internal
returns(bool)
{
require(newSrcAmount < MAX_QTY);
require(newDstAmount < MAX_QTY);
address maker;
uint128 currDstAmount;
uint128 currSrcAmount;
uint32 noUse;
uint noUse2;
require(validateLegalRate(newSrcAmount, newDstAmount, isEthToToken));
OrderListInterface list = isEthToToken ? ethToTokenList : tokenToEthList;
(maker, currSrcAmount, currDstAmount, noUse, noUse) = list.getOrderDetails(orderId);
require(maker == msg.sender);
if (!secureUpdateOrderFunds(maker, isEthToToken, currSrcAmount, currDstAmount, newSrcAmount, newDstAmount)) {
return false;
}
bool updatedWithHint = false;
if (hintPrevOrder != 0) {
(updatedWithHint, noUse2) = list.updateWithPositionHint(orderId, newSrcAmount, newDstAmount, hintPrevOrder);
}
if (!updatedWithHint) {
require(list.update(orderId, newSrcAmount, newDstAmount));
}
OrderUpdated(maker, isEthToToken, orderId, newSrcAmount, newDstAmount, updatedWithHint);
return true;
}
event OrderCanceled(address indexed maker, bool isEthToToken, uint32 orderId, uint128 srcAmount, uint dstAmount);
function cancelOrder(bool isEthToToken, uint32 orderId) internal returns(bool) {
address maker = msg.sender;
OrderListInterface list = isEthToToken ? ethToTokenList : tokenToEthList;
OrderData memory orderData = getOrderData(list, orderId);
require(orderData.maker == maker);
uint weiAmount = isEthToToken ? orderData.srcAmount : orderData.dstAmount;
require(releaseOrderStakes(maker, weiAmount, 0));
require(removeOrder(list, maker, isEthToToken ? ETH_TOKEN_ADDRESS : contracts.token, orderId));
//funds go back to makers account
makerFunds[maker][isEthToToken ? ETH_TOKEN_ADDRESS : contracts.token] += orderData.srcAmount;
OrderCanceled(maker, isEthToToken, orderId, orderData.srcAmount, orderData.dstAmount);
return true;
}
///@param maker is the maker of this order
///@param isEthToToken which order type the maker is updating / adding
///@param srcAmount is the orders src amount (token or ETH) could be negative if funds are released.
function bindOrderFunds(address maker, bool isEthToToken, int srcAmount)
internal
returns(bool)
{
address fundsAddress = isEthToToken ? ETH_TOKEN_ADDRESS : contracts.token;
if (srcAmount < 0) {
makerFunds[maker][fundsAddress] += uint(-srcAmount);
} else {
require(makerFunds[maker][fundsAddress] >= uint(srcAmount));
makerFunds[maker][fundsAddress] -= uint(srcAmount);
}
return true;
}
///@param maker is the maker address
///@param weiAmount is the wei amount inside order that should result in knc staking
function bindOrderStakes(address maker, int weiAmount) internal returns(bool) {
if (weiAmount < 0) {
uint decreaseWeiAmount = uint(-weiAmount);
if (decreaseWeiAmount > makerTotalOrdersWei[maker]) decreaseWeiAmount = makerTotalOrdersWei[maker];
makerTotalOrdersWei[maker] -= decreaseWeiAmount;
return true;
}
require(makerKnc[maker] >= calcKncStake(makerTotalOrdersWei[maker] + uint(weiAmount)));
makerTotalOrdersWei[maker] += uint(weiAmount);
return true;
}
///@dev if totalWeiAmount is 0 we only release stakes.
///@dev if totalWeiAmount == weiForBurn. all staked amount will be burned. so no knc returned to maker
///@param maker is the maker address
///@param totalWeiAmount is total wei amount that was released from order - including taken wei amount.
///@param weiForBurn is the part in order wei amount that was taken and should result in burning.
function releaseOrderStakes(address maker, uint totalWeiAmount, uint weiForBurn) internal returns(bool) {
require(weiForBurn <= totalWeiAmount);
if (totalWeiAmount > makerTotalOrdersWei[maker]) {
makerTotalOrdersWei[maker] = 0;
} else {
makerTotalOrdersWei[maker] -= totalWeiAmount;
}
if (weiForBurn == 0) return true;
uint burnAmount = calcBurnAmountFromFeeBurner(weiForBurn);
require(makerKnc[maker] >= burnAmount);
makerKnc[maker] -= burnAmount;
return true;
}
///@dev funds are valid only when required knc amount can be staked for this order.
function secureAddOrderFunds(address maker, bool isEthToToken, uint128 srcAmount, uint128 dstAmount)
internal returns(bool)
{
uint weiAmount = isEthToToken ? srcAmount : dstAmount;
require(weiAmount >= limits.minNewOrderSizeWei);
require(bindOrderFunds(maker, isEthToToken, int(srcAmount)));
require(bindOrderStakes(maker, int(weiAmount)));
return true;
}
///@dev funds are valid only when required knc amount can be staked for this order.
function secureUpdateOrderFunds(address maker, bool isEthToToken, uint128 prevSrcAmount, uint128 prevDstAmount,
uint128 newSrcAmount, uint128 newDstAmount)
internal
returns(bool)
{
uint weiAmount = isEthToToken ? newSrcAmount : newDstAmount;
int weiDiff = isEthToToken ? (int(newSrcAmount) - int(prevSrcAmount)) :
(int(newDstAmount) - int(prevDstAmount));
require(weiAmount >= limits.minNewOrderSizeWei);
require(bindOrderFunds(maker, isEthToToken, int(newSrcAmount) - int(prevSrcAmount)));
require(bindOrderStakes(maker, weiDiff));
return true;
}
event FullOrderTaken(address maker, uint32 orderId, bool isEthToToken);
function takeFullOrder(
address maker,
uint32 orderId,
ERC20 userSrc,
ERC20 userDst,
uint128 userSrcAmount,
uint128 userDstAmount
)
internal
returns (bool)
{
OrderListInterface list = (userSrc == ETH_TOKEN_ADDRESS) ? tokenToEthList : ethToTokenList;
//userDst == maker source
require(removeOrder(list, maker, userDst, orderId));
FullOrderTaken(maker, orderId, userSrc == ETH_TOKEN_ADDRESS);
return takeOrder(maker, userSrc, userSrcAmount, userDstAmount, 0);
}
event PartialOrderTaken(address maker, uint32 orderId, bool isEthToToken, bool isRemoved);
function takePartialOrder(
address maker,
uint32 orderId,
ERC20 userSrc,
ERC20 userDst,
uint128 userPartialSrcAmount,
uint128 userTakeDstAmount,
uint128 orderSrcAmount,
uint128 orderDstAmount
)
internal
returns(bool)
{
require(userPartialSrcAmount < orderDstAmount);
require(userTakeDstAmount < orderSrcAmount);
//must reuse parameters, otherwise stack too deep error.
orderSrcAmount -= userTakeDstAmount;
orderDstAmount -= userPartialSrcAmount;
OrderListInterface list = (userSrc == ETH_TOKEN_ADDRESS) ? tokenToEthList : ethToTokenList;
uint weiValueNotReleasedFromOrder = (userSrc == ETH_TOKEN_ADDRESS) ? orderDstAmount : orderSrcAmount;
uint additionalReleasedWei = 0;
if (weiValueNotReleasedFromOrder < limits.minOrderSizeWei) {
// remaining order amount too small. remove order and add remaining funds to free funds
makerFunds[maker][userDst] += orderSrcAmount;
additionalReleasedWei = weiValueNotReleasedFromOrder;
//for remove order we give makerSrc == userDst
require(removeOrder(list, maker, userDst, orderId));
} else {
bool isSuccess;
// update order values, taken order is always first order
(isSuccess,) = list.updateWithPositionHint(orderId, orderSrcAmount, orderDstAmount, HEAD_ID);
require(isSuccess);
}
PartialOrderTaken(maker, orderId, userSrc == ETH_TOKEN_ADDRESS, additionalReleasedWei > 0);
//stakes are returned for unused wei value
return(takeOrder(maker, userSrc, userPartialSrcAmount, userTakeDstAmount, additionalReleasedWei));
}
function takeOrder(
address maker,
ERC20 userSrc,
uint userSrcAmount,
uint userDstAmount,
uint additionalReleasedWei
)
internal
returns(bool)
{
uint weiAmount = userSrc == (ETH_TOKEN_ADDRESS) ? userSrcAmount : userDstAmount;
//token / eth already collected. just update maker balance
makerFunds[maker][userSrc] += userSrcAmount;
// send dst tokens in one batch. not here
//handle knc stakes and fee. releasedWeiValue was released and not traded.
return releaseOrderStakes(maker, (weiAmount + additionalReleasedWei), weiAmount);
}
function removeOrder(
OrderListInterface list,
address maker,
ERC20 makerSrc,
uint32 orderId
)
internal returns(bool)
{
require(list.remove(orderId));
OrderIdData storage orders = (makerSrc == ETH_TOKEN_ADDRESS) ?
makerOrdersEthToToken[maker] : makerOrdersTokenToEth[maker];
require(releaseOrderId(orders, orderId));
return true;
}
function getList(OrderListInterface list) internal view returns(uint32[] memory orderList) {
OrderData memory orderData;
uint32 orderId;
bool isEmpty;
(orderId, isEmpty) = list.getFirstOrder();
if (isEmpty) return(new uint32[](0));
uint numOrders = 0;
for (; !orderData.isLastOrder; orderId = orderData.nextId) {
orderData = getOrderData(list, orderId);
numOrders++;
}
orderList = new uint32[](numOrders);
(orderId, orderData.isLastOrder) = list.getFirstOrder();
for (uint i = 0; i < numOrders; i++) {
orderList[i] = orderId;
orderData = getOrderData(list, orderId);
orderId = orderData.nextId;
}
}
function getOrderData(OrderListInterface list, uint32 orderId) internal view returns (OrderData data) {
uint32 prevId;
(data.maker, data.srcAmount, data.dstAmount, prevId, data.nextId) = list.getOrderDetails(orderId);
data.isLastOrder = (data.nextId == TAIL_ID);
}
function validateLegalRate (uint srcAmount, uint dstAmount, bool isEthToToken)
internal view returns(bool)
{
uint rate;
/// notice, rate is calculated from taker perspective,
/// for taker amounts are opposite. order srcAmount will be DstAmount for taker.
if (isEthToToken) {
rate = calcRateFromQty(dstAmount, srcAmount, getDecimals(contracts.token), ETH_DECIMALS);
} else {
rate = calcRateFromQty(dstAmount, srcAmount, ETH_DECIMALS, getDecimals(contracts.token));
}
if (rate > MAX_RATE) return false;
return true;
}
} | token / eth already collected. just update maker balance send dst tokens in one batch. not herehandle knc stakes and fee. releasedWeiValue was released and not traded. | function takeOrder(
address maker,
ERC20 userSrc,
uint userSrcAmount,
uint userDstAmount,
uint additionalReleasedWei
)
internal
returns(bool)
{
uint weiAmount = userSrc == (ETH_TOKEN_ADDRESS) ? userSrcAmount : userDstAmount;
makerFunds[maker][userSrc] += userSrcAmount;
return releaseOrderStakes(maker, (weiAmount + additionalReleasedWei), weiAmount);
}
| 1,206,008 |
pragma solidity 0.6.12;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable {
address public _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () public {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract RazorToken is Ownable{
using SafeMath for uint256;
mapping (address => uint256) public balanceOf;
mapping (address => bool) public whitelist;
string public name = "Razor.Network";
string public symbol = "RAZOR";
uint8 public decimals = 18;
uint256 public totalSupply = 500000 * (uint256(10) ** decimals);
uint256 public totalPooled;
event Transfer(address indexed from, address indexed to, uint256 value);
constructor() public {
totalPooled = 50 * (uint256(10) ** decimals);
// Initially assign all non-pooled tokens to the contract's creator.
balanceOf[msg.sender] = totalSupply.sub(totalPooled);
emit Transfer(address(0), msg.sender, totalSupply.sub(totalPooled));
}
// Ensure a redemption is profitable before allowing a redeem()
modifier profitable() {
require(is_profitable(), "Redeeming is not yet profitable.");
_;
}
// VIEWS
// Get the number of tokens to be redeemed from the pool
function numberRedeemed(uint256 amount)
public
view
returns (uint256 profit) {
uint256 numerator = amount.mul(totalPooled);
uint256 denominator = totalSupply.sub(totalPooled);
return numerator.div(denominator);
}
// Check if more than 50% of the token is pooled
function is_profitable()
public
view
returns (bool _profitable) {
return totalPooled > totalSupply.sub(totalPooled);
}
// SETTERS
function addToWhitelist(address _addr)
public
onlyOwner {
whitelist[_addr] = true;
}
function removeFromWhitelist(address _addr)
public
onlyOwner {
whitelist[_addr] = false;
}
// TRANSFER FUNCTIONS
// BOA-TOKEN <- Sell taxed
// TOKEN-BOA <- Buy (not taxed)
function transfer(address to, uint256 value)
public
returns (bool success) {
require(balanceOf[msg.sender] >= value);
if(whitelist[msg.sender]) return regular_transfer(to, value);
else return burn_transfer(to, value);
}
function burn_transfer(address to, uint256 value)
private
returns (bool success) {
// send 1% to the pooled ledger
uint256 burned_amount = value.div(5); //BURRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRN
// withdraw from the user's balance
balanceOf[msg.sender] = balanceOf[msg.sender].sub(burned_amount);
// increment the total pooled amount
totalPooled = totalPooled.add(burned_amount);
value = value.sub(burned_amount);
// perform a normal transfer on the remaining 99%
return regular_transfer(to, value);
}
function regular_transfer(address to, uint256 value)
private
returns (bool success) {
// perform a normal transfer
balanceOf[msg.sender] = balanceOf[msg.sender].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
returns (bool success)
{
require(value <= balanceOf[from]);
require(value <= allowance[from][msg.sender]);
// allow feeless for the RED-BLUE uniswap pool
if(whitelist[msg.sender]) return regular_transferFrom(from, to, value);
else return burn_transferFrom(from, to, value);
}
function burn_transferFrom(address from, address to, uint256 value)
private
returns (bool success) {
// send 1% to the pooled ledger
uint256 burned_amount = value.div(5); //BURRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRN
// remove from the spender's balance
balanceOf[from] = balanceOf[from].sub(burned_amount);
// increment the total pooled amount
totalPooled = totalPooled.add(burned_amount);
// burn allowance (for approved spenders)
allowance[from][msg.sender] = allowance[from][msg.sender].sub(burned_amount);
value = value.sub(burned_amount);
// perform a normal transfer on the 99%
return regular_transferFrom(from, to, value);
}
function regular_transferFrom(address from, address to, uint256 value)
private
returns (bool success) {
// transfer without adding to a pool
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
// remove allowance (for approved spenders)
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
// REDEEM AND BURN FUNCTIONS
// amount = number of tokens to burn
function redeem(uint256 amount)
public
profitable
returns (bool success) {
// the amount must be less than the total amount pooled
require(amount <= balanceOf[msg.sender]);
require(totalPooled >= amount);
uint256 num_redeemed = numberRedeemed(amount);
// make sure the number available to be redeemed is smaller than the available pool
require(num_redeemed < totalPooled);
balanceOf[msg.sender] = balanceOf[msg.sender].add(num_redeemed);
emit Transfer(_owner, msg.sender, num_redeemed);
totalPooled = totalPooled.sub(num_redeemed);
// burn the amount sent
return burn(amount);
}
function burn(uint256 value)
private
returns (bool success) {
// burn from the user's ledger, transfer to 0x0
balanceOf[msg.sender] = balanceOf[msg.sender].sub(value);
balanceOf[address(0)] = balanceOf[address(0)].add(value);
emit Transfer(msg.sender, address(0), value);
// remove the burned amount from the total supply
totalSupply = totalSupply.sub(value);
return true;
}
// APPROVAL FUNCTIONS
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => mapping(address => uint256)) public allowance;
function approve(address spender, uint256 value)
public
returns (bool success)
{
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
} | send 1% to the pooled ledger withdraw from the user's balance increment the total pooled amount perform a normal transfer on the remaining 99% | function burn_transfer(address to, uint256 value)
private
returns (bool success) {
balanceOf[msg.sender] = balanceOf[msg.sender].sub(burned_amount);
totalPooled = totalPooled.add(burned_amount);
value = value.sub(burned_amount);
return regular_transfer(to, value);
}
| 1,397,659 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* The Rebels NFT contract
*/
contract Rebels is ERC721, Ownable {
using ECDSA for bytes32;
// Maximum supply of tokens
uint public immutable MAX_SUPPLY;
// Maximum amount of tokens that can be reserved by the owner
uint public immutable MAX_OWNER_RESERVE;
// Maximum number of tokens that can be minted in a single transaction
uint public constant MAX_MINT_NUMBER = 10;
// Maximum number of tokens per address in a whitelisted sale
uint public constant MAX_WHITELISTED_SALE_TOKENS = 6;
// SHA256 hash of the concatenated list of token image SHA256 hashes
string public provenanceHash;
// Number of tokens issued for sale
uint public issuedTotal;
// Number of minted tokens (includes reserve mints)
uint public mintedTotal;
// Number of tokens minted from reserve by the owner
uint public reserveMintedTotal;
// Single token price in wei
uint public price;
// Base URI of the token metadata
string public baseUri;
// Address used for whitelisted sale signatures
address public whitelistSigner;
// True if the public token sale is enabled
bool public publicSaleEnabled;
// True if the token sale is enabled for whitelisted addresses
bool public whitelistedSaleEnabled;
// Maps addresses to total number of tokens bought during whitelisted sale
mapping(address => uint) public whitelistedSales;
/**
* @dev Throws if the given number of tokens can't be bought by current transaction
* @param number Requested number of tokens
*
* Requirements:
* - There should be enough issued unsold tokens
* - Transaction value should be equal or bigger than the total price
* - The given number of tokens shouldn't exceed MAX_MINT_NUMBER
*/
modifier canBuy(uint number) {
require(number <= remainingUnsoldSupply(), "Not enough issued tokens left");
require(msg.value >= price * number, "Transaction value too low");
require(number <= MAX_MINT_NUMBER, "Can't mint that many tokens at once");
_;
}
/**
* @param price_ Single token price
* @param maxSupply Max amount of tokens that can be minted
* @param maxOwnerReserve Number of tokens reserved for the owner
*
* Requirements:
* - Reserved token amount must be equal or smaller than the total supply
*/
constructor(uint price_, uint maxSupply, uint maxOwnerReserve) ERC721("The Rebels", "RBLS") {
require(maxOwnerReserve <= maxSupply, "Can't reserve more than the total supply");
MAX_SUPPLY = maxSupply;
MAX_OWNER_RESERVE = maxOwnerReserve;
price = price_;
}
/**
* @dev Issues given number of tokens for sale
* @param number Number of tokens to issue
*
* Requirements:
* - There should be enough supply remaining
*/
function issue(uint number) external onlyOwner {
require(number <= remainingUnissuedSupply(), "Not enough remaining tokens");
issuedTotal += number;
}
/**
* @dev Public sale mint
* @param number Number of tokens to mint
*
* Requirements:
* - Public sale should be enabled
* - All requirements of the canBuy modifier must be satisfied
*/
function mint(uint number) external payable canBuy(number) {
require(publicSaleEnabled, "Public sale disabled");
_batchMint(number);
}
/**
* @dev Whitelisted sale mint
* @param number Number of tokens to mint
* @param signature Sender address's sha3 hash signed by the whitelist signer
*
* Requirements:
* - Whitelisted sale should be enabled
* - Address can't buy more than MAX_WHITELISTED_SALE_TOKENS in a whitelisted sale
* - All requirements of the canBuy modifier must be satisfied
*/
function whitelistedMint(uint number, bytes memory signature) external payable canBuy(number) {
require(whitelistedSaleEnabled, "Whitelisted sale disabled");
address recovered = keccak256(abi.encodePacked(msg.sender))
.toEthSignedMessageHash()
.recover(signature);
require(recovered == whitelistSigner, "Invalid whitelist signature");
require(
whitelistedSales[msg.sender] + number <= MAX_WHITELISTED_SALE_TOKENS,
"Whitelisted sale limit exceeded"
);
whitelistedSales[msg.sender] += number;
_batchMint(number);
}
/**
* @dev Mints tokens reserved for the owner
* @param number Number of tokens to mint
*
* Requirements:
* - There should be enough tokens in the reserve
*/
function reserveMint(uint number) external onlyOwner {
require(number <= remainingOwnerReserve(), "Not enough reserved tokens left");
reserveMintedTotal += number;
_batchMint(number);
}
/**
* @dev Enables minting for whitelisted addresses
*/
function enableWhitelistedSale() external onlyOwner {
whitelistedSaleEnabled = true;
}
/**
* @dev Disables minting for whitelisted addresses
*/
function disableWhitelistedSale() external onlyOwner {
whitelistedSaleEnabled = false;
}
/**
* @dev Enables minting for non-whitelisted addresses
*/
function enablePublicSale() external onlyOwner {
publicSaleEnabled = true;
}
/**
* @dev Disables minting for non-whitelisted addresses
*/
function disablePublicSale() external onlyOwner {
publicSaleEnabled = false;
}
/**
* @dev Sets the price of a single token
* @param price_ Price in wei
*/
function setPrice(uint price_) external onlyOwner {
price = price_;
}
/**
* @dev Sets the address that generates signatures for whitelisted mint
* @param whitelistSigner_ Signing address
*
* Note that whitelist signatures signed with the old address won't be accepted after changing
* the signer address.
*/
function setWhitelistSigner(address whitelistSigner_) external onlyOwner {
whitelistSigner = whitelistSigner_;
}
/**
* @dev Sets base URI for the metadata
* @param baseUri_ Base URI, where the token's ID could be appended at the end of it
*/
function setBaseUri(string memory baseUri_) external onlyOwner {
baseUri = baseUri_;
}
/**
* @dev Sets provenance hash
* @param hash SHA256 hash of the concatenated list of token image SHA256 hashes
*
* Requirements:
* - Hash can only be set (or changed) before the first mint
*/
function setProvenanceHash(string memory hash) external onlyOwner {
require(mintedTotal == 0, "Hash can only be set before first mint");
provenanceHash = hash;
}
/**
* @dev Sends contract's balance to the owner's wallet
*/
function withdraw() external onlyOwner {
uint balance = address(this).balance;
payable(owner()).transfer(balance);
}
/**
* @dev Mints new tokens
* @param number Number of tokens to mint
*/
function _batchMint(uint number) private {
uint lastTokenId = mintedTotal;
mintedTotal += number;
for (uint i = 1; i <= number; i++) {
_safeMint(msg.sender, lastTokenId + i);
}
}
/**
* @dev Overwrites parent to provide actual base URI
* @return Base URI of the token metadata
*/
function _baseURI() override internal view returns (string memory) {
return baseUri;
}
/**
* @dev Checks if the given token exists (has been minted)
* @param tokenId Token ID
* @return True, if token is minted
*/
function exists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
/**
* @dev Returns total number of minted tokens
* @return Total number of minted tokens
*
* Note: Partially implements IERC721Enumerable
*/
function totalSupply() external view returns (uint256) {
return mintedTotal;
}
/**
* @dev Returns the number of tokens than could still be minted
* @return Number of tokens
*/
function remainingSupply() external view returns (uint256) {
return MAX_SUPPLY - mintedTotal;
}
/**
* @dev Returns the number of tokens that could still be issued for sale
* @return Number of tokens
*/
function remainingUnissuedSupply() public view returns (uint256) {
return MAX_SUPPLY - MAX_OWNER_RESERVE - issuedTotal;
}
/**
* @dev Returns the number of issued tokens that could still be minted
* @return Number of tokens
*/
function remainingUnsoldSupply() public view returns (uint256) {
return issuedTotal - (mintedTotal - reserveMintedTotal);
}
/**
* @dev Returns the number of tokens that could still be reserve minted by the owner
* @return Numer of tokens
*/
function remainingOwnerReserve() public view returns (uint256) {
return MAX_OWNER_RESERVE - reserveMintedTotal;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | Disables minting for non-whitelisted addresses/ | function disablePublicSale() external onlyOwner {
publicSaleEnabled = false;
}
| 11,672,784 |
pragma solidity ^0.4.18;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;
}
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
}
contract TokenERC20 is owned {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
name = tokenName;
symbol = tokenSymbol;
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
}
function mintTokens(address target, uint256 mintedAmount) public onlyOwner {
// TODO: value overflow
require(balanceOf[target] + mintedAmount > balanceOf[target]);
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, owner, mintedAmount);
Transfer(owner, target, mintedAmount);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function _transfer(address _from, address _to, uint256 _value) private {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]); // Overflow is interesting
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transferFrom(address _from, address _to, uint256 value) public returns (bool success) {
require(value < allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= value;
_transfer(_from, _to, value);
return true;
}
// weird but allow others to send tokens on your behalf
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
// TODO: what does this even tdo?
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
// burn from myself
function burn(uint256 amount) public returns (bool success) {
require(amount <= balanceOf[msg.sender]);
balanceOf[msg.sender] -= amount;
totalSupply -= amount;
Burn(msg.sender, amount);
return true;
}
function burnFrom(address _from, uint256 amount) public returns (bool success) {
require(amount <= allowance[_from][msg.sender]);
require(amount <= balanceOf[_from]);
balanceOf[_from] -= amount;
allowance[_from][msg.sender] -= amount;
totalSupply -= amount;
Burn(_from, amount);
return true;
}
}
/******************************************/
/* ADVANCED TOKEN STARTS HERE */
/******************************************/
contract MegaUberToken is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
uint256 public minBalanceForAccounts;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function MegaUberToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol,
address centralMinter
) TokenERC20 (
initialSupply,
tokenName,
tokenSymbol
) public {
if (centralMinter != 0) {
owner = centralMinter;
}
}
function _transfer(address _from, address _to, uint256 _value) private {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]); // Overflow is interesting
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
if (msg.sender.balance < minBalanceForAccounts) {
// This is confusing but it will multiply val by sellPrice again to find amount.
sell((minBalanceForAccounts - msg.sender.balance) / sellPrice);
}
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyOwner {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
// Called by user?
// ether -> panda
// The actual transfer to the contract happens somewhere else it hink.
// One ether is 1000000000000000000 wei. So when setting prices for your token in ether, add 18 zeros at the end.
function buy() public payable returns (uint) {
uint amount = msg.value / buyPrice;
// require(balanceOf[msg.sender] + amount > balanceOf[msg.sender]);
// require(balanceOf[this] >= amount);
balanceOf[this] -= amount;
balanceOf[msg.sender] += amount;
Transfer(this, msg.sender, amount);
return amount;
}
// panda -> ether
function sell(uint amount) public payable returns (uint) {
require(balanceOf[this] + amount > balanceOf[this]);
require(balanceOf[msg.sender] >= amount);
balanceOf[this] += amount;
balanceOf[msg.sender] -= amount;
// TODO: why * sellPrice?
uint revenue = amount * sellPrice; // 10 @ .005 (.005 ether per share), but it's all wei
require(msg.sender.send(revenue));
Transfer(msg.sender, this, amount);
return revenue;
}
function freezeAccount(address target, bool freeze) public onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setMinBalanceForAccounts(uint256 minBalanceInFinney) public onlyOwner {
minBalanceForAccounts = minBalanceInFinney * 1 finney;
}
}
| panda -> ether TODO: why sellPrice? | function sell(uint amount) public payable returns (uint) {
require(balanceOf[this] + amount > balanceOf[this]);
require(balanceOf[msg.sender] >= amount);
balanceOf[this] += amount;
balanceOf[msg.sender] -= amount;
require(msg.sender.send(revenue));
Transfer(msg.sender, this, amount);
return revenue;
}
| 12,600,277 |
pragma solidity ^0.5.16;
import "./CErc20.sol";
/**
* @title Compound's CErc20Immutable Contract
* @notice CTokens which wrap an EIP-20 underlying and are immutable
* @author Compound
*/
contract CErc20Immutable is CErc20 {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
*/
constructor(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// Initialize the market
initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set the proper admin now that initialization is done
admin = admin_;
}
}
pragma solidity ^0.5.16;
import "./CToken.sol";
/**
* @title Compound's CErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.16;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
| Multiply an Exp by a scalar, then truncate to return an unsigned integer./ | function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
| 17,798 |
/**
*Submitted for verification at Etherscan.io on 2021-08-11
*/
// File: iface/IERC20.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
/**
* @dev 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: ParassetERC20.sol
pragma solidity ^0.8.4;
/*
* @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;
}
}
contract ParassetERC20 is Context, IERC20 {
mapping(address => uint256) _balances;
mapping(address => mapping(address => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
constructor() { }
/**
* @dev Returns the name of the token.
*/
function name() public view 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");
unchecked {
_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");
unchecked {
_approve(_msgSender(), 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:
*
* - `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");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, 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);
}
}
// File: iface/IParassetGovernance.sol
pragma solidity ^0.8.4;
/// @dev This interface defines the governance methods
interface IParassetGovernance {
/// @dev Set governance authority
/// @param addr Destination address
/// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function setGovernance(address addr, uint flag) external;
/// @dev Get governance rights
/// @param addr Destination address
/// @return Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function getGovernance(address addr) external view returns (uint);
/// @dev Check whether the target address has governance rights for the given target
/// @param addr Destination address
/// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check
/// @return True indicates permission
function checkGovernance(address addr, uint flag) external view returns (bool);
}
// File: ParassetBase.sol
pragma solidity ^0.8.4;
contract ParassetBase {
// Lock flag
uint256 _locked;
/// @dev To support open-zeppelin/upgrades
/// @param governance IParassetGovernance implementation contract address
function initialize(address governance) public virtual {
require(_governance == address(0), "Log:ParassetBase!initialize");
_governance = governance;
_locked = 0;
}
/// @dev IParassetGovernance implementation contract address
address public _governance;
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(newGovernance) when overriding, and override method without onlyGovernance
/// @param newGovernance IParassetGovernance implementation contract address
function update(address newGovernance) public virtual {
address governance = _governance;
require(governance == msg.sender || IParassetGovernance(governance).checkGovernance(msg.sender, 0), "Log:ParassetBase:!gov");
_governance = newGovernance;
}
/// @dev Uniform accuracy
/// @param inputToken Initial token
/// @param inputTokenAmount Amount of token
/// @param outputToken Converted token
/// @return stability Amount of outputToken
function getDecimalConversion(
address inputToken,
uint256 inputTokenAmount,
address outputToken
) public view returns(uint256) {
uint256 inputTokenDec = 18;
uint256 outputTokenDec = 18;
if (inputToken != address(0x0)) {
inputTokenDec = IERC20(inputToken).decimals();
}
if (outputToken != address(0x0)) {
outputTokenDec = IERC20(outputToken).decimals();
}
return inputTokenAmount * (10**outputTokenDec) / (10**inputTokenDec);
}
//---------modifier------------
modifier onlyGovernance() {
require(IParassetGovernance(_governance).checkGovernance(msg.sender, 0), "Log:ParassetBase:!gov");
_;
}
modifier nonReentrant() {
require(_locked == 0, "Log:ParassetBase:!_locked");
_locked = 1;
_;
_locked = 0;
}
}
// File: lib/TransferHelper.sol
pragma solidity ^0.8.4;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: iface/ILPStakingMiningPool.sol
pragma solidity ^0.8.4;
interface ILPStakingMiningPool {
function getBlock(uint256 endBlock) external view returns(uint256);
function getBalance(address stakingToken, address account) external view returns(uint256);
function getChannelInfo(address stakingToken) external view returns(uint256 lastUpdateBlock, uint256 endBlock, uint256 rewardRate, uint256 rewardPerTokenStored, uint256 totalSupply);
function getAccountReward(address stakingToken, address account) external view returns(uint256);
function stake(uint256 amount, address stakingToken) external;
function withdraw(uint256 amount, address stakingToken) external;
function getReward(address stakingToken) external;
}
// File: iface/IParasset.sol
pragma solidity ^0.8.4;
interface IParasset {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function destroy(uint256 amount, address account) external;
function issuance(uint256 amount, address account) external;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: iface/IInsurancePool.sol
pragma solidity ^0.8.4;
interface IInsurancePool {
/// @dev Destroy ptoken, update negative ledger
/// @param amount quantity destroyed
function destroyPToken(uint256 amount) external;
/// @dev Clear negative books
function eliminate() external;
}
// File: InsurancePool.sol
pragma solidity ^0.8.4;
contract InsurancePool is ParassetBase, IInsurancePool, ParassetERC20 {
// negative account funds
uint256 public _insNegative;
// latest redemption time
uint256 public _latestTime;
// status
uint8 public _flag; // = 0: pause
// = 1: active
// = 2: redemption only
// user address => freeze LP data
mapping(address => Frozen) _frozenIns;
struct Frozen {
// frozen quantity
uint256 amount;
// freezing time
uint256 time;
}
// pToken address
address public _pTokenAddress;
// redemption cycle, 2 days
uint96 public _redemptionCycle;
// underlyingToken address
address public _underlyingTokenAddress;
// redemption duration, 7 days
uint96 public _waitCycle;
// mortgagePool address
address public _mortgagePool;
// rate(2/1000)
uint96 public _feeRate;
uint constant MINIMUM_LIQUIDITY = 1e9;
// staking address
ILPStakingMiningPool _lpStakingMiningPool;
event SubNegative(uint256 amount, uint256 allValue);
event AddNegative(uint256 amount, uint256 allValue);
function initialize(address governance) public override {
super.initialize(governance);
_redemptionCycle = 15 minutes;
_waitCycle = 30 minutes;
_feeRate = 2;
_totalSupply = 0;
}
//---------modifier---------
modifier onlyMortgagePool() {
require(msg.sender == address(_mortgagePool), "Log:InsurancePool:!mortgagePool");
_;
}
modifier whenActive() {
require(_flag == 1, "Log:InsurancePool:!active");
_;
}
modifier redemptionOnly() {
require(_flag != 0, "Log:InsurancePool:!0");
_;
}
//---------view---------
/// @dev View the lpStakingMiningPool address
/// @return lpStakingMiningPool address
function getLPStakingMiningPool() external view returns(address) {
return address(_lpStakingMiningPool);
}
/// @dev View the all lp
/// @return all lp
function getAllLP(address user) public view returns(uint256) {
return _balances[user] + _lpStakingMiningPool.getBalance(address(this), user);
}
/// @dev View redemption period, next time
/// @return startTime start time
/// @return endTime end time
function getRedemptionTime() external view returns(uint256 startTime, uint256 endTime) {
uint256 time = _latestTime;
if (block.timestamp > time) {
uint256 subTime = (block.timestamp - time) / uint256(_waitCycle);
endTime = time + (uint256(_waitCycle) * (1 + subTime));
} else {
endTime = time;
}
startTime = endTime - uint256(_redemptionCycle);
}
/// @dev View frozen LP and unfreeze time
/// @param add user address
/// @return frozen LP
/// @return unfreeze time
function getFrozenIns(address add) external view returns(uint256, uint256) {
Frozen memory frozenInfo = _frozenIns[add];
return (frozenInfo.amount, frozenInfo.time);
}
/// @dev View frozen LP and unfreeze time, real time
/// @param add user address
/// @return frozen LP
function getFrozenInsInTime(address add) external view returns(uint256) {
Frozen memory frozenInfo = _frozenIns[add];
if (block.timestamp > frozenInfo.time) {
return 0;
}
return frozenInfo.amount;
}
/// @dev View redeemable LP, real time
/// @param add user address
/// @return redeemable LP
function getRedemptionAmount(address add) external view returns (uint256) {
Frozen memory frozenInfo = _frozenIns[add];
uint256 balanceSelf = _balances[add];
if (block.timestamp > frozenInfo.time) {
return balanceSelf;
} else {
return balanceSelf - frozenInfo.amount;
}
}
//---------governance----------
/// @dev Set token name
/// @param name token name
/// @param symbol token symbol
function setTokenInfo(string memory name, string memory symbol) external onlyGovernance {
_name = name;
_symbol = symbol;
}
/// @dev Set contract status
/// @param num 0: pause, 1: active, 2: redemption only
function setFlag(uint8 num) external onlyGovernance {
_flag = num;
}
/// @dev Set mortgage pool address
function setMortgagePool(address add) external onlyGovernance {
_mortgagePool = add;
}
/// @dev Set the staking contract address
function setLPStakingMiningPool(address add) external onlyGovernance {
_lpStakingMiningPool = ILPStakingMiningPool(add);
}
/// @dev Set the latest redemption time
function setLatestTime(uint256 num) external onlyGovernance {
_latestTime = num;
}
/// @dev Set the rate
function setFeeRate(uint96 num) external onlyGovernance {
_feeRate = num;
}
/// @dev Set redemption cycle
function setRedemptionCycle(uint256 num) external onlyGovernance {
require(num > 0, "Log:InsurancePool:!zero");
_redemptionCycle = uint96(num * 1 days);
}
/// @dev Set redemption duration
function setWaitCycle(uint256 num) external onlyGovernance {
require(num > 0, "Log:InsurancePool:!zero");
_waitCycle = uint96(num * 1 days);
}
/// @dev Set the underlying asset and PToken mapping and
/// @param uToken underlying asset address
/// @param pToken PToken address
function setInfo(address uToken, address pToken) external onlyGovernance {
_underlyingTokenAddress = uToken;
_pTokenAddress = pToken;
}
function test_insNegative(uint256 amount) external onlyGovernance {
_insNegative = amount;
}
//---------transaction---------
/// @dev Exchange: PToken exchanges the underlying asset
/// @param amount amount of PToken
function exchangePTokenToUnderlying(uint256 amount) public redemptionOnly nonReentrant {
// amount > 0
require(amount > 0, "Log:InsurancePool:!amount");
// Calculate the fee
uint256 fee = amount * _feeRate / 1000;
// Transfer to the PToken
address pTokenAddress = _pTokenAddress;
TransferHelper.safeTransferFrom(pTokenAddress, msg.sender, address(this), amount);
// Calculate the amount of transferred underlying asset
uint256 uTokenAmount = getDecimalConversion(pTokenAddress, amount - fee, _underlyingTokenAddress);
require(uTokenAmount > 0, "Log:InsurancePool:!uTokenAmount");
// Transfer out underlying asset
if (_underlyingTokenAddress == address(0x0)) {
TransferHelper.safeTransferETH(msg.sender, uTokenAmount);
} else {
TransferHelper.safeTransfer(_underlyingTokenAddress, msg.sender, uTokenAmount);
}
// Eliminate negative ledger
eliminate();
}
/// @dev Exchange: underlying asset exchanges the PToken
/// @param amount amount of underlying asset
function exchangeUnderlyingToPToken(uint256 amount) public payable redemptionOnly nonReentrant {
// amount > 0
require(amount > 0, "Log:InsurancePool:!amount");
// Calculate the fee
uint256 fee = amount * _feeRate / 1000;
// Transfer to the underlying asset
if (_underlyingTokenAddress == address(0x0)) {
// The underlying asset is ETH
require(msg.value == amount, "Log:InsurancePool:!msg.value");
} else {
// The underlying asset is ERC20
require(msg.value == 0, "Log:InsurancePool:msg.value!=0");
TransferHelper.safeTransferFrom(_underlyingTokenAddress, msg.sender, address(this), amount);
}
// Calculate the amount of transferred PTokens
uint256 pTokenAmount = getDecimalConversion(_underlyingTokenAddress, amount - fee, address(0x0));
require(pTokenAmount > 0, "Log:InsurancePool:!pTokenAmount");
// Transfer out PToken
address pTokenAddress = _pTokenAddress;
uint256 pTokenBalance = IERC20(pTokenAddress).balanceOf(address(this));
if (pTokenBalance < pTokenAmount) {
// Insufficient PToken balance,
uint256 subNum = pTokenAmount - pTokenBalance;
_issuancePToken(subNum);
}
TransferHelper.safeTransfer(pTokenAddress, msg.sender, pTokenAmount);
}
/// @dev Subscribe for insurance
/// @param amount amount of underlying asset
function subscribeIns(uint256 amount) public payable whenActive nonReentrant {
// amount > 0
require(amount > 0, "Log:InsurancePool:!amount");
// Update redemption time
updateLatestTime();
// Thaw LP
Frozen storage frozenInfo = _frozenIns[msg.sender];
if (block.timestamp > frozenInfo.time) {
frozenInfo.amount = 0;
}
// PToken balance
uint256 pTokenBalance = IERC20(_pTokenAddress).balanceOf(address(this));
// underlying asset balance
uint256 tokenBalance;
if (_underlyingTokenAddress == address(0x0)) {
// The amount of ETH involved in the calculation does not include the transfer in this time
require(msg.value == amount, "Log:InsurancePool:!msg.value");
tokenBalance = address(this).balance - amount;
} else {
require(msg.value == 0, "Log:InsurancePool:msg.value!=0");
// Underlying asset conversion 18 decimals
tokenBalance = getDecimalConversion(_underlyingTokenAddress, IERC20(_underlyingTokenAddress).balanceOf(address(this)), address(0x0));
}
// Calculate LP
uint256 insAmount = 0;
uint256 insTotal = _totalSupply;
uint256 allBalance = tokenBalance + pTokenBalance;
if (insTotal != 0) {
// Insurance pool assets must be greater than 0
require(allBalance > _insNegative, "Log:InsurancePool:allBalanceNotEnough");
uint256 allValue = allBalance - _insNegative;
insAmount = getDecimalConversion(_underlyingTokenAddress, amount, address(0x0)) * insTotal / allValue;
} else {
// The initial net value is 1
insAmount = getDecimalConversion(_underlyingTokenAddress, amount, address(0x0)) - MINIMUM_LIQUIDITY;
_issuance(MINIMUM_LIQUIDITY, address(0x0));
}
// Transfer to the underlying asset(ERC20)
if (_underlyingTokenAddress != address(0x0)) {
require(msg.value == 0, "Log:InsurancePool:msg.value!=0");
TransferHelper.safeTransferFrom(_underlyingTokenAddress, msg.sender, address(this), amount);
}
// Additional LP issuance
_issuance(insAmount, msg.sender);
// Freeze insurance LP
frozenInfo.amount = frozenInfo.amount + insAmount;
frozenInfo.time = _latestTime;
}
/// @dev Redemption insurance
/// @param amount redemption LP
function redemptionIns(uint256 amount) public redemptionOnly nonReentrant {
// amount > 0
require(amount > 0, "Log:InsurancePool:!amount");
// Update redemption time
updateLatestTime();
// Judging the redemption time
uint256 tokenTime = _latestTime;
require(block.timestamp < tokenTime && block.timestamp > tokenTime - uint256(_redemptionCycle), "Log:InsurancePool:!time");
// Thaw LP
Frozen storage frozenInfo = _frozenIns[msg.sender];
if (block.timestamp > frozenInfo.time) {
frozenInfo.amount = 0;
}
// PToken balance
uint256 pTokenBalance = IERC20(_pTokenAddress).balanceOf(address(this));
// underlying asset balance
uint256 tokenBalance;
if (_underlyingTokenAddress == address(0x0)) {
tokenBalance = address(this).balance;
} else {
tokenBalance = getDecimalConversion(_underlyingTokenAddress, IERC20(_underlyingTokenAddress).balanceOf(address(this)), address(0x0));
}
// Insurance pool assets must be greater than 0
uint256 allBalance = tokenBalance + pTokenBalance;
require(allBalance > _insNegative, "Log:InsurancePool:allBalanceNotEnough");
// Calculated amount of assets
uint256 allValue = allBalance - _insNegative;
uint256 insTotal = _totalSupply;
uint256 underlyingAmount = amount * allValue / insTotal;
// Destroy LP
_destroy(amount, msg.sender);
// Judgment to freeze LP
require(getAllLP(msg.sender) >= frozenInfo.amount, "Log:InsurancePool:frozen");
// Transfer out assets, priority transfer of the underlying assets, if the underlying assets are insufficient, transfer ptoken
if (_underlyingTokenAddress == address(0x0)) {
// ETH
if (tokenBalance >= underlyingAmount) {
TransferHelper.safeTransferETH(msg.sender, underlyingAmount);
} else {
TransferHelper.safeTransferETH(msg.sender, tokenBalance);
TransferHelper.safeTransfer(_pTokenAddress, msg.sender, underlyingAmount - tokenBalance);
}
} else {
// ERC20
if (tokenBalance >= underlyingAmount) {
TransferHelper.safeTransfer(_underlyingTokenAddress, msg.sender, getDecimalConversion(_pTokenAddress, underlyingAmount, _underlyingTokenAddress));
} else {
TransferHelper.safeTransfer(_underlyingTokenAddress, msg.sender, getDecimalConversion(_pTokenAddress, tokenBalance, _underlyingTokenAddress));
TransferHelper.safeTransfer(_pTokenAddress, msg.sender, underlyingAmount - tokenBalance);
}
}
}
/// @dev Destroy PToken, update negative ledger
/// @param amount quantity destroyed
function destroyPToken(uint256 amount) public override onlyMortgagePool {
_insNegative = _insNegative + amount;
emit AddNegative(amount, _insNegative);
eliminate();
}
/// @dev Issuance PToken, update negative ledger
/// @param amount Additional issuance quantity
function _issuancePToken(uint256 amount) private {
IParasset(_pTokenAddress).issuance(amount, address(this));
_insNegative = _insNegative + amount;
emit AddNegative(amount, _insNegative);
}
/// @dev Clear negative books
function eliminate() override public {
IParasset pErc20 = IParasset(_pTokenAddress);
// negative ledger
uint256 negative = _insNegative;
// PToken balance
uint256 pTokenBalance = pErc20.balanceOf(address(this));
if (negative > 0 && pTokenBalance > 0) {
if (negative >= pTokenBalance) {
// Increase negative ledger
pErc20.destroy(pTokenBalance, address(this));
_insNegative = _insNegative - pTokenBalance;
emit SubNegative(pTokenBalance, _insNegative);
} else {
// negative ledger = 0
pErc20.destroy(negative, address(this));
_insNegative = 0;
emit SubNegative(negative, _insNegative);
}
}
}
/// @dev Update redemption time
function updateLatestTime() public {
uint256 time = _latestTime;
if (block.timestamp > time) {
uint256 subTime = (block.timestamp - time) / uint256(_waitCycle);
_latestTime = time + (uint256(_waitCycle) * (1 + subTime));
}
}
/// @dev Destroy LP
/// @param amount quantity destroyed
/// @param account destroy address
function _destroy(
uint256 amount,
address account
) private {
require(_balances[account] >= amount, "Log:InsurancePool:!destroy");
_balances[account] = _balances[account] - amount;
_totalSupply = _totalSupply - amount;
// emit Destroy(amount, account);
emit Transfer(account, address(0x0), amount);
}
/// @dev Additional LP issuance
/// @param amount additional issuance quantity
/// @param account additional issuance address
function _issuance(
uint256 amount,
address account
) private {
_balances[account] = _balances[account] + amount;
_totalSupply = _totalSupply + amount;
// emit Issuance(amount, account);
emit Transfer(address(0x0), account, amount);
}
/**
* @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:
*
* - `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 override {
// Update redemption time
updateLatestTime();
// Thaw LP
Frozen storage frozenInfo = _frozenIns[sender];
if (block.timestamp > frozenInfo.time) {
frozenInfo.amount = 0;
}
require(sender != address(0), "ERC20: transfer from the zero address");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
if (recipient != address(_lpStakingMiningPool)) {
require(getAllLP(sender) >= frozenInfo.amount, "Log:InsurancePool:frozen");
}
}
/// The insurance pool penetrates the warehouse, and external assets are added to the insurance pool.
function addETH() external payable {}
} | View frozen LP and unfreeze time, real time add user address return frozen LP | function getFrozenInsInTime(address add) external view returns(uint256) {
Frozen memory frozenInfo = _frozenIns[add];
if (block.timestamp > frozenInfo.time) {
return 0;
}
return frozenInfo.amount;
}
| 2,317,967 |
./full_match/5/0x28f083f2115fbE136F2c664E90DBc27429C55c9F/sources/src/Exchanger.sol | Example for feedID = "ETH-USD": https:<mercury host>/?feedIDHex=0x2430f68ea2e8d4151992bb7fc3a4c472087a6149bf7e0232704396162ab7c1f7&L2Blocknumber=1000 | function _ccipReadURL(bytes32 feedID, uint256 commitmentBlock)
private
view
returns (string memory url)
{
return
string(
abi.encodePacked(
abi.decode(s_lookupURL, (string)),
"?feedIDHex=",
Strings.toHexString(uint256(feedID)),
"&L2Blocknumber=",
Strings.toString(commitmentBlock)
)
);
}
| 7,079,579 |
./full_match/43113/0xF20cCae781689fE736e2f89142e26352393Bd199/sources/Vikings.sol | Gets the total available reward balance of all tokens owned by the specified address./ | function getRewardBalance(address _addr) public view returns(uint256) {
uint256 totalBalance = 0;
uint count = balanceOf(_addr);
for (uint i = 0; i < count; i++) {
uint id = tokenOfOwnerByIndex(_addr, i);
totalBalance += getRewardBalance(id);
}
return totalBalance;
}
| 7,168,796 |
// Copyright 2019 Cartesi Pte. Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
/// @title ArithmeticImmediateInstructions
pragma solidity ^0.7.0;
import "../MemoryInteractor.sol";
import "../RiscVDecoder.sol";
import "../RiscVConstants.sol";
library ArithmeticImmediateInstructions {
function getRs1Imm(MemoryInteractor mi, uint32 insn) internal
returns(uint64 rs1, int32 imm)
{
rs1 = mi.readX(RiscVDecoder.insnRs1(insn));
imm = RiscVDecoder.insnIImm(insn);
}
// ADDI adds the sign extended 12 bits immediate to rs1. Overflow is ignored.
// Reference: riscv-spec-v2.2.pdf - Page 13
function executeADDI(MemoryInteractor mi, uint32 insn) public returns (uint64) {
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
int64 val = int64(rs1) + int64(imm);
return uint64(val);
}
// ADDIW adds the sign extended 12 bits immediate to rs1 and produces to correct
// sign extension for 32 bits at rd. Overflow is ignored and the result is the
// low 32 bits of the result sign extended to 64 bits.
// Reference: riscv-spec-v2.2.pdf - Page 30
function executeADDIW(MemoryInteractor mi, uint32 insn) public returns (uint64) {
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
return uint64(int32(rs1) + imm);
}
// SLLIW is analogous to SLLI but operate on 32 bit values.
// The amount of shifts are enconded on the lower 5 bits of I-imm.
// Reference: riscv-spec-v2.2.pdf - Section 4.2 - Page 30
function executeSLLIW(MemoryInteractor mi, uint32 insn) public returns (uint64) {
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
int32 rs1w = int32(rs1) << uint32(imm & 0x1F);
return uint64(rs1w);
}
// ORI performs logical Or bitwise operation on register rs1 and the sign-extended
// 12 bit immediate. It places the result in rd.
// Reference: riscv-spec-v2.2.pdf - Section 2.4 - Page 14
function executeORI(MemoryInteractor mi, uint32 insn) public returns (uint64) {
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
return rs1 | uint64(imm);
}
// SLLI performs the logical left shift. The operand to be shifted is in rs1
// and the amount of shifts are encoded on the lower 6 bits of I-imm.(RV64)
// Reference: riscv-spec-v2.2.pdf - Section 2.4 - Page 14
function executeSLLI(MemoryInteractor mi, uint32 insn) public returns(uint64) {
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
return rs1 << uint32(imm & 0x3F);
}
// SLRI instructions is a logical shift right instruction. The variable to be
// shift is in rs1 and the amount of shift operations is encoded in the lower
// 6 bits of the I-immediate field.
function executeSRLI(MemoryInteractor mi, uint32 insn) public returns(uint64) {
// Get imm's lower 6 bits
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
uint32 shiftAmount = uint32(imm & int32(RiscVConstants.getXlen() - 1));
return rs1 >> shiftAmount;
}
// SRLIW instructions operates on a 32bit value and produce a signed results.
// The variable to be shift is in rs1 and the amount of shift operations is
// encoded in the lower 6 bits of the I-immediate field.
function executeSRLIW(MemoryInteractor mi, uint32 insn) public returns(uint64) {
// Get imm's lower 6 bits
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
int32 rs1w = int32(uint32(rs1) >> uint32(imm & 0x1F));
return uint64(rs1w);
}
// SLTI - Set less than immediate. Places value 1 in rd if rs1 is less than
// the signed extended imm when both are signed. Else 0 is written.
// Reference: riscv-spec-v2.2.pdf - Section 2.4 - Page 13.
function executeSLTI(MemoryInteractor mi, uint32 insn) public returns (uint64) {
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
return (int64(rs1) < int64(imm))? 1 : 0;
}
// SLTIU is analogous to SLLTI but treats imm as unsigned.
// Reference: riscv-spec-v2.2.pdf - Section 2.4 - Page 14
function executeSLTIU(MemoryInteractor mi, uint32 insn) public returns (uint64) {
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
return (rs1 < uint64(imm))? 1 : 0;
}
// SRAIW instructions operates on a 32bit value and produce a signed results.
// The variable to be shift is in rs1 and the amount of shift operations is
// encoded in the lower 6 bits of the I-immediate field.
function executeSRAIW(MemoryInteractor mi, uint32 insn) public returns(uint64) {
// Get imm's lower 6 bits
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
int32 rs1w = int32(rs1) >> uint32(imm & 0x1F);
return uint64(rs1w);
}
// TO-DO: make sure that >> is now arithmetic shift and not logical shift
// SRAI instruction is analogous to SRAIW but for RV64I
function executeSRAI(MemoryInteractor mi, uint32 insn) public returns(uint64) {
// Get imm's lower 6 bits
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
return uint64(int64(rs1) >> uint256(int64(imm) & int64((RiscVConstants.getXlen() - 1))));
}
// XORI instructions performs XOR operation on register rs1 and hhe sign extended
// 12 bit immediate, placing result in rd.
function executeXORI(MemoryInteractor mi, uint32 insn) public returns(uint64) {
// Get imm's lower 6 bits
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
return rs1 ^ uint64(imm);
}
// ANDI instructions performs AND operation on register rs1 and hhe sign extended
// 12 bit immediate, placing result in rd.
function executeANDI(MemoryInteractor mi, uint32 insn) public returns(uint64) {
// Get imm's lower 6 bits
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
//return (rs1 & uint64(imm) != 0)? 1 : 0;
return rs1 & uint64(imm);
}
/// @notice Given a arithmetic immediate32 funct3 insn, finds the associated func.
// Uses binary search for performance.
// @param insn for arithmetic immediate32 funct3 field.
function arithmeticImmediate32Funct3(MemoryInteractor mi, uint32 insn)
public returns (uint64, bool)
{
uint32 funct3 = RiscVDecoder.insnFunct3(insn);
if (funct3 == 0x0000) {
/*funct3 == 0x0000*/
//return "ADDIW";
return (executeADDIW(mi, insn), true);
} else if (funct3 == 0x0005) {
/*funct3 == 0x0005*/
return shiftRightImmediate32Group(mi, insn);
} else if (funct3 == 0x0001) {
/*funct3 == 0x0001*/
//return "SLLIW";
return (executeSLLIW(mi, insn), true);
}
return (0, false);
}
/// @notice Given a arithmetic immediate funct3 insn, finds the func associated.
// Uses binary search for performance.
// @param insn for arithmetic immediate funct3 field.
function arithmeticImmediateFunct3(MemoryInteractor mi, uint32 insn)
public returns (uint64, bool)
{
uint32 funct3 = RiscVDecoder.insnFunct3(insn);
if (funct3 < 0x0003) {
if (funct3 == 0x0000) {
/*funct3 == 0x0000*/
return (executeADDI(mi, insn), true);
} else if (funct3 == 0x0002) {
/*funct3 == 0x0002*/
return (executeSLTI(mi, insn), true);
} else if (funct3 == 0x0001) {
// Imm[11:6] must be zero for it to be SLLI.
// Reference: riscv-spec-v2.2.pdf - Section 2.4 - Page 14
if (( insn & (0x3F << 26)) != 0) {
return (0, false);
}
return (executeSLLI(mi, insn), true);
}
} else if (funct3 > 0x0003) {
if (funct3 < 0x0006) {
if (funct3 == 0x0004) {
/*funct3 == 0x0004*/
return (executeXORI(mi, insn), true);
} else if (funct3 == 0x0005) {
/*funct3 == 0x0005*/
return shiftRightImmediateFunct6(mi, insn);
}
} else if (funct3 == 0x0007) {
/*funct3 == 0x0007*/
return (executeANDI(mi, insn), true);
} else if (funct3 == 0x0006) {
/*funct3 == 0x0006*/
return (executeORI(mi, insn), true);
}
} else if (funct3 == 0x0003) {
/*funct3 == 0x0003*/
return (executeSLTIU(mi, insn), true);
}
return (0, false);
}
/// @notice Given a right immediate funct6 insn, finds the func associated.
// Uses binary search for performance.
// @param insn for right immediate funct6 field.
function shiftRightImmediateFunct6(MemoryInteractor mi, uint32 insn)
public returns (uint64, bool)
{
uint32 funct6 = RiscVDecoder.insnFunct6(insn);
if (funct6 == 0x0000) {
/*funct6 == 0x0000*/
return (executeSRLI(mi, insn), true);
} else if (funct6 == 0x0010) {
/*funct6 == 0x0010*/
return (executeSRAI(mi, insn), true);
}
//return "illegal insn";
return (0, false);
}
/// @notice Given a shift right immediate32 funct3 insn, finds the associated func.
// Uses binary search for performance.
// @param insn for shift right immediate32 funct3 field.
function shiftRightImmediate32Group(MemoryInteractor mi, uint32 insn)
public returns (uint64, bool)
{
uint32 funct7 = RiscVDecoder.insnFunct7(insn);
if (funct7 == 0x0000) {
/*funct7 == 0x0000*/
return (executeSRLIW(mi, insn), true);
} else if (funct7 == 0x0020) {
/*funct7 == 0x0020*/
return (executeSRAIW(mi, insn), true);
}
return (0, false);
}
}
| SRAIW instructions operates on a 32bit value and produce a signed results. The variable to be shift is in rs1 and the amount of shift operations is encoded in the lower 6 bits of the I-immediate field. Get imm's lower 6 bits | function executeSRAIW(MemoryInteractor mi, uint32 insn) public returns(uint64) {
(uint64 rs1, int32 imm) = getRs1Imm(mi, insn);
int32 rs1w = int32(rs1) >> uint32(imm & 0x1F);
return uint64(rs1w);
}
| 12,830,566 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "../balancer/BFactory.sol";
import "../libraries/SafeMathUint256.sol";
import "./AbstractMarketFactoryV3.sol";
import "../balancer/BNum.sol";
contract AMMFactory is BNum {
using SafeMathUint256 for uint256;
uint256 private constant MAX_UINT = 2**256 - 1;
uint256 private constant MIN_INITIAL_LIQUIDITY = BONE * 100;
BFactory public bFactory;
// MarketFactory => Market => BPool
mapping(address => mapping(uint256 => BPool)) public pools;
uint256 fee;
event PoolCreated(
address pool,
address indexed marketFactory,
uint256 indexed marketId,
address indexed creator,
address lpTokenRecipient
);
event LiquidityChanged(
address indexed marketFactory,
uint256 indexed marketId,
address indexed user,
address recipient,
// from the perspective of the user. e.g. collateral is negative when adding liquidity
int256 collateral,
int256 lpTokens,
uint256[] sharesReturned
);
event SharesSwapped(
address indexed marketFactory,
uint256 indexed marketId,
address indexed user,
uint256 outcome,
// from the perspective of the user. e.g. collateral is negative when buying
int256 collateral,
int256 shares,
uint256 price
);
constructor(BFactory _bFactory, uint256 _fee) {
bFactory = _bFactory;
fee = _fee;
}
function createPool(
AbstractMarketFactoryV3 _marketFactory,
uint256 _marketId,
uint256 _initialLiquidity,
address _lpTokenRecipient
) public returns (uint256) {
require(pools[address(_marketFactory)][_marketId] == BPool(0), "Pool already created");
AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId);
uint256 _sets = _marketFactory.calcShares(_initialLiquidity);
// Comparing to sets because sets are normalized to 10e18.
require(_sets >= MIN_INITIAL_LIQUIDITY, "Initial liquidity must be at least 100 collateral.");
// Turn collateral into shares
IERC20Full _collateral = _marketFactory.collateral();
require(
_collateral.allowance(msg.sender, address(this)) >= _initialLiquidity,
"insufficient collateral allowance for initial liquidity"
);
_collateral.transferFrom(msg.sender, address(this), _initialLiquidity);
_collateral.approve(address(_marketFactory), MAX_UINT);
_marketFactory.mintShares(_marketId, _sets, address(this));
// Create pool
BPool _pool = bFactory.newBPool();
// Add each outcome to the pool. Collateral is NOT added.
for (uint256 i = 0; i < _market.shareTokens.length; i++) {
OwnedERC20 _token = _market.shareTokens[i];
_token.approve(address(_pool), MAX_UINT);
_pool.bind(address(_token), _sets, _market.initialOdds[i]);
}
// Set the swap fee.
_pool.setSwapFee(fee);
// Finalize pool setup
_pool.finalize();
pools[address(_marketFactory)][_marketId] = _pool;
// Pass along LP tokens for initial liquidity
uint256 _lpTokenBalance = _pool.balanceOf(address(this)) - (BONE / 1000);
// Burn (BONE / 1000) lp tokens to prevent the bpool from locking up. When all liquidity is removed.
_pool.transfer(address(0x0), (BONE / 1000));
_pool.transfer(_lpTokenRecipient, _lpTokenBalance);
uint256[] memory _balances = new uint256[](_market.shareTokens.length);
for (uint256 i = 0; i < _market.shareTokens.length; i++) {
_balances[i] = 0;
}
emit PoolCreated(address(_pool), address(_marketFactory), _marketId, msg.sender, _lpTokenRecipient);
emit LiquidityChanged(
address(_marketFactory),
_marketId,
msg.sender,
_lpTokenRecipient,
-int256(_initialLiquidity),
int256(_lpTokenBalance),
_balances
);
return _lpTokenBalance;
}
function addLiquidity(
AbstractMarketFactoryV3 _marketFactory,
uint256 _marketId,
uint256 _collateralIn,
uint256 _minLPTokensOut,
address _lpTokenRecipient
) public returns (uint256 _poolAmountOut, uint256[] memory _balances) {
BPool _pool = pools[address(_marketFactory)][_marketId];
require(_pool != BPool(0), "Pool needs to be created");
AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId);
// Turn collateral into shares
IERC20Full _collateral = _marketFactory.collateral();
_collateral.transferFrom(msg.sender, address(this), _collateralIn);
_collateral.approve(address(_marketFactory), MAX_UINT);
uint256 _sets = _marketFactory.calcShares(_collateralIn);
_marketFactory.mintShares(_marketId, _sets, address(this));
// Find poolAmountOut
_poolAmountOut = MAX_UINT;
{
uint256 _totalSupply = _pool.totalSupply();
uint256[] memory _maxAmountsIn = new uint256[](_market.shareTokens.length);
for (uint256 i = 0; i < _market.shareTokens.length; i++) {
_maxAmountsIn[i] = _sets;
OwnedERC20 _token = _market.shareTokens[i];
uint256 _bPoolTokenBalance = _pool.getBalance(address(_token));
// This is the result the following when solving for poolAmountOut:
// uint256 ratio = bdiv(poolAmountOut, poolTotal);
// uint256 tokenAmountIn = bmul(ratio, bal);
uint256 _tokenPoolAmountOut =
(((((_sets * BONE) - (BONE / 2)) * _totalSupply) / _bPoolTokenBalance) - (_totalSupply / 2)) / BONE;
if (_tokenPoolAmountOut < _poolAmountOut) {
_poolAmountOut = _tokenPoolAmountOut;
}
}
_pool.joinPool(_poolAmountOut, _maxAmountsIn);
}
require(_poolAmountOut >= _minLPTokensOut, "Would not have received enough LP tokens");
_pool.transfer(_lpTokenRecipient, _poolAmountOut);
// Transfer the remaining shares back to _lpTokenRecipient.
_balances = new uint256[](_market.shareTokens.length);
for (uint256 i = 0; i < _market.shareTokens.length; i++) {
OwnedERC20 _token = _market.shareTokens[i];
_balances[i] = _token.balanceOf(address(this));
if (_balances[i] > 0) {
_token.transfer(_lpTokenRecipient, _balances[i]);
}
}
emit LiquidityChanged(
address(_marketFactory),
_marketId,
msg.sender,
_lpTokenRecipient,
-int256(_collateralIn),
int256(_poolAmountOut),
_balances
);
}
function removeLiquidity(
AbstractMarketFactoryV3 _marketFactory,
uint256 _marketId,
uint256 _lpTokensIn,
uint256 _minCollateralOut,
address _collateralRecipient
) public returns (uint256 _collateralOut, uint256[] memory _balances) {
BPool _pool = pools[address(_marketFactory)][_marketId];
require(_pool != BPool(0), "Pool needs to be created");
AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId);
_pool.transferFrom(msg.sender, address(this), _lpTokensIn);
uint256[] memory exitPoolEstimate;
{
uint256[] memory minAmountsOut = new uint256[](_market.shareTokens.length);
exitPoolEstimate = _pool.calcExitPool(_lpTokensIn, minAmountsOut);
_pool.exitPool(_lpTokensIn, minAmountsOut);
}
// Find the number of sets to sell.
uint256 _setsToSell = MAX_UINT;
for (uint256 i = 0; i < _market.shareTokens.length; i++) {
uint256 _acquiredTokenBalance = exitPoolEstimate[i];
if (_acquiredTokenBalance < _setsToSell) _setsToSell = _acquiredTokenBalance;
}
// Must be a multiple of share factor.
_setsToSell = (_setsToSell / _marketFactory.shareFactor()) * _marketFactory.shareFactor();
bool _resolved = _marketFactory.isMarketResolved(_marketId);
if (_resolved) {
_collateralOut = _marketFactory.claimWinnings(_marketId, _collateralRecipient);
} else {
_collateralOut = _marketFactory.burnShares(_marketId, _setsToSell, _collateralRecipient);
}
require(_collateralOut > _minCollateralOut, "Amount of collateral returned too low.");
// Transfer the remaining shares back to _collateralRecipient.
_balances = new uint256[](_market.shareTokens.length);
for (uint256 i = 0; i < _market.shareTokens.length; i++) {
OwnedERC20 _token = _market.shareTokens[i];
if (_resolved && _token == _market.winner) continue; // all winning shares claimed when market is resolved
_balances[i] = exitPoolEstimate[i] - _setsToSell;
if (_balances[i] > 0) {
_token.transfer(_collateralRecipient, _balances[i]);
}
}
emit LiquidityChanged(
address(_marketFactory),
_marketId,
msg.sender,
_collateralRecipient,
int256(_collateralOut),
-int256(_lpTokensIn),
_balances
);
}
function buy(
AbstractMarketFactoryV3 _marketFactory,
uint256 _marketId,
uint256 _outcome,
uint256 _collateralIn,
uint256 _minTokensOut
) external returns (uint256) {
BPool _pool = pools[address(_marketFactory)][_marketId];
require(_pool != BPool(0), "Pool needs to be created");
AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId);
IERC20Full _collateral = _marketFactory.collateral();
_collateral.transferFrom(msg.sender, address(this), _collateralIn);
uint256 _sets = _marketFactory.calcShares(_collateralIn);
_marketFactory.mintShares(_marketId, _sets, address(this));
uint256 _totalDesiredOutcome = _sets;
{
OwnedERC20 _desiredToken = _market.shareTokens[_outcome];
for (uint256 i = 0; i < _market.shareTokens.length; i++) {
if (i == _outcome) continue;
OwnedERC20 _token = _market.shareTokens[i];
(uint256 _acquiredToken, ) =
_pool.swapExactAmountIn(address(_token), _sets, address(_desiredToken), 0, MAX_UINT);
_totalDesiredOutcome += _acquiredToken;
}
require(_totalDesiredOutcome >= _minTokensOut, "Slippage exceeded");
_desiredToken.transfer(msg.sender, _totalDesiredOutcome);
}
emit SharesSwapped(
address(_marketFactory),
_marketId,
msg.sender,
_outcome,
-int256(_collateralIn),
int256(_totalDesiredOutcome),
bdiv(_sets, _totalDesiredOutcome)
);
return _totalDesiredOutcome;
}
function sellForCollateral(
AbstractMarketFactoryV3 _marketFactory,
uint256 _marketId,
uint256 _outcome,
uint256[] memory _shareTokensIn,
uint256 _minSetsOut
) external returns (uint256) {
BPool _pool = pools[address(_marketFactory)][_marketId];
require(_pool != BPool(0), "Pool needs to be created");
AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId);
uint256 _setsOut = MAX_UINT;
uint256 _totalUndesiredTokensIn = 0;
for (uint256 i = 0; i < _market.shareTokens.length; i++) {
_totalUndesiredTokensIn += _shareTokensIn[i];
}
{
_market.shareTokens[_outcome].transferFrom(msg.sender, address(this), _totalUndesiredTokensIn);
_market.shareTokens[_outcome].approve(address(_pool), MAX_UINT);
for (uint256 i = 0; i < _market.shareTokens.length; i++) {
if (i == _outcome) continue;
OwnedERC20 _token = _market.shareTokens[i];
(uint256 tokenAmountOut, ) =
_pool.swapExactAmountIn(
address(_market.shareTokens[_outcome]),
_shareTokensIn[i],
address(_token),
0,
MAX_UINT
);
//Ensure tokenAmountOut is a multiple of shareFactor.
tokenAmountOut = (tokenAmountOut / _marketFactory.shareFactor()) * _marketFactory.shareFactor();
if (tokenAmountOut < _setsOut) _setsOut = tokenAmountOut;
}
require(_setsOut >= _minSetsOut, "Minimum sets not available.");
_marketFactory.burnShares(_marketId, _setsOut, msg.sender);
}
// Transfer undesired token balance back.
for (uint256 i = 0; i < _market.shareTokens.length; i++) {
OwnedERC20 _token = _market.shareTokens[i];
uint256 _balance = _token.balanceOf(address(this));
if (_balance > 0) {
_token.transfer(msg.sender, _balance);
}
}
uint256 _collateralOut = _marketFactory.calcCost(_setsOut);
emit SharesSwapped(
address(_marketFactory),
_marketId,
msg.sender,
_outcome,
int256(_collateralOut),
-int256(_totalUndesiredTokensIn),
bdiv(_setsOut, _totalUndesiredTokensIn)
);
return _collateralOut;
}
// Returns an array of token values for the outcomes of the market, relative to the first outcome.
// So the first outcome is 10**18 and all others are higher or lower.
// Prices can be derived due to the fact that the total of all outcome shares equals one collateral, possibly with a scaling factor,
function tokenRatios(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId)
external
view
returns (uint256[] memory)
{
BPool _pool = pools[address(_marketFactory)][_marketId];
// Pool does not exist. Do not want to revert because multicall.
if (_pool == BPool(0)) {
return new uint256[](0);
}
AbstractMarketFactoryV3.Market memory _market = _marketFactory.getMarket(_marketId);
address _basisToken = address(_market.shareTokens[0]);
uint256[] memory _ratios = new uint256[](_market.shareTokens.length);
_ratios[0] = 10**18;
for (uint256 i = 1; i < _market.shareTokens.length; i++) {
uint256 _price = _pool.getSpotPrice(_basisToken, address(_market.shareTokens[i]));
_ratios[i] = _price;
}
return _ratios;
}
function getPoolBalances(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId)
external
view
returns (uint256[] memory)
{
BPool _pool = pools[address(_marketFactory)][_marketId];
// Pool does not exist. Do not want to revert because multicall.
if (_pool == BPool(0)) {
return new uint256[](0);
}
address[] memory _tokens = _pool.getCurrentTokens();
uint256[] memory _balances = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_balances[i] = _pool.getBalance(_tokens[i]);
}
return _balances;
}
function getPoolWeights(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId)
external
view
returns (uint256[] memory)
{
BPool _pool = pools[address(_marketFactory)][_marketId];
// Pool does not exist. Do not want to revert because multicall.
if (_pool == BPool(0)) {
return new uint256[](0);
}
address[] memory _tokens = _pool.getCurrentTokens();
uint256[] memory _weights = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_weights[i] = _pool.getDenormalizedWeight(_tokens[i]);
}
return _weights;
}
function getSwapFee(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId) external view returns (uint256) {
BPool _pool = pools[address(_marketFactory)][_marketId];
return _pool.getSwapFee();
}
function getPoolTokenBalance(
AbstractMarketFactoryV3 _marketFactory,
uint256 _marketId,
address _user
) external view returns (uint256) {
BPool _pool = pools[address(_marketFactory)][_marketId];
return _pool.balanceOf(_user);
}
function getPool(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId) external view returns (BPool) {
return pools[address(_marketFactory)][_marketId];
}
}
| Pool does not exist. Do not want to revert because multicall. | function getPoolBalances(AbstractMarketFactoryV3 _marketFactory, uint256 _marketId)
external
view
returns (uint256[] memory)
{
BPool _pool = pools[address(_marketFactory)][_marketId];
if (_pool == BPool(0)) {
return new uint256[](0);
}
address[] memory _tokens = _pool.getCurrentTokens();
uint256[] memory _balances = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_balances[i] = _pool.getBalance(_tokens[i]);
}
return _balances;
}
| 12,875,586 |
/**
*Submitted for verification at Etherscan.io on 2022-02-19
*/
/*
__ __ _
| \/ | \| |
| |\/| | |) | |__
|_| |__/|___|
Million Dollar Living
Website: https://mdldao.eth.link
Twitter: https://twitter.com/MDLDAO
Discord: https://discord.gg/7hvY8fz2VA
*/
//SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
pragma solidity >=0.6.0 <0.8.0;
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https:
* 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);
}
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https:
*/
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);
}
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https:
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
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 {
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
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) {
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;
}
}
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) {
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:
* 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:
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https:
*/
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:
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https:
* 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 {
*
* using EnumerableSet for EnumerableSet.AddressSet;
*
*
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
struct Set {
bytes32[] _values;
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);
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) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
set._indexes[lastvalue] = toDeleteIndex + 1;
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @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];
}
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);
}
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))));
}
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https:
* 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 {
*
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
*
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
MapEntry[] _entries;
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) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
map._entries.push(MapEntry({ _key: key, _value: value }));
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
MapEntry storage lastEntry = map._entries[lastIndex];
map._entries[toDeleteIndex] = lastEntry;
map._indexes[lastEntry._key] = toDeleteIndex + 1;
map._entries.pop();
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0);
return (true, map._entries[keyIndex - 1]._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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key");
return map._entries[keyIndex - 1]._value;
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage);
return map._entries[keyIndex - 1]._value;
}
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https:
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping (address => EnumerableSet.UintSet) private _holderTokens;
EnumerableMap.UintToAddressMap private _tokenOwners;
mapping (uint256 => address) private _tokenApprovals;
mapping (address => mapping (address => bool)) private _operatorApprovals;
string private _name;
string private _symbol;
mapping (uint256 => string) private _tokenURIs;
string private _baseURI;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 {
uint256 _value;
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity >=0.6.0 <0.7.0;
contract NFTSticker is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter public _tokenIds;
mapping (address => bool) public hasMinted;
mapping (uint256 => string) public stickerText;
uint256 public supplyLimit = 999;
bool public mintEnabled = false;
string public _contractURI;
modifier ownsToken(uint256 _tokenId){
require(ownerOf(_tokenId) == msg.sender, "You don't own this token!");
_;
}
constructor(string memory _contractMeta) public ERC721("ETHDenver2022", "ETHD"){
_contractURI = _contractMeta;
}
function mintSticker(string memory _text) public{
require(mintEnabled == true, "Mint is not yet enabled");
require(_tokenIds.current() < supplyLimit, "All out! :(");
require(hasMinted[msg.sender] != true, "Don't get greedy!");
hasMinted[msg.sender] = true;
uint256 id = _tokenIds.current();
string memory string_id = id.toString();
_mint(msg.sender, id);
_setTokenURI(id, string_id);
stickerText[id] = _text;
_tokenIds.increment();
}
function changeSticker(uint256 _tokenId, string memory _text) public ownsToken(_tokenId){
stickerText[_tokenId] = _text;
}
function mintSwitch() public onlyOwner{
mintEnabled = !mintEnabled;
}
function changeURI(string memory url) public onlyOwner {
_setBaseURI(url);
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
function changeContractURI(string memory url) public onlyOwner {
_contractURI = url;
}
} | Same as {_get}, with a custom error message when `key` is not in the map. CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {_tryGet}./ | function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage);
return map._entries[keyIndex - 1]._value;
}
| 10,962,080 |
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./tools/ERC1820Client.sol";
import "./interface/ERC1820Implementer.sol";
import "./roles/MinterRole.sol";
import "./IERC1400.sol";
// Extensions
import "./extensions/tokenExtensions/IERC1400TokensValidator.sol";
import "./extensions/tokenExtensions/IERC1400TokensChecker.sol";
import "./extensions/userExtensions/IERC1400TokensSender.sol";
import "./extensions/userExtensions/IERC1400TokensRecipient.sol";
/**
* @title ERC1400
* @dev ERC1400 logic
*/
contract ERC1400 is IERC20, IERC1400, Ownable, ERC1820Client, ERC1820Implementer, MinterRole {
using SafeMath for uint256;
// Token
string constant internal ERC1400_INTERFACE_NAME = "ERC1400Token";
string constant internal ERC20_INTERFACE_NAME = "ERC20Token";
// Token extensions
string constant internal ERC1400_TOKENS_CHECKER = "ERC1400TokensChecker";
string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator";
// User extensions
string constant internal ERC1400_TOKENS_SENDER = "ERC1400TokensSender";
string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient";
/************************************* Token description ****************************************/
string internal _name;
string internal _symbol;
uint256 internal _granularity;
uint256 internal _totalSupply;
bool internal _migrated;
/************************************************************************************************/
/**************************************** Token behaviours **************************************/
// Indicate whether the token can still be controlled by operators or not anymore.
bool internal _isControllable;
// Indicate whether the token can still be issued by the issuer or not anymore.
bool internal _isIssuable;
/************************************************************************************************/
/********************************** ERC20 Token mappings ****************************************/
// Mapping from tokenHolder to balance.
mapping(address => uint256) internal _balances;
// Mapping from (tokenHolder, spender) to allowed value.
mapping (address => mapping (address => uint256)) internal _allowed;
/************************************************************************************************/
/**************************************** Documents *********************************************/
struct Doc {
string docURI;
bytes32 docHash;
}
// Mapping for token URIs.
mapping(bytes32 => Doc) internal _documents;
/************************************************************************************************/
/*********************************** Partitions mappings ***************************************/
// List of partitions.
bytes32[] internal _totalPartitions;
// Mapping from partition to their index.
mapping (bytes32 => uint256) internal _indexOfTotalPartitions;
// Mapping from partition to global balance of corresponding partition.
mapping (bytes32 => uint256) internal _totalSupplyByPartition;
// Mapping from tokenHolder to their partitions.
mapping (address => bytes32[]) internal _partitionsOf;
// Mapping from (tokenHolder, partition) to their index.
mapping (address => mapping (bytes32 => uint256)) internal _indexOfPartitionsOf;
// Mapping from (tokenHolder, partition) to balance of corresponding partition.
mapping (address => mapping (bytes32 => uint256)) internal _balanceOfByPartition;
// List of token default partitions (for ERC20 compatibility).
bytes32[] internal _defaultPartitions;
/************************************************************************************************/
/********************************* Global operators mappings ************************************/
// Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC]
mapping(address => mapping(address => bool)) internal _authorizedOperator;
// Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC]
address[] internal _controllers;
// Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC]
mapping(address => bool) internal _isController;
/************************************************************************************************/
/******************************** Partition operators mappings **********************************/
// Mapping from (partition, tokenHolder, spender) to allowed value. [TOKEN-HOLDER-SPECIFIC]
mapping(bytes32 => mapping (address => mapping (address => uint256))) internal _allowedByPartition;
// Mapping from (tokenHolder, partition, operator) to 'approved for partition' status. [TOKEN-HOLDER-SPECIFIC]
mapping (address => mapping (bytes32 => mapping (address => bool))) internal _authorizedOperatorByPartition;
// Mapping from partition to controllers for the partition. [NOT TOKEN-HOLDER-SPECIFIC]
mapping (bytes32 => address[]) internal _controllersByPartition;
// Mapping from (partition, operator) to PartitionController status. [NOT TOKEN-HOLDER-SPECIFIC]
mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition;
/************************************************************************************************/
/***************************************** Modifiers ********************************************/
/**
* @dev Modifier to verify if token is issuable.
*/
modifier isIssuableToken() {
require(_isIssuable, "55"); // 0x55 funds locked (lockup period)
_;
}
/**
* @dev Modifier to make a function callable only when the contract is not migrated.
*/
modifier isNotMigratedToken() {
require(!_migrated, "54"); // 0x54 transfers halted (contract paused)
_;
}
/**
* @dev Modifier to verifiy if sender is a minter.
*/
modifier onlyMinter() override {
require(isMinter(msg.sender) || owner() == _msgSender());
_;
}
/************************************************************************************************/
/**************************** Events (additional - not mandatory) *******************************/
event ApprovalByPartition(bytes32 indexed partition, address indexed owner, address indexed spender, uint256 value);
/************************************************************************************************/
/**
* @dev Initialize ERC1400 + register the contract implementation in ERC1820Registry.
* @param name Name of the token.
* @param symbol Symbol of the token.
* @param granularity Granularity of the token.
* @param controllers Array of initial controllers.
* @param defaultPartitions Partitions chosen by default, when partition is
* not specified, like the case ERC20 tranfers.
*/
constructor(
string memory name,
string memory symbol,
uint256 granularity,
address[] memory controllers,
bytes32[] memory defaultPartitions
)
public
{
_name = name;
_symbol = symbol;
_totalSupply = 0;
require(granularity >= 1); // Constructor Blocked - Token granularity can not be lower than 1
_granularity = granularity;
_setControllers(controllers);
_defaultPartitions = defaultPartitions;
_isControllable = true;
_isIssuable = true;
// Register contract in ERC1820 registry
ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, address(this));
ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this));
// Indicate token verifies ERC1400 and ERC20 interfaces
ERC1820Implementer._setInterface(ERC1400_INTERFACE_NAME); // For migration
ERC1820Implementer._setInterface(ERC20_INTERFACE_NAME); // For migration
}
/************************************************************************************************/
/****************************** EXTERNAL FUNCTIONS (ERC20 INTERFACE) ****************************/
/************************************************************************************************/
/**
* @dev Get the total number of issued tokens.
* @return Total supply of tokens currently in circulation.
*/
function totalSupply() external override view returns (uint256) {
return _totalSupply;
}
/**
* @dev Get the balance of the account with address 'tokenHolder'.
* @param tokenHolder Address for which the balance is returned.
* @return Amount of token held by 'tokenHolder' in the token contract.
*/
function balanceOf(address tokenHolder) external override view returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev Transfer token for a specified address.
* @param to The address to transfer to.
* @param value The value to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address to, uint256 value) external override returns (bool) {
_transferByDefaultPartitions(msg.sender, msg.sender, to, value, "");
return true;
}
/**
* @dev Check the value of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the value of tokens still available for the spender.
*/
function allowance(address owner, address spender) external override view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean that indicates if the operation was successful.
*/
function approve(address spender, uint256 value) external override returns (bool) {
require(spender != address(0), "56"); // 0x56 invalid sender
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address which you want to transfer tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transferFrom(address from, address to, uint256 value) external override returns (bool) {
require( _isOperator(msg.sender, from)
|| (value <= _allowed[from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowed[from][msg.sender] >= value) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
} else {
_allowed[from][msg.sender] = 0;
}
_transferByDefaultPartitions(msg.sender, from, to, value, "");
return true;
}
/************************************************************************************************/
/****************************** EXTERNAL FUNCTIONS (ERC1400 INTERFACE) **************************/
/************************************************************************************************/
/************************************* Document Management **************************************/
/**
* @dev Access a document associated with the token.
* @param name Short name (represented as a bytes32) associated to the document.
* @return Requested document + document hash.
*/
function getDocument(bytes32 name) external override view returns (string memory, bytes32) {
require(bytes(_documents[name].docURI).length != 0); // Action Blocked - Empty document
return (
_documents[name].docURI,
_documents[name].docHash
);
}
/**
* @dev Associate a document with the token.
* @param name Short name (represented as a bytes32) associated to the document.
* @param uri Document content.
* @param documentHash Hash of the document [optional parameter].
*/
function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external override {
require(_isController[msg.sender]);
_documents[name] = Doc({
docURI: uri,
docHash: documentHash
});
emit Document(name, uri, documentHash);
}
/************************************************************************************************/
/************************************** Token Information ***************************************/
/**
* @dev Get balance of a tokenholder for a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which the balance is returned.
* @return Amount of token of partition 'partition' held by 'tokenHolder' in the token contract.
*/
function balanceOfByPartition(bytes32 partition, address tokenHolder) external override view returns (uint256) {
return _balanceOfByPartition[tokenHolder][partition];
}
/**
* @dev Get partitions index of a tokenholder.
* @param tokenHolder Address for which the partitions index are returned.
* @return Array of partitions index of 'tokenHolder'.
*/
function partitionsOf(address tokenHolder) external override view returns (bytes32[] memory) {
return _partitionsOf[tokenHolder];
}
/************************************************************************************************/
/****************************************** Transfers *******************************************/
/**
* @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, by the token holder.
*/
function transferWithData(address to, uint256 value, bytes calldata data) external override {
_transferByDefaultPartitions(msg.sender, msg.sender, to, value, data);
}
/**
* @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'.
* @param from Token holder (or 'address(0)' to set from to 'msg.sender').
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, and intended for the token holder ('from').
*/
function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external override virtual {
require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent)
_transferByDefaultPartitions(msg.sender, from, to, value, data);
}
/************************************************************************************************/
/********************************** Partition Token Transfers ***********************************/
/**
* @dev Transfer tokens from a specific partition.
* @param partition Name of the partition.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, by the token holder.
* @return Destination partition.
*/
function transferByPartition(
bytes32 partition,
address to,
uint256 value,
bytes calldata data
)
external
override
returns (bytes32)
{
return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, "");
}
/**
* @dev Transfer tokens from a specific partition through an operator.
* @param partition Name of the partition.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator.
* @return Destination partition.
*/
function operatorTransferByPartition(
bytes32 partition,
address from,
address to,
uint256 value,
bytes calldata data,
bytes calldata operatorData
)
external
override
returns (bytes32)
{
require(_isOperatorForPartition(partition, msg.sender, from)
|| (value <= _allowedByPartition[partition][from][msg.sender]), "53"); // 0x53 insufficient allowance
if(_allowedByPartition[partition][from][msg.sender] >= value) {
_allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender].sub(value);
} else {
_allowedByPartition[partition][from][msg.sender] = 0;
}
return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData);
}
/************************************************************************************************/
/************************************* Controller Operation *************************************/
/**
* @dev Know if the token can be controlled by operators.
* If a token returns 'false' for 'isControllable()'' then it MUST always return 'false' in the future.
* @return bool 'true' if the token can still be controlled by operators, 'false' if it can't anymore.
*/
function isControllable() external override view returns (bool) {
return _isControllable;
}
/************************************************************************************************/
/************************************* Operator Management **************************************/
/**
* @dev Set a third party operator address as an operator of 'msg.sender' to transfer
* and redeem tokens on its behalf.
* @param operator Address to set as an operator for 'msg.sender'.
*/
function authorizeOperator(address operator) external override {
require(operator != msg.sender);
_authorizedOperator[operator][msg.sender] = true;
emit AuthorizedOperator(operator, msg.sender);
}
/**
* @dev Remove the right of the operator address to be an operator for 'msg.sender'
* and to transfer and redeem tokens on its behalf.
* @param operator Address to rescind as an operator for 'msg.sender'.
*/
function revokeOperator(address operator) external override {
require(operator != msg.sender);
_authorizedOperator[operator][msg.sender] = false;
emit RevokedOperator(operator, msg.sender);
}
/**
* @dev Set 'operator' as an operator for 'msg.sender' for a given partition.
* @param partition Name of the partition.
* @param operator Address to set as an operator for 'msg.sender'.
*/
function authorizeOperatorByPartition(bytes32 partition, address operator) external override {
_authorizedOperatorByPartition[msg.sender][partition][operator] = true;
emit AuthorizedOperatorByPartition(partition, operator, msg.sender);
}
/**
* @dev Remove the right of the operator address to be an operator on a given
* partition for 'msg.sender' and to transfer and redeem tokens on its behalf.
* @param partition Name of the partition.
* @param operator Address to rescind as an operator on given partition for 'msg.sender'.
*/
function revokeOperatorByPartition(bytes32 partition, address operator) external override {
_authorizedOperatorByPartition[msg.sender][partition][operator] = false;
emit RevokedOperatorByPartition(partition, operator, msg.sender);
}
/************************************************************************************************/
/************************************* Operator Information *************************************/
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder address.
* @param operator Address which may be an operator of tokenHolder.
* @param tokenHolder Address of a token holder which may have the operator address as an operator.
* @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise.
*/
function isOperator(address operator, address tokenHolder) external override view returns (bool) {
return _isOperator(operator, tokenHolder);
}
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder
* address for the given partition.
* @param partition Name of the partition.
* @param operator Address which may be an operator of tokenHolder for the given partition.
* @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition.
* @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise.
*/
function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external override view returns (bool) {
return _isOperatorForPartition(partition, operator, tokenHolder);
}
/************************************************************************************************/
/**************************************** Token Issuance ****************************************/
/**
* @dev Know if new tokens can be issued in the future.
* @return bool 'true' if tokens can still be issued by the issuer, 'false' if they can't anymore.
*/
function isIssuable() external override view returns (bool) {
return _isIssuable;
}
/**
* @dev Issue tokens from default partition.
* @param tokenHolder Address for which we want to issue tokens.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, by the issuer.
*/
function issue(address tokenHolder, uint256 value, bytes calldata data)
external
override
onlyMinter
isIssuableToken
{
require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period)
_issueByPartition(_defaultPartitions[0], msg.sender, tokenHolder, value, data);
}
/**
* @dev Issue tokens from a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which we want to issue tokens.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, by the issuer.
*/
function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data)
external
override
onlyMinter
isIssuableToken
{
_issueByPartition(partition, msg.sender, tokenHolder, value, data);
}
/************************************************************************************************/
/*************************************** Token Redemption ***************************************/
/**
* @dev Redeem the amount of tokens from the address 'msg.sender'.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption, by the token holder.
*/
function redeem(uint256 value, bytes calldata data)
external
override
{
_redeemByDefaultPartitions(msg.sender, msg.sender, value, data);
}
/**
* @dev Redeem the amount of tokens on behalf of the address from.
* @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender).
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function redeemFrom(address from, uint256 value, bytes calldata data)
external
override
virtual
{
require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent)
_redeemByDefaultPartitions(msg.sender, from, value, data);
}
/**
* @dev Redeem tokens of a specific partition.
* @param partition Name of the partition.
* @param value Number of tokens redeemed.
* @param data Information attached to the redemption, by the redeemer.
*/
function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data)
external
override
{
_redeemByPartition(partition, msg.sender, msg.sender, value, data, "");
}
/**
* @dev Redeem tokens of a specific partition.
* @param partition Name of the partition.
* @param tokenHolder Address for which we want to redeem tokens.
* @param value Number of tokens redeemed
* @param operatorData Information attached to the redemption, by the operator.
*/
function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData)
external
override
{
require(_isOperatorForPartition(partition, msg.sender, tokenHolder), "58"); // 0x58 invalid operator (transfer agent)
_redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData);
}
/************************************************************************************************/
/************************************************************************************************/
/************************ EXTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/
/************************************************************************************************/
/************************************ Token description *****************************************/
/**
* @dev Get the name of the token, e.g., "MyToken".
* @return Name of the token.
*/
function name() external view returns(string memory) {
return _name;
}
/**
* @dev Get the symbol of the token, e.g., "MYT".
* @return Symbol of the token.
*/
function symbol() external view returns(string memory) {
return _symbol;
}
/**
* @dev Get the number of decimals of the token.
* @return The number of decimals of the token. For retrocompatibility, decimals are forced to 18 in ERC1400.
*/
function decimals() external pure returns(uint8) {
return uint8(18);
}
/**
* @dev Get the smallest part of the token that’s not divisible.
* @return The smallest non-divisible part of the token.
*/
function granularity() external view returns(uint256) {
return _granularity;
}
/**
* @dev Get list of existing partitions.
* @return Array of all exisiting partitions.
*/
function totalPartitions() external view returns (bytes32[] memory) {
return _totalPartitions;
}
/**
* @dev Get the total number of issued tokens for a given partition.
* @param partition Name of the partition.
* @return Total supply of tokens currently in circulation, for a given partition.
*/
function totalSupplyByPartition(bytes32 partition) external view returns (uint256) {
return _totalSupplyByPartition[partition];
}
/************************************************************************************************/
/**************************************** Token behaviours **************************************/
/**
* @dev Definitely renounce the possibility to control tokens on behalf of tokenHolders.
* Once set to false, '_isControllable' can never be set to 'true' again.
*/
function renounceControl() external onlyOwner {
_isControllable = false;
}
/**
* @dev Definitely renounce the possibility to issue new tokens.
* Once set to false, '_isIssuable' can never be set to 'true' again.
*/
function renounceIssuance() external onlyOwner {
_isIssuable = false;
}
/************************************************************************************************/
/************************************ Token controllers *****************************************/
/**
* @dev Get the list of controllers as defined by the token contract.
* @return List of addresses of all the controllers.
*/
function controllers() external view returns (address[] memory) {
return _controllers;
}
/**
* @dev Get controllers for a given partition.
* @param partition Name of the partition.
* @return Array of controllers for partition.
*/
function controllersByPartition(bytes32 partition) external view returns (address[] memory) {
return _controllersByPartition[partition];
}
/**
* @dev Set list of token controllers.
* @param operators Controller addresses.
*/
function setControllers(address[] calldata operators) external onlyOwner {
_setControllers(operators);
}
/**
* @dev Set list of token partition controllers.
* @param partition Name of the partition.
* @param operators Controller addresses.
*/
function setPartitionControllers(bytes32 partition, address[] calldata operators) external onlyOwner {
_setPartitionControllers(partition, operators);
}
/************************************************************************************************/
/********************************* Token default partitions *************************************/
/**
* @dev Get default partitions to transfer from.
* Function used for ERC20 retrocompatibility.
* For example, a security token may return the bytes32("unrestricted").
* @return Array of default partitions.
*/
function getDefaultPartitions() external view returns (bytes32[] memory) {
return _defaultPartitions;
}
/**
* @dev Set default partitions to transfer from.
* Function used for ERC20 retrocompatibility.
* @param partitions partitions to use by default when not specified.
*/
function setDefaultPartitions(bytes32[] calldata partitions) external onlyOwner {
_defaultPartitions = partitions;
}
/************************************************************************************************/
/******************************** Partition Token Allowances ************************************/
/**
* @dev Check the value of tokens that an owner allowed to a spender.
* @param partition Name of the partition.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the value of tokens still available for the spender.
*/
function allowanceByPartition(bytes32 partition, address owner, address spender) external view returns (uint256) {
return _allowedByPartition[partition][owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'.
* @param partition Name of the partition.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean that indicates if the operation was successful.
*/
function approveByPartition(bytes32 partition, address spender, uint256 value) external returns (bool) {
require(spender != address(0), "56"); // 0x56 invalid sender
_allowedByPartition[partition][msg.sender][spender] = value;
emit ApprovalByPartition(partition, msg.sender, spender, value);
return true;
}
/************************************************************************************************/
/************************************** Token extension *****************************************/
/**
* @dev Set token extension contract address.
* The extension contract can for example verify "ERC1400TokensValidator" or "ERC1400TokensChecker" interfaces.
* If the extension is an "ERC1400TokensValidator", it will be called everytime a transfer is executed.
* @param extension Address of the extension contract.
* @param interfaceLabel Interface label of extension contract.
* @param removeOldExtensionRoles If set to 'true', the roles of the old extension(minter, controller) will be removed extension.
* @param addMinterRoleForExtension If set to 'true', the extension contract will be added as minter.
* @param addControllerRoleForExtension If set to 'true', the extension contract will be added as controller.
*/
function setTokenExtension(address extension, string calldata interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) external onlyOwner {
_setTokenExtension(extension, interfaceLabel, removeOldExtensionRoles, addMinterRoleForExtension, addControllerRoleForExtension);
}
/************************************************************************************************/
/************************************* Token migration ******************************************/
/**
* @dev Migrate contract.
*
* ===> CAUTION: DEFINITIVE ACTION
*
* This function shall be called once a new version of the smart contract has been created.
* Once this function is called:
* - The address of the new smart contract is set in ERC1820 registry
* - If the choice is definitive, the current smart contract is turned off and can never be used again
*
* @param newContractAddress Address of the new version of the smart contract.
* @param definitive If set to 'true' the contract is turned off definitely.
*/
function migrate(address newContractAddress, bool definitive) external onlyOwner {
_migrate(newContractAddress, definitive);
}
/************************************************************************************************/
/************************************************************************************************/
/************************************* INTERNAL FUNCTIONS ***************************************/
/************************************************************************************************/
/**************************************** Token Transfers ***************************************/
/**
* @dev Perform the transfer of tokens.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
*/
function _transferWithData(
address from,
address to,
uint256 value
)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(to != address(0), "57"); // 0x57 invalid receiver
require(_balances[from] >= value, "52"); // 0x52 insufficient balance
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value); // ERC20 retrocompatibility
}
/**
* @dev Transfer tokens from a specific partition.
* @param fromPartition Partition of the tokens to transfer.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator (if any).
* @return Destination partition.
*/
function _transferByPartition(
bytes32 fromPartition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
returns (bytes32)
{
require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance
bytes32 toPartition = fromPartition;
if(operatorData.length != 0 && data.length >= 64) {
toPartition = _getDestinationPartition(fromPartition, data);
}
_callSenderExtension(fromPartition, operator, from, to, value, data, operatorData);
_callTokenExtension(fromPartition, operator, from, to, value, data, operatorData);
_removeTokenFromPartition(from, fromPartition, value);
_transferWithData(from, to, value);
_addTokenToPartition(to, toPartition, value);
_callRecipientExtension(toPartition, operator, from, to, value, data, operatorData);
emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData);
if(toPartition != fromPartition) {
emit ChangedPartition(fromPartition, toPartition, value);
}
return toPartition;
}
/**
* @dev Transfer tokens from default partitions.
* Function used for ERC20 retrocompatibility.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer, and intended for the token holder ('from') [CAN CONTAIN THE DESTINATION PARTITION].
*/
function _transferByDefaultPartitions(
address operator,
address from,
address to,
uint256 value,
bytes memory data
)
internal
{
require(_defaultPartitions.length != 0, "55"); // // 0x55 funds locked (lockup period)
uint256 _remainingValue = value;
uint256 _localBalance;
for (uint i = 0; i < _defaultPartitions.length; i++) {
_localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];
if(_remainingValue <= _localBalance) {
_transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, "");
_remainingValue = 0;
break;
} else if (_localBalance != 0) {
_transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, "");
_remainingValue = _remainingValue - _localBalance;
}
}
require(_remainingValue == 0, "52"); // 0x52 insufficient balance
}
/**
* @dev Retrieve the destination partition from the 'data' field.
* By convention, a partition change is requested ONLY when 'data' starts
* with the flag: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
* When the flag is detected, the destination tranche is extracted from the
* 32 bytes following the flag.
* @param fromPartition Partition of the tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @return toPartition Destination partition.
*/
function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) {
bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
bytes32 flag;
assembly {
flag := mload(add(data, 32))
}
if(flag == changePartitionFlag) {
assembly {
toPartition := mload(add(data, 64))
}
} else {
toPartition = fromPartition;
}
}
/**
* @dev Remove a token from a specific partition.
* @param from Token holder.
* @param partition Name of the partition.
* @param value Number of tokens to transfer.
*/
function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal {
_balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value);
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value);
// If the total supply is zero, finds and deletes the partition.
if(_totalSupplyByPartition[partition] == 0) {
uint256 index1 = _indexOfTotalPartitions[partition];
require(index1 > 0, "50"); // 0x50 transfer failure
// move the last item into the index being vacated
bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1];
_totalPartitions[index1 - 1] = lastValue; // adjust for 1-based indexing
_indexOfTotalPartitions[lastValue] = index1;
//_totalPartitions.length -= 1;
_totalPartitions.pop();
_indexOfTotalPartitions[partition] = 0;
}
// If the balance of the TokenHolder's partition is zero, finds and deletes the partition.
if(_balanceOfByPartition[from][partition] == 0) {
uint256 index2 = _indexOfPartitionsOf[from][partition];
require(index2 > 0, "50"); // 0x50 transfer failure
// move the last item into the index being vacated
bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1];
_partitionsOf[from][index2 - 1] = lastValue; // adjust for 1-based indexing
_indexOfPartitionsOf[from][lastValue] = index2;
//_partitionsOf[from].length -= 1;
_partitionsOf[from].pop();
_indexOfPartitionsOf[from][partition] = 0;
}
}
/**
* @dev Add a token to a specific partition.
* @param to Token recipient.
* @param partition Name of the partition.
* @param value Number of tokens to transfer.
*/
function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal {
if(value != 0) {
if (_indexOfPartitionsOf[to][partition] == 0) {
_partitionsOf[to].push(partition);
_indexOfPartitionsOf[to][partition] = _partitionsOf[to].length;
}
_balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition].add(value);
if (_indexOfTotalPartitions[partition] == 0) {
_totalPartitions.push(partition);
_indexOfTotalPartitions[partition] = _totalPartitions.length;
}
_totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].add(value);
}
}
/**
* @dev Check if 'value' is multiple of the granularity.
* @param value The quantity that want's to be checked.
* @return 'true' if 'value' is a multiple of the granularity.
*/
function _isMultiple(uint256 value) internal view returns(bool) {
return(value.div(_granularity).mul(_granularity) == value);
}
/************************************************************************************************/
/****************************************** Hooks ***********************************************/
/**
* @dev Check for 'ERC1400TokensSender' user extension in ERC1820 registry and call it.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance decrease (through transfer or redemption).
* @param from Token holder.
* @param to Token recipient for a transfer and 0x for a redemption.
* @param value Number of tokens the token holder balance is decreased by.
* @param data Extra information.
* @param operatorData Extra information, attached by the operator (if any).
*/
function _callSenderExtension(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
address senderImplementation;
senderImplementation = interfaceAddr(from, ERC1400_TOKENS_SENDER);
if (senderImplementation != address(0)) {
IERC1400TokensSender(senderImplementation).tokensToTransfer(msg.data, partition, operator, from, to, value, data, operatorData);
}
}
/**
* @dev Check for 'ERC1400TokensValidator' token extension in ERC1820 registry and call it.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance decrease (through transfer or redemption).
* @param from Token holder.
* @param to Token recipient for a transfer and 0x for a redemption.
* @param value Number of tokens the token holder balance is decreased by.
* @param data Extra information.
* @param operatorData Extra information, attached by the operator (if any).
*/
function _callTokenExtension(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
address validatorImplementation;
validatorImplementation = interfaceAddr(address(this), ERC1400_TOKENS_VALIDATOR);
if (validatorImplementation != address(0)) {
IERC1400TokensValidator(validatorImplementation).tokensToValidate(msg.data, partition, operator, from, to, value, data, operatorData);
}
}
/**
* @dev Check for 'ERC1400TokensRecipient' user extension in ERC1820 registry and call it.
* @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).
* @param operator Address which triggered the balance increase (through transfer or issuance).
* @param from Token holder for a transfer and 0x for an issuance.
* @param to Token recipient.
* @param value Number of tokens the recipient balance is increased by.
* @param data Extra information, intended for the token holder ('from').
* @param operatorData Extra information attached by the operator (if any).
*/
function _callRecipientExtension(
bytes32 partition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
virtual
{
address recipientImplementation;
recipientImplementation = interfaceAddr(to, ERC1400_TOKENS_RECIPIENT);
if (recipientImplementation != address(0)) {
IERC1400TokensRecipient(recipientImplementation).tokensReceived(msg.data, partition, operator, from, to, value, data, operatorData);
}
}
/************************************************************************************************/
/************************************* Operator Information *************************************/
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder address.
* @param operator Address which may be an operator of 'tokenHolder'.
* @param tokenHolder Address of a token holder which may have the 'operator' address as an operator.
* @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise.
*/
function _isOperator(address operator, address tokenHolder) internal view returns (bool) {
return (operator == tokenHolder
|| _authorizedOperator[operator][tokenHolder]
|| (_isControllable && _isController[operator])
);
}
/**
* @dev Indicate whether the operator address is an operator of the tokenHolder
* address for the given partition.
* @param partition Name of the partition.
* @param operator Address which may be an operator of tokenHolder for the given partition.
* @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition.
* @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise.
*/
function _isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) internal view returns (bool) {
return (_isOperator(operator, tokenHolder)
|| _authorizedOperatorByPartition[tokenHolder][partition][operator]
|| (_isControllable && _isControllerByPartition[partition][operator])
);
}
/************************************************************************************************/
/**************************************** Token Issuance ****************************************/
/**
* @dev Perform the issuance of tokens.
* @param operator Address which triggered the issuance.
* @param to Token recipient.
* @param value Number of tokens issued.
* @param data Information attached to the issuance, and intended for the recipient (to).
*/
function _issue(address operator, address to, uint256 value, bytes memory data)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(to != address(0), "57"); // 0x57 invalid receiver
_totalSupply = _totalSupply.add(value);
_balances[to] = _balances[to].add(value);
emit Issued(operator, to, value, data);
emit Transfer(address(0), to, value); // ERC20 retrocompatibility
}
/**
* @dev Issue tokens from a specific partition.
* @param toPartition Name of the partition.
* @param operator The address performing the issuance.
* @param to Token recipient.
* @param value Number of tokens to issue.
* @param data Information attached to the issuance.
*/
function _issueByPartition(
bytes32 toPartition,
address operator,
address to,
uint256 value,
bytes memory data
)
internal
{
_callTokenExtension(toPartition, operator, address(0), to, value, data, "");
_issue(operator, to, value, data);
_addTokenToPartition(to, toPartition, value);
_callRecipientExtension(toPartition, operator, address(0), to, value, data, "");
emit IssuedByPartition(toPartition, operator, to, value, data, "");
}
/************************************************************************************************/
/*************************************** Token Redemption ***************************************/
/**
* @dev Perform the token redemption.
* @param operator The address performing the redemption.
* @param from Token holder whose tokens will be redeemed.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function _redeem(address operator, address from, uint256 value, bytes memory data)
internal
isNotMigratedToken
{
require(_isMultiple(value), "50"); // 0x50 transfer failure
require(from != address(0), "56"); // 0x56 invalid sender
require(_balances[from] >= value, "52"); // 0x52 insufficient balance
_balances[from] = _balances[from].sub(value);
_totalSupply = _totalSupply.sub(value);
emit Redeemed(operator, from, value, data);
emit Transfer(from, address(0), value); // ERC20 retrocompatibility
}
/**
* @dev Redeem tokens of a specific partition.
* @param fromPartition Name of the partition.
* @param operator The address performing the redemption.
* @param from Token holder whose tokens will be redeemed.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
* @param operatorData Information attached to the redemption, by the operator (if any).
*/
function _redeemByPartition(
bytes32 fromPartition,
address operator,
address from,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
{
require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance
_callSenderExtension(fromPartition, operator, from, address(0), value, data, operatorData);
_callTokenExtension(fromPartition, operator, from, address(0), value, data, operatorData);
_removeTokenFromPartition(from, fromPartition, value);
_redeem(operator, from, value, data);
emit RedeemedByPartition(fromPartition, operator, from, value, operatorData);
}
/**
* @dev Redeem tokens from a default partitions.
* @param operator The address performing the redeem.
* @param from Token holder.
* @param value Number of tokens to redeem.
* @param data Information attached to the redemption.
*/
function _redeemByDefaultPartitions(
address operator,
address from,
uint256 value,
bytes memory data
)
internal
{
require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period)
uint256 _remainingValue = value;
uint256 _localBalance;
for (uint i = 0; i < _defaultPartitions.length; i++) {
_localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];
if(_remainingValue <= _localBalance) {
_redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, "");
_remainingValue = 0;
break;
} else {
_redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, "");
_remainingValue = _remainingValue - _localBalance;
}
}
require(_remainingValue == 0, "52"); // 0x52 insufficient balance
}
/************************************************************************************************/
/************************************** Transfer Validity ***************************************/
/**
* @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.
* @param payload Payload of the initial transaction.
* @param partition Name of the partition.
* @param operator The address performing the transfer.
* @param from Token holder.
* @param to Token recipient.
* @param value Number of tokens to transfer.
* @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]
* @param operatorData Information attached to the transfer, by the operator (if any).
* @return ESC (Ethereum Status Code) following the EIP-1066 standard.
* @return Additional bytes32 parameter that can be used to define
* application specific reason codes with additional details (for example the
* transfer restriction rule responsible for making the transfer operation invalid).
* @return Destination partition.
*/
function _canTransfer(bytes memory payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData)
internal
view
returns (bytes1, bytes32, bytes32)
{
address checksImplementation = interfaceAddr(address(this), ERC1400_TOKENS_CHECKER);
if((checksImplementation != address(0))) {
return IERC1400TokensChecker(checksImplementation).canTransferByPartition(payload, partition, operator, from, to, value, data, operatorData);
}
else {
return(hex"00", "", partition);
}
}
/************************************************************************************************/
/************************************************************************************************/
/************************ INTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/
/************************************************************************************************/
/************************************ Token controllers *****************************************/
/**
* @dev Set list of token controllers.
* @param operators Controller addresses.
*/
function _setControllers(address[] memory operators) internal {
for (uint i = 0; i<_controllers.length; i++){
_isController[_controllers[i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isController[operators[j]] = true;
}
_controllers = operators;
}
/**
* @dev Set list of token partition controllers.
* @param partition Name of the partition.
* @param operators Controller addresses.
*/
function _setPartitionControllers(bytes32 partition, address[] memory operators) internal {
for (uint i = 0; i<_controllersByPartition[partition].length; i++){
_isControllerByPartition[partition][_controllersByPartition[partition][i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isControllerByPartition[partition][operators[j]] = true;
}
_controllersByPartition[partition] = operators;
}
/************************************************************************************************/
/************************************** Token extension *****************************************/
/**
* @dev Set token extension contract address.
* The extension contract can for example verify "ERC1400TokensValidator" or "ERC1400TokensChecker" interfaces.
* If the extension is an "ERC1400TokensValidator", it will be called everytime a transfer is executed.
* @param extension Address of the extension contract.
* @param interfaceLabel Interface label of extension contract.
* @param removeOldExtensionRoles If set to 'true', the roles of the old extension(minter, controller) will be removed extension.
* @param addMinterRoleForExtension If set to 'true', the extension contract will be added as minter.
* @param addControllerRoleForExtension If set to 'true', the extension contract will be added as controller.
*/
function _setTokenExtension(address extension, string memory interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) internal {
address oldExtension = interfaceAddr(address(this), interfaceLabel);
if (oldExtension != address(0) && removeOldExtensionRoles) {
if(isMinter(oldExtension)) {
_removeMinter(oldExtension);
}
_isController[oldExtension] = false;
}
ERC1820Client.setInterfaceImplementation(interfaceLabel, extension);
if(addMinterRoleForExtension && !isMinter(extension)) {
_addMinter(extension);
}
if (addControllerRoleForExtension) {
_isController[extension] = true;
}
}
/************************************************************************************************/
/************************************* Token migration ******************************************/
/**
* @dev Migrate contract.
*
* ===> CAUTION: DEFINITIVE ACTION
*
* This function shall be called once a new version of the smart contract has been created.
* Once this function is called:
* - The address of the new smart contract is set in ERC1820 registry
* - If the choice is definitive, the current smart contract is turned off and can never be used again
*
* @param newContractAddress Address of the new version of the smart contract.
* @param definitive If set to 'true' the contract is turned off definitely.
*/
function _migrate(address newContractAddress, bool definitive) internal {
ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, newContractAddress);
ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, newContractAddress);
if(definitive) {
_migrated = true;
}
}
/************************************************************************************************/
}
| Document Management / Access a document associated with the token. name Short name (represented as a bytes32) associated to the document. return Requested document + document hash./ | function getDocument(bytes32 name) external override view returns (string memory, bytes32) {
return (
_documents[name].docURI,
_documents[name].docHash
);
}
| 7,232,055 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
import './interface/ComptrollerInterface.sol';
//
// Lend token contract is forked and modified from venus' VToken contract
// LendREI is not ERC20 standard !!
//
contract LendREI{
function isLendToken() external pure returns(bool) {return true;} // Indicator that this is the lend token
bool internal _notEntered; // re-entrancy guarding check
// -----------------------------
// Standard variables for tokens
// -----------------------------
string public name;
string public symbol;
uint8 public decimals;
uint public totalSupply;
mapping (address => uint256) accountTokens;
mapping (address => mapping (address => uint256)) transferAllowances;
address public admin; //owner of this contract
// ----------------
// Market parameter
// ----------------
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
mapping (address => BorrowSnapshot) public accountBorrows; //Outstanding borrow balances for each account
function getAccountBorrows(address user) external view returns(uint, uint) {
return (accountBorrows[user].principal, accountBorrows[user].interestIndex);
}
ComptrollerInterface public comptroller; //get the comptroller
InterestRateModel public interestRateModel;
address[] public borrowAddress; //Stored all borrow address
mapping(address => bool) hasBorrowed;
function getBorrowAddress() external view returns(address[] memory){
return borrowAddress;
}
// -----------------
// Lending parameter
// -----------------
uint constant public borrowRateMaxMantissa = 0.0004e14; //Maximum borrow rate (0.000004% / sec) or 126.14% /year
uint constant public reserveFactorMaxMantissa = 1e18; //Maximum fraction of interest that can be set aside for reserves
uint constant public initialExchangeRateMantissa = 1e18; //Initial exchange rate, Used when minting first Lend token (totalSupply = 0)
uint public reserveFactorMantissa; //Current fraction of interest
// AccrueInterest update parameter
uint public accrualTimestamp; //Last accrued block timestamp
uint public borrowIndex; //Accumulate total earned interest rate
uint public totalBorrows; //Total amount of borrowed underlying asset
uint public totalReserves; //Total amount of underlying asset
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
// ------------------
// Initiate parameter
// ------------------
constructor (string memory name_, string memory symbol_, uint8 decimals_, address interestRateModel_, address comptroller_) {
name = name_;
symbol = symbol_;
decimals = decimals_;
interestRateModel = InterestRateModel(interestRateModel_);
comptroller = ComptrollerInterface(comptroller_);
borrowIndex = 1e18;
reserveFactorMantissa = 0.2e18; //default reserveFactor = 20%
accrualTimestamp = block.timestamp;
admin = msg.sender;
_notEntered = true;
}
// -------------
// Market Events
// -------------
error NotAllowed();
event Mint(address minter, uint mintAmount, uint mintTokens); //Emit when tokens are minted
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); //Emit when tokens are redeemed
event RedeemFee(address redeemer, uint feeAmount, uint redeemTokens); //Emit when tokens are redeemed and fee are transferred
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); //Emit when underlying is borrowed
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); //Emit when a borrow is repaid
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address LendTokenCollateral, uint seizeTokens); //Emit when a borrow is liquidated
event NewLendTokenStorage(address oldLendTokenStorage, address newLendTokenStorage);
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); //Emit when interest is accrued
event NEW_SUPERVISE_TOKEN(address oldLendToken, address newLendToken); //Emit when change the bind token
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); //Emit when changing interestRateModel
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); //Emit when changing reserve factor
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); //Emit when adding reserves
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); //Emit when reducing reserves
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); //Emit when changing comptroller
// ------------
// Admin Events
// ------------
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal{
/* Fail if transfer not allowed */
comptroller.transferAllowed(address(this), src, dst, tokens);
/* Do not allow self-transfers */
if (src == dst) {
revert ("BAD_INPUT");
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = type(uint).max;
} else {
startingAllowance = transferAllowances[src][spender];
}
uint allowanceNew;
uint srvTokensNew;
uint dstTokensNew;
allowanceNew = startingAllowance - tokens;
srvTokensNew = accountTokens[src] - tokens;
dstTokensNew = accountTokens[dst] + tokens;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srvTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != type(uint).max) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external nonReentrant {
transferTokens(msg.sender, msg.sender, dst, amount);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant{
transferTokens(msg.sender, src, dst, amount);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
*/
function approve(address spender, uint256 amount) external{
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
uint exchangeRate = exchangeRateCurrent();
uint balance = exchangeRate * accountTokens[owner] / 1e18;
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint) {
uint LendTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
borrowBalance = borrowBalanceStored(account);
exchangeRateMantissa = exchangeRateStored();
return (LendTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The principal * market borrow index / recorded borrowIndex
*/
function borrowBalanceStored(address account) public view returns (uint) {
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
(uint principal, uint interestIndex) = this.getAccountBorrows(account);
if (principal == 0) {
return 0;
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
// principalTimesIndex is now 1e36 :: e18 * e18 = e36
principalTimesIndex = principal * borrowIndex;
// result is 1e18 :: e36 / e18 = e18
result = principalTimesIndex / interestIndex;
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the lendToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
uint _totalSupply = totalSupply;
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
// cashPlusBorrows is in 1e18
cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves;
// exchangeRate mantissa is in 1e18 :: e18 * 1e18 / e18
uint exchangeRateMantissa = cashPlusBorrowsMinusReserves * 1e18 / _totalSupply;
return exchangeRateMantissa;
}
}
function getCash() public view returns (uint) {
return payable(address(this)).balance;
}
function getCashPrior() internal view returns (uint) {
uint contractBalance = payable(address(this)).balance;
uint startingBalance = contractBalance - msg.value;
return startingBalance;
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed timestamp
* up to the current timestamp and writes new checkpoint to storage.
*/
function accrueInterest() public {
/* Remember the initial block timestamp */
uint currentTimestamp = block.timestamp;
uint accrualTimestampPrior = accrualTimestamp;
/* Short-circuit accumulating 0 interest */
if (accrualTimestampPrior == currentTimestamp) {
return ;
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the time elapsed since the last accrual */
uint timeDelta = currentTimestamp - accrualTimestampPrior;
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * timeDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
uint simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
// simpleInterestFactor is 1e18 :: e18 * e1
simpleInterestFactor = borrowRateMantissa * timeDelta;
// interestAccumulated is 1e18 :: e18 * e18 /1e18
interestAccumulated = simpleInterestFactor * borrowsPrior / 1e18;
// totalBorrowsNew is 1e18
totalBorrowsNew = interestAccumulated + borrowsPrior;
// totalReservesNew is 1e18 :: (e18 * e18 / e18) + e18
totalReservesNew = (reserveFactorMantissa * interestAccumulated / 1e18) + reservesPrior;
// borrowIndexNew is 1e18 :: (e18 * e18 / e18) + e18
borrowIndexNew = (simpleInterestFactor * borrowIndexPrior / 1e18) + borrowIndexPrior;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualTimestamp = currentTimestamp;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
}
/**
* @notice Returns the current per-seconds borrow interest rate for this LendToken
* @return The borrow interest rate per seconds, scaled by 1e18
*/
function borrowRatePerSeconds() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-seconds supply interest rate for this lendToken
* @return The supply interest rate per seconds, scaled by 1e18
*/
function supplyRatePerSeconds() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public returns (uint) {
accrueInterest();
return exchangeRateStored();
}
/**
* @notice Sender supplies assets into the market and receives lendTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @return (uint) the actual mint amount.
*/
function mint() external payable returns(uint) {
return mintInternal(msg.value);
}
function mintInternal(uint mintAmount) internal nonReentrant returns (uint) {
accrueInterest();
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
/**
* @notice User supplies assets into the market and receives lendTokens in exchange
* @dev Assumes interest has already been accrued up to the current timestamp
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint) the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint) {
/* Fail if mint not allowed */
comptroller.mintAllowed(address(this), minter);
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
exchangeRateMantissa = exchangeRateStored();
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of lendTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
mintTokens = actualMintAmount * 1e18 / exchangeRateMantissa;
/*
* We calculate the new total supply of lendTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
totalSupplyNew = totalSupply + mintTokens;
accountTokensNew = accountTokens[minter] + mintTokens;
/* We write previously calculated values into storage */
totalSupply = totalSupplyNew;
accountTokens[minter] = accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, actualMintAmount, mintTokens);
emit Transfer(address(this), minter, mintTokens);
return (actualMintAmount);
}
/**
* @notice Sender redeems lendTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of lendTokens to redeem into underlying
*/
function redeem(uint redeemTokens) external{
redeemInternal(redeemTokens);
}
function redeemInternal(uint redeemTokens) internal nonReentrant {
accrueInterest();
redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems lendTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming lendTokens
*/
function redeemUnderlying(uint redeemAmount) external{
redeemUnderlyingInternal(redeemAmount);
}
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant{
accrueInterest();
redeemFresh(msg.sender, 0, redeemAmount);
}
/**
* @notice User redeems lendTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current timestamp
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of lendTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming lendTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
*/
struct RedeemVars {
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
function redeemFresh(address redeemer, uint redeemTokensIn, uint redeemAmountIn) internal{
require(redeemTokensIn == 0 || redeemAmountIn == 0, "BAD_INPUT");
RedeemVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
vars.exchangeRateMantissa = exchangeRateStored();
if (vars.exchangeRateMantissa == 0) {
revert ("Fail exchange rate");
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
// redeemAmount is 1e18 :: e18*e18 / 1e18
vars.redeemAmount = vars.exchangeRateMantissa * redeemTokensIn / 1e18;
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
// redeemTokens is 1e18 :: e18 * 1e18 / e18
vars.redeemTokens = redeemAmountIn * 1e18 / vars.exchangeRateMantissa;
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
vars.totalSupplyNew = totalSupply - vars.redeemTokens;
vars.accountTokensNew = accountTokens[redeemer] - vars.redeemTokens;
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
revert ("Insufficient cash");
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
uint feeAmount;
uint remainedAmount;
if (IComptroller(address(comptroller)).treasuryPercent() != 0) {
//feeAmount is 1e18 :: e18 * e18 /1e18
feeAmount = vars.redeemAmount * IComptroller(address(comptroller)).treasuryPercent() /1e18;
remainedAmount = vars.redeemAmount - feeAmount;
} else {
remainedAmount = vars.redeemAmount;
}
if(feeAmount != 0) {
doTransferOut(IComptroller(address(comptroller)).treasuryAddress(), feeAmount);
emit RedeemFee(redeemer, feeAmount, vars.redeemTokens);
}
doTransferOut(redeemer, remainedAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, remainedAmount, vars.redeemTokens);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
*/
function borrow(uint borrowAmount) external {
borrowInternal(borrowAmount);
}
function borrowInternal(uint borrowAmount) internal nonReentrant {
accrueInterest();
// borrowFresh emits borrow-specific logs on errors, so we don't need to
borrowFresh(msg.sender, borrowAmount);
}
/*
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
*/
function borrowFresh(address borrower, uint borrowAmount) internal {
/* Fail if borrow not allowed */
comptroller.borrowAllowed(address(this), borrower, borrowAmount);
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
revert("TOKEN_INSUFFICIENT_CASH");
}
uint localvarsAccountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
localvarsAccountBorrows = borrowBalanceStored(borrower);
accountBorrowsNew = localvarsAccountBorrows + borrowAmount;
totalBorrowsNew = totalBorrows + borrowAmount;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// List borrower to the ledger
if (hasBorrowed[borrower] == false){
hasBorrowed[borrower] = true;
borrowAddress.push(borrower);
}
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, accountBorrowsNew, totalBorrowsNew);
}
/**
* @notice Sender repays their own borrow
* @return actualRepayAmount
*/
function repayBorrow() external payable returns (uint) {
return repayBorrowInternal(msg.value);
}
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint) {
accrueInterest();
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) {
/* Fail if repayBorrow not allowed */
comptroller.repayBorrowAllowed(address(this), borrower);
uint localvarsRepayAmount;
uint borrowerIndex;
uint localvarsAccountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
/* We remember the original borrowerIndex for verification purposes */
borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
localvarsAccountBorrows = borrowBalanceStored(borrower);
/* this part is modified from venus vToken contract, */
// prevent over repay by change repayAmount to maximum repay (total borrowed amount)
if (repayAmount >= localvarsAccountBorrows) {
// Could 'not allowed' to over repay in LendREI because the use of payable function
// if this happen the transaction will revert in 'doTransferIn' function
// localvarsRepayAmount = localvarsAccountBorrows;
// We revert here to prevent over gas cost
revert('Over repay');
} else {
localvarsRepayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
actualRepayAmount = doTransferIn(payer, localvarsRepayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
accountBorrowsNew = localvarsAccountBorrows - actualRepayAmount;
totalBorrowsNew = totalBorrows - actualRepayAmount;
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, actualRepayAmount, accountBorrowsNew, totalBorrowsNew);
return actualRepayAmount;
}
function liquidateBorrow(address borrower, LendTokenInterface lendTokenCollateral) external payable returns (uint) {
return liquidateBorrowInternal(borrower, msg.value, lendTokenCollateral);
}
// Fallback function, sending Rei to contract will mint tokens
receive() external payable {
mintInternal(msg.value);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this lendToken to be liquidated
* @param lendTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, LendTokenInterface lendTokenCollateral) internal nonReentrant returns (uint) {
//Interest must be update in this and Collateral lendToken
accrueInterest();
lendTokenCollateral.accrueInterest();
address liquidator = msg.sender;
/* Fail if liquidate not allowed */
comptroller.liquidateBorrowAllowed(address(this), address(lendTokenCollateral), borrower, repayAmount);
/* Verify lendTokenCollateral market's lastTimestamp equals current timestamp */
if (lendTokenCollateral.accrualTimestamp() != block.timestamp) {
revert ("TIME MISMATCH");
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
revert ("CAN'T SELF LIQUIDATE");
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
revert ("Amount = 0");
}
/* Fail if repayAmount = -1 */
if (repayAmount == type(uint).max) {
revert ("AMOUNT is MAX value");
}
/* Fail if repayBorrow fails */
uint actualRepayAmount = repayBorrowFresh(liquidator, borrower, repayAmount);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
uint seizeTokens = comptroller.liquidateCalculateSeizeTokens(address(this), address(lendTokenCollateral), actualRepayAmount);
/* Revert if borrower collateral token balance < seizeTokens */
require(lendTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
if (address(lendTokenCollateral) == address(this)) {
seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
lendTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(lendTokenCollateral), seizeTokens);
return actualRepayAmount;
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another lendToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed lendToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of lendTokens to seize
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant{
// msg.sender pass the contract caller address to get allowance.
// only Collateral LendToken OR aurumController which are listed in market can call and got allowed.
seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another lendToken.
* Its absolutely critical to use msg.sender as the seizer lendToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed lendToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of lendTokens to seize
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal{
/* Fail if seize not allowed */
comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower);
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
revert ("CAN'T SELF LIQUIDATE");
}
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
borrowerTokensNew = accountTokens[borrower] - seizeTokens;
liquidatorTokensNew = accountTokens[liquidator] + seizeTokens;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
}
/*** Admin Functions ***/
function _setAdmin(address newAdmin) external{
// Check caller = admin
if (msg.sender != admin) {
revert("UNAUTHORIZED");
}
address oldAdmin = admin;
admin = newAdmin;
emit NewAdmin(oldAdmin, newAdmin);
}
// Fee rate
function _setReserveFactor(uint newReserveFactorMantissa) external {
//Only admin function
require (msg.sender == admin,"Only admin function");
accrueInterest();
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
revert ("Value greater than max");
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
}
function _setInterestRateModel(InterestRateModel newInterestRateModel) external {
require (msg.sender == admin, "Only admin");
accrueInterest();
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
}
function _setComptroller(ComptrollerInterface newComptroller) external{
require (msg.sender == admin, "Only admin");
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
}
function _reduceReserves(uint reduceAmount) external nonReentrant{
if (msg.sender != admin) {
revert("UNAUTHORIZED");
}
accrueInterest();
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
revert ("INSUFFICIENT CASH");
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
revert ("INSUFFICIENT RESERVES");
}
// totalReserves - reduceAmount
uint totalReservesNew;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
}
/*** Safe Token ***/
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
// Sanity checks
require(msg.sender == from, "sender mismatch");
require(msg.value == amount, "value mismatch");
return amount;
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address to, uint amount) internal {
payable(to).transfer(amount);
}
} | Fee rateOnly admin function Check newReserveFactor ≤ maxReserveFactor | function _setReserveFactor(uint newReserveFactorMantissa) external {
require (msg.sender == admin,"Only admin function");
accrueInterest();
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
revert ("Value greater than max");
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
}
| 12,649,226 |
./full_match/1/0x552754cBd16264C5141cB5fdAF34246553a10C49/sources/MP/MoonPrinter.sol | Send remaining ETH to treasuryWallet It will send all ETH to treasuryWallet | function forceSend() external onlyOwner {
(bool success, ) = payable(devWallet).call{
value: address(this).balance
}("");
require(success, "Failed to send ETH to dev wallet");
}
| 2,959,481 |
pragma solidity 0.4.24;
/**
* GRP TOKEN Contract
* ERC-20 Token Standard Compliant
* @author Fares A. Akel C. [email protected]
*/
/**
* @title SafeMath by OpenZeppelin
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
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;
}
}
/**
* Token contract interface for external use
*/
contract ERC20TokenInterface {
function balanceOf(address _owner) public constant returns (uint256 value);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
}
/**
* @title Admin parameters
* @dev Define administration parameters for this contract
*/
contract admined { //This token contract is administered
address public admin; //Master address is public
mapping(address => uint256) public level; //Admin level
bool public lockSupply; //Burn Lock flag
/**
* @dev Contract constructor
* define initial administrator
*/
constructor() public {
admin = 0x6585b849371A40005F9dCda57668C832a5be1777; //Set initial admin
level[admin] = 2;
emit Admined(admin);
}
modifier onlyAdmin(uint8 _level) { //A modifier to define admin-only functions
require(msg.sender == admin || level[msg.sender] >= _level);
_;
}
modifier supplyLock() { //A modifier to lock burn transactions
require(lockSupply == false);
_;
}
/**
* @dev Function to set new admin address
* @param _newAdmin The address to transfer administration to
*/
function transferAdminship(address _newAdmin) onlyAdmin(2) public { //Admin can be transfered
require(_newAdmin != address(0));
admin = _newAdmin;
level[_newAdmin] = 2;
emit TransferAdminship(admin);
}
function setAdminLevel(address _target, uint8 _level) onlyAdmin(2) public {
level[_target] = _level;
emit AdminLevelSet(_target,_level);
}
/**
* @dev Function to set burn lock
* @param _set boolean flag (true | false)
*/
function setSupplyLock(bool _set) onlyAdmin(2) public { //Only the admin can set a lock on supply
lockSupply = _set;
emit SetSupplyLock(_set);
}
//All admin actions have a log for public review
event SetSupplyLock(bool _set);
event TransferAdminship(address newAdminister);
event Admined(address administer);
event AdminLevelSet(address _target,uint8 _level);
}
/**
* @title Token definition
* @dev Define token paramters including ERC20 ones
*/
contract ERC20Token is ERC20TokenInterface, admined { //Standard definition of a ERC20Token
using SafeMath for uint256;
uint256 public totalSupply;
mapping (address => uint256) balances; //A mapping of all balances per address
mapping (address => mapping (address => uint256)) allowed; //A mapping of all allowances
/**
* @dev Get the balance of an specified address.
* @param _owner The address to be query.
*/
function balanceOf(address _owner) public constant returns (uint256 value) {
return balances[_owner];
}
/**
* @dev transfer token to a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0)); //If you dont want that people destroy token
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev transfer token from an address to another specified address using allowance
* @param _from The address where token comes.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != address(0)); //If you dont want that people destroy token
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Assign allowance to an specified address to use the owner balance
* @param _spender The address to be allowed to spend.
* @param _value The amount to be allowed.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0)); //exploit mitigation
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Get the allowance of an specified address to use another address balance.
* @param _owner The address of the owner of the tokens.
* @param _spender The address of the allowed spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* @dev Burn token of an specified address.
* @param _target The address of the holder of the tokens.
* @param _burnedAmount amount to burn.
*/
function burnToken(address _target, uint256 _burnedAmount) onlyAdmin(2) supplyLock public {
balances[_target] = SafeMath.sub(balances[_target], _burnedAmount);
totalSupply = SafeMath.sub(totalSupply, _burnedAmount);
emit Burned(_target, _burnedAmount);
}
/**
* @dev Log Events
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burned(address indexed _target, uint256 _value);
event FrozenStatus(address _target,bool _flag);
}
/**
* @title AssetGRP
* @dev Initial supply creation
*/
contract AssetGRP is ERC20Token {
string public name = 'Gripo';
uint8 public decimals = 18;
string public symbol = 'GRP';
string public version = '1';
address writer = 0xA6bc924715A0B63C6E0a7653d3262D26F254EcFd;
constructor() public {
totalSupply = 200000000 * (10**uint256(decimals)); //initial token creation
balances[writer] = totalSupply / 10000; //0.01%
balances[admin] = totalSupply.sub(balances[writer]);
emit Transfer(address(0), writer, balances[writer]);
emit Transfer(address(0), admin, balances[admin]);
}
/**
*@dev Function to handle callback calls
*/
function() public {
revert();
}
} | Burn token of an specified address. _target The address of the holder of the tokens. _burnedAmount amount to burn./ | function burnToken(address _target, uint256 _burnedAmount) onlyAdmin(2) supplyLock public {
balances[_target] = SafeMath.sub(balances[_target], _burnedAmount);
totalSupply = SafeMath.sub(totalSupply, _burnedAmount);
emit Burned(_target, _burnedAmount);
}
| 6,362,615 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0;
pragma experimental ABIEncoderV2;
import './SafeMath.sol';
library FixedPoint {
using SafeMath for uint256;
// The scale to use for fixed point numbers. Same as Ether for simplicity.
uint256 internal constant SCALE = 1e18;
/**
* Calculates a Fixed18 mantissa given the numerator and denominator
*
* The mantissa = (numerator * 1e18) / denominator
*
* @param numerator The mantissa numerator
* @param denominator The mantissa denominator
* @return The mantissa of the fraction
*/
function calculateMantissa(uint256 numerator, uint256 denominator) internal pure returns (uint256) {
uint256 mantissa = numerator.mul(SCALE);
mantissa = mantissa.div(denominator);
return mantissa;
}
/**
* Multiplies a Fixed18 number by an integer.
*
* @param b The whole integer to multiply
* @param mantissa The Fixed18 number
* @return An integer that is the result of multiplying the params.
*/
function multiplyUintByMantissa(uint256 b, uint256 mantissa) internal pure returns (uint256) {
uint256 result = mantissa.mul(b);
result = result.div(SCALE);
return result;
}
/**
* Divides an integer by a fixed point 18 mantissa
*
* @param dividend The integer to divide
* @param mantissa The fixed point 18 number to serve as the divisor
* @return An integer that is the result of dividing an integer by a fixed point 18 mantissa
*/
function divideUintByMantissa(uint256 dividend, uint256 mantissa) internal pure returns (uint256) {
uint256 result = SCALE.mul(dividend);
result = result.div(mantissa);
return result;
}
}
| Calculates a Fixed18 mantissa given the numerator and denominator The mantissa = (numerator 1e18) / denominator numerator The mantissa numerator denominator The mantissa denominator return The mantissa of the fraction/ | function calculateMantissa(uint256 numerator, uint256 denominator) internal pure returns (uint256) {
uint256 mantissa = numerator.mul(SCALE);
mantissa = mantissa.div(denominator);
return mantissa;
}
| 971,638 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
/**
* @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;
}
/**
* @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);
}
}
/*
* @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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev 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;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title 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);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev 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 extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
/// @title A Loot-Derivative Project for the Travel Industry
/// @author jacmos3 - TripsCommunity
/// @notice Text-based NFTs thought for the Travel Industry appannage. Hotels, restaurants, hospitality etc can use them both in the real or metaverse worlds
contract TravelerLoot is ERC721Enumerable, ReentrancyGuard, Ownable {
uint256 private constant DISCOUNT_EXPIRATION = 1790553599; //Sun 27 Sep 2026 21:59:59 UTC
string private constant WHITE = "white";
string private constant BLACK = "black";
string private constant GOLD = "gold";
string private constant PLATINUM = "#D5D6D8";
string private constant GUILD = "GUILD";
string private constant PATRON = "PATRON";
string private constant CONQUEROR = "CONQUEROR";
string private constant OG_LOOT = "Loot (for Adventurers)";
uint160 private constant INITIAL_PRICE_FOR_PATRONS = 1 ether;
string private constant ERROR_TOKEN_ID_INVALID = "Token ID invalid";
string private constant ERROR_ADDRESS_NOT_VERIFIED = "Address not verified. Try another";
string private constant ERROR_NOT_THE_OWNER = "You do not own token(s) of the address";
string private constant ERROR_DOM_40TH_BIRTHDAY = "Only valid till Dom's 40th bday";
string private constant ERROR_LOW_VALUE = "Set a higher value";
string private constant ERROR_COMPETITION_ENDED = "Competition has ended. Check the Conqueror!";
string private constant ERROR_COMPETITION_ONGOING = "Conqueror not yet elected!";
string private constant ERROR_OWNER_NOT_ALLOWED = "Use claimByOwner() instead";
string private constant ERROR_ALREADY_ACTIVATED = "Already activated";
string private constant ERROR_COME_BACK_LATER = "Come back later";
string private constant ERROR_WITHDRAW_NEEDED = "Treasurer already changed. Perform a withdrawal before changing it";
string private constant ERROR_GUILD_ALREADY_WHITELISTED = "Guild already whitelisted!";
string private constant ERROR_CANNOT_ADD_THIS_CONTRACT = "Not possible";
string private constant ERROR_NOT_ENTITLED = "Check conditions before whitelisting";
address private constant INITIAL_TREASURER = 0xce73904422880604e78591fD6c758B0D5106dD50; //TripsCommunity address
address private constant ADDRESS_OG_LOOT = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7;
address private constant PH_USERS = address(1);
address private constant PH_PATRONS = address(2);
address private constant PH_OG_LOOT = address(3);
address private constant PH_CONQUERORS = address(4);
address private constant PH_OWNER = address(0);
uint16 public constant MAX_ID = 10000;
uint16 public constant MAX_FOR_OWNER = 100;
uint16 public constant MAX_FOR_GUILDS = 900;
uint16 public constant LOCK_TIME = 5760 * 3; //it's three days
struct Traveler {
string familyType;
string familyName;
string color;
uint256 counter;
bool verified;
}
struct Conqueror {
address addr;
uint16 count;
bool elected;
}
struct Treasurer {
address old;
address current;
uint256 blockNumber;
}
struct Initial{
address addr;
string symbol;
}
Conqueror public conqueror;
Treasurer public treasurer;
bool public canChangeTreasurer = true;
mapping(address => Traveler) public detailsByAddress;
mapping(uint256 => address) public addressList;
uint8 public counterOwner = 0;
uint16 public counterStandard = 0;
uint16 public counterGuild = 0;
uint16 public counterPatrons = 0;
uint160 public priceForPatrons = INITIAL_PRICE_FOR_PATRONS;
uint256 public blockActivation = 0;
string[] private categories = ["ENVIRONMENT","TALENT","PLACE","CHARACTER","TRANSPORT","LANGUAGE","EXPERIENCE","OCCUPATION","ACCOMMODATION","BAG"];
address[] public whiteListedGuilds;
mapping(string => string[]) elements;
constructor() ERC721("TravelerLoot", "TRVLR") Ownable(){
uint256 blockNumber = block.number;
treasurer.old = address(0);
treasurer.current = INITIAL_TREASURER;
treasurer.blockNumber = blockNumber;
elements[categories[0]] = ["Beaches", "Mountains", "Urban", "Countrysides", "Lakes", "Rivers", "Farms", "Tropical areas", "Snowy places", "Forests", "Historical cities", "Islands", "Wilderness", "Deserts", "Natural parks", "Old towns", "Lakes", "Villages", "Forests", "Coral Reefs", "Wetlands", "Rainforests", "Grasslands", "Chaparral"];
elements[categories[1]] = ["Cooking", "Painting", "Basketball", "Tennis", "Football", "Soccer", "Climbing", "Surfing", "Photographer", "Fishing", "Painting", "Writing", "Dancing", "Architecture", "Singing", "Dancing", "Baking", "Running", "Sword-fighting", "Boxing", "Jumping", "Climbing", "Hiking", "Kitesurfing", "Sailing", "Comforting others", "Flipping NFTs", "Katana sword fighter", "Programming Solidity", "Creating Memes"];
elements[categories[2]] = ["Eiffel Tower", "Colosseum", "Taj Mahal", "Forbidden City", "Las Vegas", "Sagrada Familia", "Statue of Liberty", "Pompeii", "Tulum", "St. Peter's Basilica", "Bangkok", "Tower of London", "Alhambra", "San Marco Square", "Ciudad de las Artes y las Ciencias", "Moscow Kremlin", "Copacabana", "Great Wall of China", "Havana", "Arc de Triomphe", "Neuschwanstein Castle", "Machu Picchu", "Gili Islands", "Maya Bay", "Etherscan", "0x0000000000000000000000000000000000000000", "::1", "42.452483,-6.051345","Parcel 0, CityDAO", "Wyoming"];
elements[categories[3]] = ["Energetic", "Good-Natured", "Enthusiastic", "Challenging", "Charismatic", "Wise", "Modest", "Honest", "Protective", "Perceptive", "Providential", "Prudent", "Spontaneous", "Insightful", "Intelligent", "Intuitive", "Precise", "Sharing", "Simple", "Sociable", "Sophisticated", "Benevolent", "Admirable", "Brilliant", "Accessible", "Calm", "Capable", "Optimistic", "Respectful", "Responsible"];
elements[categories[4]] = ["Train", "Car", "Airplane", "Cruise", "4 wheel drive car", "Bus", "Convertible car", "Bicycle", "Motorbike", "Campervan", "Trailer", "Sailboat", "Electric car", "Sidecar", "Scooter", "Tram", "Cinquecento", "Hitch-hiking", "VW Beetle", "VW Bus", "Truck", "Off-road Vehicle", "Cab", "Lambo", "Ferrari", "Rocket", "DeLorean", "Kia Sedona", "Magic carpet", "Broomstick"];
elements[categories[5]] = ["English", "Mandarin Chinese", "Hindi", "Spanish", "Arabic", "French", "Russian", "Portuguese", "Indonesian", "German", "Japanese", "Turkish", "Korean", "Vietnamese", "Iranian Persian", "Swahili", "Javanese", "Italian", "Thai", "Filipino", "Burmese", "Polish", "Croatian", "Danish", "Serbian", "Slovenian", "Czech", "Slovakian", "Greek", "Hungarian"];
elements[categories[6]] = ["2", "3", "4", "5", "6", "7", "8", "9","10","100","0","1"];
elements[categories[7]] = ["Host", "Cook", "Writer", "DeeJay", "Employee", "Doctor", "Traveler", "Tour Guide", "Ship Pilot", "DAO Member", "Driver", "NFT flipper", "Meme creator", "Sales Manager", "Play 2 Earner", "NFT collector", "Hotel receptionist", "Hotel Manager", "Digital Nomad", "Crypto Trader", "Head of Growth", "PoS validator", "Lightning Network Developer", "Anonymous DeFi Protocol Lead", "Yacht owner (in bull markets)", "Web3 Engineer", "Blockchain Consultant", "Crypto VC", "Miner","Metaverse Realtor"];
elements[categories[8]] = ["Hotel", "Apartment", "Hostel", "Tent", "BnB", "Guest House", "Chalet", "Cottage", "Boat", "Caravan", "Motorhome", "5 stars Hotel", "Suite in 5 Stars Hotel", "Tipi", "Tree House", "Bungalow", "Ranch", "Co-living", "Gablefront cottage", "Longhouse", "Villa", "Yurt", "Housebarn", "Adobe House", "Castle", "Rammed earth", "Underground living", "Venetian palace", "Igloo", "Trullo"];
elements[categories[9]] = ["Pen", "eBook reader", "Water", "Cigarettes", "Swiss knife", "Mobile phone", "Notebook", "Laptop", "Digital Camera", "Lighter", "Earphones", "Beauty case", "Toothbrush", "Toothpaste", "Slippers", "Shirts", "Pants", "T-shirts", "Socks", "Underwear","Condoms"];
detailsByAddress[PH_USERS] = Traveler({color:BLACK,familyType:"",familyName:"",counter:0,verified:true});
detailsByAddress[PH_PATRONS] = Traveler({color:"#F87151",familyType:PATRON,familyName:"",counter:0,verified:true});
detailsByAddress[PH_OG_LOOT] = Traveler({color:GOLD,familyType:PATRON,familyName:OG_LOOT,counter:0,verified:true});
detailsByAddress[PH_CONQUERORS] = Traveler({color:WHITE,familyType:CONQUEROR,familyName:"",counter:0,verified:true});
detailsByAddress[PH_OWNER] = Traveler({color:BLACK,familyType:" ",familyName:"",counter:0,verified:true});
whiteListedGuilds.push(ADDRESS_OG_LOOT);
detailsByAddress[ADDRESS_OG_LOOT] = Traveler({color:PLATINUM,familyType:GUILD,familyName:OG_LOOT,counter:0,verified:true});
}
modifier checkStart() {
require(blockActivation > 0 && block.number >= blockActivation,ERROR_COME_BACK_LATER);
_;
}
/// @notice Everyone can claim an available tokenId for free (+ gas)
function claim() external nonReentrant checkStart {
require(owner() != _msgSender(),ERROR_OWNER_NOT_ALLOWED);
uint16 adjusted = 1 + counterStandard + MAX_FOR_GUILDS + MAX_FOR_OWNER;
require(adjusted <= MAX_ID, ERROR_TOKEN_ID_INVALID);
processing(adjusted,PH_USERS,1,false);
_safeMint(_msgSender(), adjusted);
counterStandard++;
}
/// @notice Guilds can use this function to mint a forged Traveler Loot.
/// Forged TLs are recognizable by a colored line on the NFT.
/// When all the forgeable TLs are minted, the guild who forged
/// the most becomes Conqueror. Its members gain access to
/// claimByConquerors() function
/// @param tokenId derivative's tokenId owned by the user
/// @param contractAddress derivative's address pretending to be guild
function claimByGuilds(uint256 tokenId, address contractAddress) external nonReentrant checkStart{
require(!conqueror.elected, ERROR_COMPETITION_ENDED);
Traveler storage details = detailsByAddress[contractAddress];
require(details.verified, ERROR_ADDRESS_NOT_VERIFIED);
IERC721 looter = IERC721(contractAddress);
require(tokenId > 0 && looter.ownerOf(tokenId) == _msgSender(), ERROR_NOT_THE_OWNER);
if (details.counter == 0 && contractAddress != whiteListedGuilds[0]){
details.color = pickAColor();
}
uint16 discretId = uint16(tokenId % MAX_FOR_GUILDS);
if (counterGuild == MAX_FOR_GUILDS - 1 ){
(conqueror.addr, conqueror.count) = whoIsWinning();
conqueror.elected = true;
detailsByAddress[PH_CONQUERORS].color = details.color;
detailsByAddress[PH_CONQUERORS].familyName = details.familyName;
}
// after this mint, the price for patrons will be increased by 1%
uint16 finalId = discretId == 0 ? MAX_FOR_GUILDS : discretId;
processing(finalId, contractAddress, 1, true);
_safeMint(_msgSender(), finalId);
counterGuild++;
}
/// @notice Becoming a Patron. Requires payment
function claimByPatrons() external payable nonReentrant checkStart{
require(msg.value >= priceForPatrons, ERROR_LOW_VALUE);
if (priceForPatrons < INITIAL_PRICE_FOR_PATRONS){
priceForPatrons == INITIAL_PRICE_FOR_PATRONS;
}
// After this mint, the price for next patrons will be increased by 5%
reservedMinting(PH_PATRONS, 5, true);
counterPatrons++;
}
/// @notice - Loot (for Adventurers) holders can become Patrons for free if:
/// . the Conqueror Guild is not yet elected,
/// . or Dominik Hoffman (@ dhof on twitter) is still younger than 40 y/o.
function claimByOGLooters() external nonReentrant checkStart{
require(IERC721(whiteListedGuilds[0]).balanceOf(_msgSender()) > 0, ERROR_NOT_THE_OWNER);
require(!conqueror.elected, ERROR_COMPETITION_ENDED);
require(block.timestamp <= DISCOUNT_EXPIRATION, ERROR_DOM_40TH_BIRTHDAY);
// After this mint, the price for patrons will be decreased by 5%
reservedMinting(PH_OG_LOOT, 5, false);
counterPatrons++;
}
/// @notice Conquerors can mint a CONQUEROR Traveler Loot for free + gas
/// only valid if they have not already minted a PATRON type before
function claimByConquerors() external nonReentrant checkStart{
require(conqueror.elected, ERROR_COMPETITION_ONGOING);
require(IERC721(conqueror.addr).balanceOf(_msgSender()) > 0, ERROR_NOT_THE_OWNER);
// After this mint, the price for patrons is increased by 2%
reservedMinting(PH_CONQUERORS, 2, true);
counterPatrons++;
}
/// @notice Owner can claim its reserved tokenIds.
function claimByOwner() external nonReentrant onlyOwner checkStart{
uint16 adjusted = 1 + counterOwner + MAX_FOR_GUILDS;
require(adjusted <= MAX_FOR_GUILDS + MAX_FOR_OWNER, ERROR_TOKEN_ID_INVALID);
//after this mint, the price for patrons will remain the same
processing(adjusted,PH_OWNER,0,true);
_safeMint(_msgSender(), adjusted);
counterOwner++;
}
/// @notice Owner can call this function to activate the mintings.
/// Note that the activation is delayed of LOCK_TIME blocks
function activateClaims() external onlyOwner{
require (blockActivation == 0, ERROR_ALREADY_ACTIVATED);
blockActivation = block.number + LOCK_TIME;
}
/// @notice Owner can order the withdraw all the funds coming from Patron mints
/// to the Treasurer address previously set.
function withdraw() external onlyOwner {
require(block.number >= treasurer.blockNumber, ERROR_COME_BACK_LATER);
canChangeTreasurer = true; //release treasurer
payable(treasurer.current).transfer(address(this).balance);
}
/// @notice . Owner calls this function with lockTreasurer = true if the intent is
/// to do a donation to a public-good project. Lock guarantees that nobody
/// (not even the owner) can change treasurer till the donation is made.
/// . Owner calls this function with lockTreasurer = false if the intent is
/// to keep open the chance to change the treasurer even if no any
/// withdrawal has been performed in the meanwhile.
/// @param newAddress the new treasurer address
/// @param lockTreasurer true if the the treasurer has to be locked till one withdraw is performed
function setTreasurer(address newAddress, bool lockTreasurer) external onlyOwner{
require(canChangeTreasurer, ERROR_WITHDRAW_NEEDED); //this is a safety measure for when donating to public goods
if (lockTreasurer){
canChangeTreasurer = false;
}
uint256 blockNumber = block.number + LOCK_TIME;
treasurer.old = treasurer.current;
treasurer.current = newAddress;
treasurer.blockNumber = blockNumber;
}
/// @notice You can register new Guilds to the whitelist, if:
/// - You own at least 50 Traveler Loots in your address
/// - Or if you have mint a Patron version by using claimByPatrons() or
/// claimByOGLooters() functions (no matter if you dont own them anymore)
/// - Or if you are the owner of this Contract
/// NOTE: no Guilds can be registered once the competition has ended
/// @param addresses List of contract addresses to be whitelisted for the game.
/// They'll be allowed to mint GUILD type Traveler Loot
function addNewGuildToWhiteList(address[] calldata addresses) nonReentrant external {
require(!conqueror.elected, ERROR_COMPETITION_ENDED);
for (uint8 j = 0; j< addresses.length; j++){
address addr = addresses[j];
require(address(this) != addr, ERROR_CANNOT_ADD_THIS_CONTRACT);
require(IERC721(address(this)).balanceOf(_msgSender()) > 50
|| _exists(uint160(_msgSender()))
|| owner() == _msgSender()
,ERROR_NOT_ENTITLED);
for (uint16 i = 0; i < whiteListedGuilds.length; i++){
require(whiteListedGuilds[i] != addr, ERROR_GUILD_ALREADY_WHITELISTED);
}
whiteListedGuilds.push(addr);
detailsByAddress[addr] = Traveler({color:BLACK,familyType:GUILD,familyName:familyName(addr),counter:0,verified:true});
}
}
/// @notice Given a Guild address, returns the count for that addr
/// @param addr Address of the Guild to be checked (the contract address)
/// @return Number of the NFT minted from the members of the given Guild address
function getCounterForAddress(address addr) external view returns (uint256){
Traveler memory details = detailsByAddress[addr];
require(details.verified, ERROR_ADDRESS_NOT_VERIFIED);
return details.counter;
}
/// @notice Call this function if you want to know the list of the current Guilds
/// return Array containing the addresses of all the whitelisted guilds
function getWhiteListedGuilds() external view returns (address[] memory){
return whiteListedGuilds;
}
/// @notice Call this function to see the element for a given tokenId and categoryId
/// @param tokenId The id of the Traveler Loot you want to check
/// @param categoryId The category of the Traveler Loot you want to check
/// @return The element of the given Token Id for the given categoryId
function getElement(uint256 tokenId, uint8 categoryId) public view returns (string memory){
return pluck(tokenId, categories[categoryId], elements[categories[categoryId]]);
}
/// @notice Provides metadata and image of the PATRONS and CONQUEROR
/// @param addr Address of the user who minted the PATRON or CONQUEROR you are checking
/// @return The json containing the NFT info
function addressURI(address addr) external view returns (string memory){
return tokenURI(uint160(addr));
}
/// @notice Provides metadata and image of the Traveler Loot
/// @param tokenId Token if of the Traveler Loot to process
/// @return The json containing the NFT info
function tokenURI(uint256 tokenId) override public view returns (string memory) {
Traveler memory details = detailsByAddress[addressList[tokenId]];
string[4] memory parts;
parts[0] = string(abi.encodePacked('<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.b { fill:white; font-family: serif; font-size: 14px; }</style> <rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="b">'));
parts[1] = string(abi.encodePacked(getElement(tokenId,0),'</text><text x="10" y="40" class="b">',getElement(tokenId,1),'</text><text x="10" y="60" class="b">',getElement(tokenId,2),'</text><text x="10" y="80" class="b">',getElement(tokenId,3),'</text><text x="10" y="100" class="b">',getElement(tokenId,4),'</text><text x="10" y="120" class="b">',getElement(tokenId,5)));
parts[2] = string(abi.encodePacked('</text><text x="10" y="140" class="b">',getElement(tokenId,6),'</text><text x="10" y="160" class="b">',getElement(tokenId,7),'</text><text x="10" y="180" class="b">',getElement(tokenId,8),'</text><text x="10" y="200" class="b">',getElement(tokenId,9),'</text>'));
parts[3] = string(abi.encodePacked('<line x1="0" x2="350" y1="300" y2="300" stroke="',details.color,'" stroke-width="4"/>','<text x="340" y="294" text-anchor="end" class="b">',details.familyType,'</text></svg>'));
string memory compact = string(abi.encodePacked(parts[0], parts[1], parts[2],parts[3]));
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Traveler #', toString(tokenId), '", "description": "Traveler Loot is a Loot derivative for the Travel Industry, generated and stored on chain. Feel free to use the Traveler Loot in any way you want", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(compact)), '","attributes":[',metadata(tokenId,details),']}'))));
return string(abi.encodePacked('data:application/json;base64,', json));
}
/// @notice Call this method to check the Guild which is owning the most Forged Traveler Loot
///
/// @return The address of the guild who has the most Forged Traveler Loot so far
/// @return The amount of Forged Traveler Loot minted by the Winning Guild so far
function whoIsWinning() public view returns (address, uint16){
if (conqueror.elected){
return (conqueror.addr,conqueror.count);
}
address winningLoot = whiteListedGuilds[0];
uint16 winningCount = uint16(detailsByAddress[winningLoot].counter);
for (uint8 i = 1; i < whiteListedGuilds.length; i++){
address addr = whiteListedGuilds[i];
(winningLoot, winningCount) = checkWinning(winningLoot,winningCount, addr, uint16(detailsByAddress[addr].counter));
}
return (winningLoot, winningCount);
}
/// @notice Call this function to get a random color using block difficulty, timestamp as seed
/// @return A string containing the HEX number of a random color
function pickAColor() internal view returns (string memory){
string[16] memory list = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
string memory color = "#";
for (uint8 i=0; i<6;i++){
uint rand = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, i )));
color = string(abi.encodePacked(color,list[rand % list.length]));
}
return color;
}
/// @notice This function calls an external NFT contract and gets the symbol to be used into the metadata
/// @param addr The address of the contract address to whitelist
/// @return The symbol of the given external contract address
function familyName(address addr) internal view returns (string memory){
return IERC721Metadata(addr).symbol();
}
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
/// @notice Update the PATRON price and the address counter
/// @param id TokenId minted
/// @param addr address Guild of the token to mint
/// @param percentage percentage number of the PATRON'price variability
/// @param isPositive true if the variability is positive, false if it's negative
function processing(uint256 id, address addr, uint8 percentage, bool isPositive) internal{
if (percentage != 0){
uint160 x = priceForPatrons / (100 / percentage);
priceForPatrons = isPositive ? priceForPatrons + x : priceForPatrons - x;
}
detailsByAddress[addr].counter++;
addressList[id] = addr;
}
/// @notice It mints the Traveler Loot using the address as tokenId.
/// Only particular cases can access to this:
/// - Users who decide to become Patrons by paying the patronPrice
/// - Conqueror Guild members, as the prize for have won the competition
/// - OG Loot owners, as privilegiate users till @ dhof 40 bday or till Conqueror Guild election
/// @param addr address Guild of the token to mint
/// @param percentage percentage number of the PATRON'price variability
/// @param isPositive true if the variability is positive, false if it's negative
function reservedMinting(address addr,uint8 percentage, bool isPositive) internal{
uint160 castedAddress = uint160(_msgSender());
require(castedAddress > MAX_ID, ERROR_ADDRESS_NOT_VERIFIED);
processing(castedAddress, addr, percentage, isPositive);
_safeMint(_msgSender(), castedAddress);
}
/// @notice Call this function to get pick the element for a given Traveler Loot id and category
/// @param tokenId TokenId
/// @param keyPrefix Seed/nounce of the randomity
/// @param sourceArray The list of all the elements
/// @return The element extracted
function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) {
uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId))));
uint8 toHoundred = uint8(rand % 100);
uint8 delta = toHoundred > 95 ? 1 : toHoundred > 80 ? 2 : 3;
uint8 len = uint8(sourceArray.length);
uint8 x = len / 3;
uint8 min = len - (delta * x);
uint8 max = (len - 1) - ((delta - 1) * x);
uint8 rand2 = uint8((random(string(abi.encodePacked(msg.sender, toHoundred, keyPrefix ))) % (max - min + 1)) + min);
return sourceArray[rand2];
}
/// @dev This function processes and build the metadata for the given tokenId
/// @param tokenId TokenId
/// @param details The details to be used for filling the metadata
/// @return The json with the metadata to be appended to the full json
function metadata(uint256 tokenId, Traveler memory details) internal view returns (string memory){
string memory toRet = "";
for (uint8 i = 0; i < 10; i++){
toRet = string(abi.encodePacked(toRet,'{"trait_type":"', categories[i], '","value":"',getElement(tokenId,i),'"},'));
}
if (keccak256(abi.encodePacked(details.color)) != keccak256(abi.encodePacked(BLACK))) {
toRet = string(abi.encodePacked(toRet,'{"trait_type":"Type","value":"',details.familyType,'"}'));
toRet = string(abi.encodePacked(toRet,',{"trait_type":"Flag Color","value":"',details.color,'"}'));
toRet = string(abi.encodePacked(toRet,',{"trait_type":"',details.familyType,'","value":"',details.familyName,'"}'));
}
else{
toRet = string(abi.encodePacked(toRet,'{"trait_type":"Type","value":"EXPLORER"}'));
}
return toRet;
}
/// @dev This function compares two Guilds and check which has more Froged Guild already minted
/// @param winningAddress The legacy winning address (so far)
/// @param winningCount The amount for the legacy winning address (so far)
/// @param newAddress The new address to compare with legacy
/// @param newCount The new amount to compare with legacy
/// @return The new winning address after comparison
/// @return The new minted amount of winning address after comparison
function checkWinning(address winningAddress, uint16 winningCount, address newAddress, uint16 newCount) internal pure returns(address,uint16){
return newCount > winningCount ? (newAddress, newCount) : (winningAddress, winningCount);
}
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
| Given a Guild address, returns the count for that addr addr Address of the Guild to be checked (the contract address) return Number of the NFT minted from the members of the given Guild address | function getCounterForAddress(address addr) external view returns (uint256){
Traveler memory details = detailsByAddress[addr];
require(details.verified, ERROR_ADDRESS_NOT_VERIFIED);
return details.counter;
}
| 1,050,415 |
/*
website: bns.finance
This project is freshly written to change the way ICO is done.
BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNNN SSSSSSSSSSSSSSS DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFIIIIIIIIII
B::::::::::::::::B N:::::::N N::::::N SS:::::::::::::::S D::::::::::::DDD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I
B::::::BBBBBB:::::B N::::::::N N::::::NS:::::SSSSSS::::::S D:::::::::::::::DD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I
BB:::::B B:::::BN:::::::::N N::::::NS:::::S SSSSSSS DDD:::::DDDDD:::::DEE::::::EEEEEEEEE::::EFF::::::FFFFFFFFF::::FII::::::II
B::::B B:::::BN::::::::::N N::::::NS:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F FFFFFF I::::I
B::::B B:::::BN:::::::::::N N::::::NS:::::S D:::::D D:::::DE:::::E F:::::F I::::I
B::::BBBBBB:::::B N:::::::N::::N N::::::N S::::SSSS D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I
B:::::::::::::BB N::::::N N::::N N::::::N SS::::::SSSSS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I
B::::BBBBBB:::::B N::::::N N::::N:::::::N SSS::::::::SS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I
B::::B B:::::BN::::::N N:::::::::::N SSSSSS::::S D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I
B::::B B:::::BN::::::N N::::::::::N S:::::S D:::::D D:::::DE:::::E F:::::F I::::I
B::::B B:::::BN::::::N N:::::::::N S:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F I::::I
BB:::::BBBBBB::::::BN::::::N N::::::::NSSSSSSS S:::::S DDD:::::DDDDD:::::DEE::::::EEEEEEEE:::::EFF:::::::FF II::::::II
B:::::::::::::::::B N::::::N N:::::::NS::::::SSSSSS:::::S ...... D:::::::::::::::DD E::::::::::::::::::::EF::::::::FF I::::::::I
B::::::::::::::::B N::::::N N::::::NS:::::::::::::::SS .::::. D::::::::::::DDD E::::::::::::::::::::EF::::::::FF I::::::::I
BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNN SSSSSSSSSSSSSSS ...... DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFF IIIIIIIIII
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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, "SAO");
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, "SMO");
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 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, "IB");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "RR");
}
/**
* @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, "IBC");
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), "CNC");
// 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);
}
}
}
}
/**
* @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, "DAB0");
_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, "LF1");
if (returndata.length != 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "LF2");
}
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 public _totalSupply;
string public _name;
string public _symbol;
uint8 public _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), "ISA");
require(recipient != address(0), "IRA");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "TIF");
_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), "M0");
_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), "B0");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "BIB");
_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), "IA");
require(spender != address(0), "A0");
_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 { }
}
contract BnsdLaunchPool is Context {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of a raising pool.
struct RaisePoolInfo {
IERC20 raiseToken; // Address of raising token contract.
uint256 maxTokensPerPerson; // Maximum tokens a user can buy.
uint256 totalTokensOnSale; // Total tokens available on offer.
uint256 startBlock; // When the sale starts
uint256 endBlock; // When the sale ends
uint256 totalTokensSold; // Total tokens sold to users so far
uint256 tokensDeposited; // Total ICO tokens deposited
uint256 votes; // Voted by users
address owner; // Owner of the pool
bool updateLocked; // No pool info can be updated once this is turned ON
bool balanceAdded; // Whether ICO tokens are added in correct amount
bool paymentMethodAdded; // Supported currencies added or not
string poolName; // Human readable string name of the pool
}
struct AirdropPoolInfo {
uint256 totalTokensAvailable; // Total tokens staked so far.
IERC20 airdropToken; // Address of staking LP token.
bool airdropExists;
}
// Info of a raising pool.
struct UseCasePoolInfo {
uint256 tokensAllocated; // Total tokens available for this use
uint256 tokensClaimed; // Total tokens claimed
address reserveAdd; // Address where tokens will be released for that usecase.
bool tokensDeposited; // No pool info can be updated once this is turned ON
bool exists; // Whether reserve already exists for a pool
string useName; // Human readable string name of the pool
uint256[] unlock_perArray; // Release percent for usecase
uint256[] unlock_daysArray; // Release days for usecase
}
struct DistributionInfo {
uint256[] percentArray; // Percentage of tokens to be unlocked every phase
uint256[] daysArray; // Days from the endDate when tokens starts getting unlocked
}
// The BNSD TOKEN!
address public timeLock;
// Dev address.
address public devaddr;
// Temp dev address while switching
address private potentialAdmin;
// To store owner diistribution info after sale ends
mapping (uint256 => DistributionInfo) private ownerDistInfo;
// To store user distribution info after sale ends
mapping (uint256 => DistributionInfo) private userDistInfo;
// To store tokens on sale and their rates
mapping (uint256 => mapping (address => uint256)) public saleRateInfo;
// To store invite codes and corresponding token address and pool owners, INVITE CODE => TOKEN => OWNER => bool
mapping (uint256 => mapping (address => mapping (address => bool))) private inviteCodeList;
// To store user contribution for a sale - POOL => USER => USDT
mapping (uint256 => mapping (address => mapping (address => uint256))) public userDepositInfo;
// To store total token promised to a user - POOL => USER
mapping (uint256 => mapping (address => uint256)) public userTokenAllocation;
// To store total token claimed by a user already
mapping (uint256 => mapping (address => uint256)) public userTokenClaimed;
// To store total token redeemed by users after sale
mapping (uint256 => uint256) public totalTokenClaimed;
// To store total token raised by a project - POOL => TOKEN => AMT
mapping (uint256 => mapping (address => uint256)) public fundsRaisedSoFar;
mapping (uint256 => address) private tempAdmin;
// To store total token claimed by a project
mapping (uint256 => mapping (address => uint256)) public fundsClaimedSoFar;
// To store addresses voted for a project - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public userVotes;
// No of blocks in a day - 6700
uint256 public constant BLOCKS_PER_DAY = 6700; // Changing to 5 for test cases
// Info of each pool on blockchain.
RaisePoolInfo[] public poolInfo;
// Info of reserve pool of any project - POOL => RESERVE_ADD => USECASEINFO
mapping (uint256 => mapping (address => UseCasePoolInfo)) public useCaseInfo;
// To store total token reserved
mapping (uint256 => uint256) public totalTokenReserved;
// To store total reserved claimed
mapping (uint256 => uint256) public totalReservedTokenClaimed;
// To store list of all sales associated with a token
mapping (address => uint256[]) public listSaleTokens;
// To store list of all currencies allowed for a sale
mapping (uint256 => address[]) public listSupportedCurrencies;
// To store list of all reserve addresses for a sale
mapping (uint256 => address[]) public listReserveAddresses;
// To check if staking is enabled on a token
mapping (address => bool) public stakingEnabled;
// To get staking weight of a token
mapping (address => uint256) public stakingWeight;
// To store sum of weight of all staking tokens
uint256 public totalStakeWeight;
// To store list of staking addresses
address[] public stakingPools;
// To store stats of staked tokens per sale
mapping (uint256 => mapping (address => uint256)) public stakedLPTokensInfo;
// To store user staked amount for a sale - POOL => USER => LP_TOKEN
mapping (uint256 => mapping (address => mapping (address => uint256))) public userStakeInfo;
// To store reward claimed by a user - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public rewardClaimed;
// To store airdrop claimed by a user - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public airdropClaimed;
// To store extra airdrop tokens withdrawn by fund raiser - POOL => BOOL
mapping (uint256 => bool) public extraAirdropClaimed;
// To store airdrop info for a sale
mapping (uint256 => AirdropPoolInfo) public airdropInfo;
// To store airdrop tokens balance of a user , TOKEN => USER => BAL
mapping (address => mapping (address => uint256)) public airdropBalances;
uint256 public fee = 300; // To be divided by 1e4 before using it anywhere => 3.00%
uint256 public constant rewardPer = 8000; // To be divided by 1e4 before using it anywhere => 80.00%
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Stake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount);
event UnStake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount);
event MoveStake(address indexed user, address indexed lptoken, uint256 pid, uint256 indexed pidnew, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event WithdrawAirdrop(address indexed user, address indexed token, uint256 amount);
event ClaimAirdrop(address indexed user, address indexed token, uint256 amount);
event AirdropDeposit(address indexed user, address indexed token, uint256 indexed pid, uint256 amount);
event AirdropExtraWithdraw(address indexed user, address indexed token, uint256 indexed pid, uint256 amount);
event Voted(address indexed user, uint256 indexed pid);
constructor() public {
devaddr = _msgSender();
}
modifier onlyAdmin() {
require(devaddr == _msgSender(), "ND");
_;
}
modifier onlyAdminOrTimeLock() {
require((devaddr == _msgSender() || timeLock == _msgSender()), "ND");
_;
}
function setTimeLockAdd(address _add) public onlyAdmin {
timeLock = _add;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function getListOfSale(address _token) external view returns (uint256[] memory) {
return listSaleTokens[_token];
}
function getUserDistPercent(uint256 _pid) external view returns (uint256[] memory) {
return userDistInfo[_pid].percentArray;
}
function getUserDistDays(uint256 _pid) external view returns (uint256[] memory) {
return userDistInfo[_pid].daysArray;
}
function getReserveUnlockPercent(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) {
return useCaseInfo[_pid][_reserveAdd].unlock_perArray;
}
function getReserveUnlockDays(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) {
return useCaseInfo[_pid][_reserveAdd].unlock_daysArray;
}
function getUserDistBlocks(uint256 _pid) external view returns (uint256[] memory) {
uint256[] memory daysArray = userDistInfo[_pid].daysArray;
uint256 endPool = poolInfo[_pid].endBlock;
for(uint256 i=0; i<daysArray.length; i++){
daysArray[i] = (daysArray[i].mul(BLOCKS_PER_DAY)).add(endPool);
}
return daysArray;
}
function getOwnerDistPercent(uint256 _pid) external view returns (uint256[] memory) {
return ownerDistInfo[_pid].percentArray;
}
function getOwnerDistDays(uint256 _pid) external view returns (uint256[] memory) {
return ownerDistInfo[_pid].daysArray;
}
// Add a new token sale to the pool. Can only be called by the person having the invite code.
function addNewPool(uint256 totalTokens, uint256 maxPerPerson, uint256 startBlock, uint256 endBlock, string memory namePool, IERC20 tokenAddress, uint256 _inviteCode) external returns (uint256) {
require(endBlock > startBlock, "ESC"); // END START COMPARISON FAILED
require(startBlock > block.number, "TLS"); // TIME LIMIT START SALE
require(maxPerPerson !=0 && totalTokens!=0, "IIP"); // INVALID INDIVIDUAL PER PERSON
require(inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()]==true,"IIC"); // INVALID INVITE CODE
poolInfo.push(RaisePoolInfo({
raiseToken: tokenAddress,
maxTokensPerPerson: maxPerPerson,
totalTokensOnSale: totalTokens,
startBlock: startBlock,
endBlock: endBlock,
poolName: namePool,
updateLocked: false,
owner: _msgSender(),
totalTokensSold: 0,
balanceAdded: false,
tokensDeposited: 0,
paymentMethodAdded: false,
votes: 0
}));
uint256 poolId = (poolInfo.length - 1);
listSaleTokens[address(tokenAddress)].push(poolId);
// This makes the invite code claimed
inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()] = false;
return poolId;
}
function _checkSumArray(uint256[] memory _percentArray) internal pure returns (bool) {
uint256 _sum;
for (uint256 i = 0; i < _percentArray.length; i++) {
_sum = _sum.add(_percentArray[i]);
}
return (_sum==10000);
}
function _checkValidDaysArray(uint256[] memory _daysArray) internal pure returns (bool) {
uint256 _lastDay = _daysArray[0];
for (uint256 i = 1; i < _daysArray.length; i++) {
if(_lastDay < _daysArray[i]){
_lastDay = _daysArray[i];
}
else {
return false;
}
}
return true;
}
function _checkUpdateAllowed(uint256 _pid) internal view{
RaisePoolInfo storage pool = poolInfo[_pid];
require(pool.updateLocked == false, "CT2"); // CRITICAL TERMINATION 2
require(pool.owner==_msgSender(), "OAU"); // OWNER AUTHORIZATION FAILED
require(pool.startBlock > block.number, "CT"); // CRITICAL TERMINATION
}
// Add rule for funds locking after sale
function updateUserDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external {
require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH
_checkUpdateAllowed(_pid);
require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
userDistInfo[_pid] = DistributionInfo({
percentArray: _percentArray,
daysArray: _daysArray
});
}
// Add rule for funds unlocking of the fund raiser after sale
function updateOwnerDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external {
require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH
_checkUpdateAllowed(_pid);
require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
ownerDistInfo[_pid] = DistributionInfo({
percentArray: _percentArray,
daysArray: _daysArray
});
}
// Lock sale detail changes in future
function lockPool(uint256 _pid) external {
require(poolInfo[_pid].paymentMethodAdded==true, "CP"); // CHECK PAYMENT METHOD FAILED
_checkUpdateAllowed(_pid);
poolInfo[_pid].updateLocked = true;
}
// Add supported currencies and their rate w.r.t token on sale
// rateToken = price of one satoshi of the token in terms of token to be raised * 1e18
// 1 BNSD = 0.00021 ETH => 1e18 BNSD Satoshi = 0.00021 * 1e18 ETH satoshi => 1 BNSD Satoshi = 0.00021 ETH satoshi => rateToken = 0.00021 * 1e18 = 21 * 1e13
// rateToken for BNSD/ETH pair = 21 * 1e13;
function addSupportedCurrencies(uint256 _pid, address _tokenRaise, uint256 rateToken) external {
_checkUpdateAllowed(_pid);
require(rateToken!=0, "IR"); // INVALID RATE
require(_tokenRaise!=address(poolInfo[_pid].raiseToken), "IT"); // INVALIID PURCHASE TOKEN
if(saleRateInfo[_pid][_tokenRaise] == 0){
listSupportedCurrencies[_pid].push(_tokenRaise);
}
saleRateInfo[_pid][_tokenRaise] = rateToken;
poolInfo[_pid].paymentMethodAdded = true;
}
function getSupportedCurrencies(uint256 _pid) external view returns (address[] memory) {
return listSupportedCurrencies[_pid];
}
function _checkUpdateReserveAllowed(uint256 _pid, address _resAdd) internal view returns (bool) {
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
return (poolU.exists == false || poolU.tokensDeposited == false);
// if(poolU.exists == false || poolU.tokensDeposited == false){
// return true;
// }
// return false;
}
function addReservePool(uint256 _pid, address _reserveAdd, string memory _nameReserve, uint256 _totalTokens, uint256[] memory _perArray, uint256[] memory _daysArray) external {
_checkUpdateAllowed(_pid);
require(_checkUpdateReserveAllowed(_pid, _reserveAdd) == true, "UB"); // UPDATE RESERVE FAILED
require(_checkSumArray(_perArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
require(_perArray.length==_daysArray.length, "IAL"); // INVALID ARRAY LENGTH
if(useCaseInfo[_pid][_reserveAdd].exists == false){
listReserveAddresses[_pid].push(_reserveAdd);
}
useCaseInfo[_pid][_reserveAdd] = UseCasePoolInfo({
reserveAdd: _reserveAdd,
useName: _nameReserve,
tokensAllocated: _totalTokens,
unlock_perArray: _perArray,
unlock_daysArray: _daysArray,
tokensDeposited: false,
tokensClaimed: 0,
exists: true
});
}
function getReserveAddresses(uint256 _pid) external view returns (address[] memory) {
return listReserveAddresses[_pid];
}
function tokensPurchaseAmt(uint256 _pid, address _tokenAdd, uint256 amt) public view returns (uint256) {
uint256 rateToken = saleRateInfo[_pid][_tokenAdd];
require(rateToken!=0, "NAT"); // NOT AVAILABLE TOKEN
return (amt.mul(1e18)).div(rateToken);
}
// Check if user can deposit specfic amount of funds to the pool
function _checkDepositAllowed(uint256 _pid, address _tokenAdd, uint256 _amt) internal view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
uint256 userBought = userTokenAllocation[_pid][_msgSender()];
uint256 purchasePossible = tokensPurchaseAmt(_pid, _tokenAdd, _amt);
require(pool.balanceAdded == true, "NA"); // NOT AVAILABLE
require(pool.startBlock <= block.number, "NT1"); // NOT AVAILABLE TIME 1
require(pool.endBlock >= block.number, "NT2"); // NOT AVAILABLE TIME 2
require(pool.totalTokensSold.add(purchasePossible) <= pool.totalTokensOnSale, "PLE"); // POOL LIMIT EXCEEDED
require(userBought.add(purchasePossible) <= pool.maxTokensPerPerson, "ILE"); // INDIVIDUAL LIMIT EXCEEDED
return purchasePossible;
}
// Check max a user can deposit right now
function getMaxDepositAllowed(uint256 _pid, address _tokenAdd, address _user) external view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
uint256 maxBuyPossible = (pool.maxTokensPerPerson).sub(userTokenAllocation[_pid][_user]);
uint256 maxBuyPossiblePoolLimit = (pool.totalTokensOnSale).sub(pool.totalTokensSold);
if(maxBuyPossiblePoolLimit < maxBuyPossible){
maxBuyPossible = maxBuyPossiblePoolLimit;
}
if(block.number >= pool.startBlock && block.number <= pool.endBlock && pool.balanceAdded == true){
uint256 rateToken = saleRateInfo[_pid][_tokenAdd];
return (maxBuyPossible.mul(rateToken).div(1e18));
}
else {
return 0;
}
}
// Check if deposit is enabled for a pool
function checkDepositEnabled(uint256 _pid) external view returns (bool){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.balanceAdded == true && pool.startBlock <= block.number && pool.endBlock >= block.number && pool.totalTokensSold <= pool.totalTokensOnSale && pool.paymentMethodAdded==true){
return true;
}
else {
return false;
}
}
// Deposit ICO tokens to start a pool for ICO.
function depositICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NOT"); // NOT VALID TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(block.number < pool.endBlock, "NT"); // No point adding tokens after sale has ended - Possible deadlock case
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
pool.tokensDeposited = (pool.tokensDeposited).add(_amount);
if(pool.tokensDeposited >= pool.totalTokensOnSale){
pool.balanceAdded = true;
}
emit Deposit(msgSender, _pid, _amount);
}
// Deposit Airdrop tokens anytime before end of the sale.
function depositAirdropTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number < pool.endBlock, "NT"); // NOT VALID TIME
AirdropPoolInfo storage airdrop = airdropInfo[_pid];
require((_tokenAdd == airdrop.airdropToken || airdrop.airdropExists==false), "NOT"); // NOT VALID TOKEN
require(_msgSender() == pool.owner || _msgSender() == devaddr , "NAU"); // NOT AUTHORISED USER
_tokenAdd.safeTransferFrom(_msgSender(), address(this), _amount);
airdrop.totalTokensAvailable = (airdrop.totalTokensAvailable).add(_amount);
if(!airdrop.airdropExists){
airdrop.airdropToken = _tokenAdd;
airdrop.airdropExists = true;
}
emit AirdropDeposit(_msgSender(), address(_tokenAdd), _pid, _amount);
}
// Withdraw extra airdrop tokens - Possible only if no one added liquidity to one of the pools
function withdrawExtraAirdropTokens(uint256 _pid) external {
require(extraAirdropClaimed[_pid]==false, "NA"); // NOT AVAILABLE
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "NSE"); // SALE NOT ENDED
address msgSender = _msgSender();
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
uint256 extraTokens = calculateExtraAirdropTokens(_pid);
require(extraTokens!=0, "NAT"); // NOT AVAILABLE TOKEN
extraAirdropClaimed[_pid] = true;
airdropInfo[_pid].airdropToken.safeTransfer(msgSender, extraTokens);
emit AirdropExtraWithdraw(msg.sender, address(airdropInfo[_pid].airdropToken), _pid, extraTokens);
}
function calculateExtraAirdropTokens(uint256 _pid) public view returns (uint256){
if(extraAirdropClaimed[_pid] == true) return 0;
uint256 _totalTokens;
for (uint256 i=0; i<stakingPools.length; i++){
uint256 stake = stakedLPTokensInfo[_pid][stakingPools[i]];
if(stake == 0){
_totalTokens = _totalTokens.add(((stakingWeight[stakingPools[i]]).mul(airdropInfo[_pid].totalTokensAvailable)).div(totalStakeWeight));
}
}
return _totalTokens;
}
// Deposit LP tokens for a sale.
function stakeLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external {
require(stakingEnabled[address(_lpAdd)]==true, "NST"); // NOT STAKING TOKEN
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number < pool.startBlock, "NT"); // NOT VALID TIME
address msgSender = _msgSender();
_lpAdd.safeTransferFrom(msgSender, address(this), _amount);
stakedLPTokensInfo[_pid][address(_lpAdd)] = (stakedLPTokensInfo[_pid][address(_lpAdd)]).add(_amount);
userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).add(_amount);
emit Stake(msg.sender, address(_lpAdd), _pid, _amount);
}
// Withdraw LP tokens from a sale after it's over => Automatically claims rewards and airdrops also
function withdrawLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external {
require(stakingEnabled[address(_lpAdd)]==true, "NAT"); // NOT AUTHORISED TOKEN
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "SE"); // SALE NOT ENDED
address msgSender = _msgSender();
claimRewardAndAirdrop(_pid);
userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).sub(_amount);
_lpAdd.safeTransfer(msgSender, _amount);
emit UnStake(msg.sender, address(_lpAdd), _pid, _amount);
}
// Withdraw airdrop tokens accumulated over one or more than one sale.
function withdrawAirdropTokens(IERC20 _token, uint256 _amount) external {
address msgSender = _msgSender();
airdropBalances[address(_token)][msgSender] = (airdropBalances[address(_token)][msgSender]).sub(_amount);
_token.safeTransfer(msgSender, _amount);
emit WithdrawAirdrop(msgSender, address(_token), _amount);
}
// Move LP tokens from one sale to another directly => Automatically claims rewards and airdrops also
function moveLPTokens(uint256 _pid, uint256 _newpid, uint256 _amount, address _lpAdd) external {
require(stakingEnabled[_lpAdd]==true, "NAT1"); // NOT AUTHORISED TOKEN 1
RaisePoolInfo storage poolOld = poolInfo[_pid];
RaisePoolInfo storage poolNew = poolInfo[_newpid];
require(block.number > poolOld.endBlock, "NUA"); // OLD SALE NOT ENDED
require(block.number < poolNew.startBlock, "NSA"); // SALE START CHECK FAILED
address msgSender = _msgSender();
claimRewardAndAirdrop(_pid);
userStakeInfo[_pid][msgSender][_lpAdd] = (userStakeInfo[_pid][msgSender][_lpAdd]).sub(_amount);
userStakeInfo[_newpid][msgSender][_lpAdd] = (userStakeInfo[_newpid][msgSender][_lpAdd]).add(_amount);
emit MoveStake(msg.sender, _lpAdd, _pid, _newpid, _amount);
}
function claimRewardAndAirdrop(uint256 _pid) public {
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "SE"); // SUM INVALID
_claimReward(_pid, _msgSender());
_claimAirdrop(_pid, _msgSender());
}
function _claimReward(uint256 _pid, address _user) internal {
if (rewardClaimed[_pid][_user]==false){
rewardClaimed[_pid][_user] = true;
for (uint256 i=0; i<stakingPools.length; i++){
for(uint256 j=0; j<listSupportedCurrencies[_pid].length; j++){
uint256 _tokenAmt = getReward(_pid, _user, stakingPools[i], listSupportedCurrencies[_pid][j]);
_creditAirdrop(_user, listSupportedCurrencies[_pid][j], _tokenAmt);
}
}
}
}
function _claimAirdrop(uint256 _pid, address _user) internal {
if (airdropClaimed[_pid][_user]==false){
airdropClaimed[_pid][_user] = true;
address _airdropToken = address(airdropInfo[_pid].airdropToken);
uint256 _tokenAmt = 0;
for (uint256 i=0; i<stakingPools.length; i++){
_tokenAmt = _tokenAmt.add(getAirdrop(_pid, _user, stakingPools[i]));
}
if(_tokenAmt !=0){
_creditAirdrop(_user, _airdropToken, _tokenAmt);
}
}
}
function _creditAirdrop(address _user, address _token, uint256 _amt) internal {
airdropBalances[_token][_user] = (airdropBalances[_token][_user]).add(_amt);
emit ClaimAirdrop(_user, _token, _amt);
}
function getReward(uint256 _pid, address _user, address _lpAdd, address _token) public view returns (uint256) {
uint256 stake = stakedLPTokensInfo[_pid][_lpAdd];
if(stake==0) return 0;
uint256 _multipliedData = (userStakeInfo[_pid][_user][_lpAdd]).mul(fundsRaisedSoFar[_pid][_token]);
_multipliedData = (_multipliedData).mul(rewardPer).mul(fee).mul(stakingWeight[_lpAdd]);
return (((_multipliedData).div(stake)).div(1e8)).div(totalStakeWeight);
}
function getAirdrop(uint256 _pid, address _user, address _lpAdd) public view returns (uint256) {
uint256 _userStaked = userStakeInfo[_pid][_user][_lpAdd];
uint256 _totalStaked = stakedLPTokensInfo[_pid][_lpAdd];
if(_totalStaked==0) return 0;
return ((((_userStaked).mul(airdropInfo[_pid].totalTokensAvailable).mul(stakingWeight[_lpAdd])).div(_totalStaked))).div(totalStakeWeight);
}
// Deposit ICO tokens for a use case as reserve.
function depositReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd, address _resAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NOT"); // NOT AUTHORISED TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(poolU.tokensDeposited == false, "DR"); // TOKENS NOT DEPOSITED
require(poolU.tokensAllocated == _amount && _amount!=0, "NA"); // NOT AVAILABLE
require(block.number < pool.endBlock, "CRN"); // CANNOT_RESERVE_NOW to avoid deadlocks
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
totalTokenReserved[_pid] = (totalTokenReserved[_pid]).add(_amount);
poolU.tokensDeposited = true;
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw extra unsold ICO tokens or extra deposited tokens.
function withdrawExtraICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NT"); // NOT AUTHORISED TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(block.number > pool.endBlock, "NA"); // NOT AVAILABLE TIME
uint256 _amtAvail = pool.tokensDeposited.sub(pool.totalTokensSold);
require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE TOKEN
pool.tokensDeposited = (pool.tokensDeposited).sub(_amount);
_tokenAdd.safeTransfer(msgSender, _amount);
emit Withdraw(msgSender, _pid, _amount);
}
// Fetch extra ICO tokens available.
function fetchExtraICOTokens(uint256 _pid) external view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
return pool.tokensDeposited.sub(pool.totalTokensSold);
}
// Deposit tokens to a pool for ICO.
function deposit(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
address msgSender = _msgSender();
uint256 _buyThisStep = _checkDepositAllowed(_pid, address(_tokenAdd), _amount);
// require(_buyThisStep >= _amount, "CDE");
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
userDepositInfo[_pid][msgSender][address(_tokenAdd)] = userDepositInfo[_pid][msgSender][address(_tokenAdd)].add(_amount);
userTokenAllocation[_pid][msgSender] = userTokenAllocation[_pid][msgSender].add(_buyThisStep);
poolInfo[_pid].totalTokensSold = poolInfo[_pid].totalTokensSold.add(_buyThisStep);
fundsRaisedSoFar[_pid][address(_tokenAdd)] = fundsRaisedSoFar[_pid][address(_tokenAdd)].add(_amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Vote your favourite ICO project.
function voteProject(uint256 _pid) external {
address msgSender = _msgSender();
require(userVotes[_pid][msgSender]==false,"AVO"); // ALREADY VOTED
require(poolInfo[_pid].endBlock >= block.number,"CVO"); // CANNOT VOTE NOW
userVotes[_pid][msgSender] = true;
poolInfo[_pid].votes = (poolInfo[_pid].votes).add(1);
emit Voted(msgSender, _pid);
}
function _calculatePerAvailable(uint256[] memory _daysArray, uint256[] memory _percentArray, uint256 blockEnd) internal view returns (uint256) {
uint256 _defaultPer = 10000;
uint256 _perNow;
if(_daysArray.length==0){
return _defaultPer;
}
uint256 daysDone = ((block.number).sub(blockEnd)).div(BLOCKS_PER_DAY);
for (uint256 i = 0; i < _daysArray.length; i++) {
if(_daysArray[i] <= daysDone){
_perNow = _perNow.add(_percentArray[i]);
}
else {
break;
}
}
return _perNow;
}
function _getPercentAvailable(uint256 _pid, uint256 blockEnd) internal view returns (uint256){
DistributionInfo storage distInfo = userDistInfo[_pid];
uint256[] storage _percentArray = distInfo.percentArray;
uint256[] storage _daysArray = distInfo.daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by user till now - public
function amountAvailToWithdrawUser(uint256 _pid, address _user) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailable(_pid, pool.endBlock);
return ((percentAvail).mul(userTokenAllocation[_pid][_user]).div(10000)).sub(userTokenClaimed[_pid][_user]);
}
else {
return 0;
}
}
// Withdraw ICO tokens after sale is over based on distribution rules.
function withdrawUser(uint256 _pid, uint256 _amount) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
uint256 _amtAvail = amountAvailToWithdrawUser(_pid, msgSender);
require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN
userTokenClaimed[_pid][msgSender] = userTokenClaimed[_pid][msgSender].add(_amount);
totalTokenClaimed[_pid] = totalTokenClaimed[_pid].add(_amount);
pool.raiseToken.safeTransfer(msgSender, _amount);
emit Withdraw(msgSender, _pid, _amount);
}
function _getPercentAvailableFundRaiser(uint256 _pid, uint256 blockEnd) internal view returns (uint256){
DistributionInfo storage distInfo = ownerDistInfo[_pid];
uint256[] storage _percentArray = distInfo.percentArray;
uint256[] storage _daysArray = distInfo.daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by user till now
function amountAvailToWithdrawFundRaiser(uint256 _pid, IERC20 _tokenAdd) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailableFundRaiser(_pid, pool.endBlock);
return (((percentAvail).mul(fundsRaisedSoFar[_pid][address(_tokenAdd)]).div(10000))).sub(fundsClaimedSoFar[_pid][address(_tokenAdd)]);
}
else {
return 0;
}
}
function _getPercentAvailableReserve(uint256 _pid, uint256 blockEnd, address _resAdd) internal view returns (uint256){
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
uint256[] storage _percentArray = poolU.unlock_perArray;
uint256[] storage _daysArray = poolU.unlock_daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by reserve user till now
function amountAvailToWithdrawReserve(uint256 _pid, address _resAdd) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailableReserve(_pid, pool.endBlock, _resAdd);
return ((percentAvail).mul(poolU.tokensAllocated).div(10000)).sub(poolU.tokensClaimed);
}
else {
return 0;
}
}
// Withdraw ICO tokens for various use cases as per the schedule promised on provided address.
function withdrawReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_msgSender()];
require(poolU.reserveAdd == _msgSender(), "NAUTH"); // NOT AUTHORISED USER
require(_tokenAdd == poolInfo[_pid].raiseToken, "NT"); // NOT AUTHORISED TOKEN
uint256 _amtAvail = amountAvailToWithdrawReserve(_pid, _msgSender());
require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE USER
poolU.tokensClaimed = poolU.tokensClaimed.add(_amount);
totalTokenReserved[_pid] = totalTokenReserved[_pid].sub(_amount);
totalReservedTokenClaimed[_pid] = totalReservedTokenClaimed[_pid].add(_amount);
_tokenAdd.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _pid, _amount);
}
// Withdraw raised funds after sale is over as per the schedule promised
function withdrawFundRaiser(uint256 _pid, uint256 _amount, IERC20 _tokenAddress) external {
RaisePoolInfo storage pool = poolInfo[_pid];
require(pool.owner == _msgSender(), "NAUTH"); // NOT AUTHORISED USER
uint256 _amtAvail = amountAvailToWithdrawFundRaiser(_pid, _tokenAddress);
require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN
uint256 _fee = ((_amount).mul(fee)).div(1e4);
uint256 _actualTransfer = _amtAvail.sub(_fee);
uint256 _feeDev = (_fee).mul(10000 - rewardPer).div(1e4); // Remaining tokens for reward mining
fundsClaimedSoFar[_pid][address(_tokenAddress)] = fundsClaimedSoFar[_pid][address(_tokenAddress)].add(_amount);
_tokenAddress.safeTransfer(_msgSender(), _actualTransfer);
_tokenAddress.safeTransfer(devaddr, _feeDev);
emit Withdraw(_msgSender(), _pid, _actualTransfer);
emit Withdraw(devaddr, _pid, _feeDev);
}
// Update dev address by initiating with the previous dev.
function changeDev(address _newowner) external onlyAdmin {
potentialAdmin = _newowner;
}
function becomeDev() external {
require(potentialAdmin == msg.sender, "NA"); // NOT ALLOWED
devaddr = msg.sender;
}
// Update temp pool owner address by initiating with the previous pool owner.
function changePoolOwner(uint256 _pid, address _newowner) external {
require(_msgSender()==poolInfo[_pid].owner, "OA"); // NOT AUTHORISED USER
tempAdmin[_pid] = _newowner;
}
// Claim pool ownership with new address
function becomePoolOwner(uint256 _pid) external {
if (tempAdmin[_pid] == _msgSender()) poolInfo[_pid].owner = _msgSender();
}
// Update fee, can never be more than 3%.
function changeFee(uint256 _fee) external onlyAdmin{
require(_fee <= 300, "MAX3"); // MAX FEE POSSIBLE
fee = _fee;
}
// To generate a new invite code
function generateNewCode(address _token, address _poolOwner) external onlyAdminOrTimeLock returns (uint256) {
uint256 inviteCode = block.number;
inviteCodeList[inviteCode][_token][_poolOwner] = true;
return inviteCode;
}
// To invalidate an invite code
function invalidateOldCode(uint256 _inviteCode, address _token, address _poolOwner) external onlyAdmin {
inviteCodeList[_inviteCode][_token][_poolOwner] = false;
}
// To add or update a staking pool with weight
function addStakingPool(address _token, uint256 _weight) external onlyAdmin {
if(stakingEnabled[_token]==false){
stakingPools.push(_token);
stakingEnabled[_token] = true;
}
totalStakeWeight = totalStakeWeight.sub(stakingWeight[_token]).add(_weight);
stakingWeight[_token] = _weight;
}
} | Claim pool ownership with new address | function becomePoolOwner(uint256 _pid) external {
if (tempAdmin[_pid] == _msgSender()) poolInfo[_pid].owner = _msgSender();
}
| 15,113,622 |
./partial_match/1/0x0ad87b4977C14bbE78Ca7A47BAFbB262eaBd8638/sources/StrategyLPMasterChef.sol | pending function changes names often (e.g. pendingYEL, pendingReward). This is only called in the tests, so no need to include it in the contract's interface function pendingCake(uint256 _pid, address _user) external view returns (uint256); | interface IMasterChef {
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function enterStaking(uint256 _amount) external;
function leaveStaking(uint256 _amount) external;
function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256);
function emergencyWithdraw(uint256 _pid) external;
}
| 4,049,628 |
pragma solidity 0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract YUPTimelock is Ownable {
using SafeERC20 for StandardToken;
using SafeMath for uint256;
/** Contract events **/
event IsLocked(uint256 _time);
event IsClaiming(uint256 _time);
event IsFinalized(uint256 _time);
event Claimed(address indexed _to, uint256 _value);
event ClaimedFutureUse(address indexed _to, uint256 _value);
/** State variables **/
enum ContractState { Locked, Claiming, Finalized }
ContractState public state;
uint256 constant D160 = 0x0010000000000000000000000000000000000000000;
StandardToken public token;
mapping(address => uint256) public allocations;
mapping(address => bool) public claimed; //indicates whether beneficiary has claimed tokens
uint256 public expectedAmount = 193991920 * (10**18); //should hold 193,991,920 x 10^18 (43.59% of total supply)
uint256 public amountLocked;
uint256 public amountClaimed;
uint256 public releaseTime; //investor claim starting time
uint256 public claimEndTime; //investor claim expiration time
uint256 public fUseAmount; //amount of tokens for future use
address fUseBeneficiary; //address of future use tokens beneficiary
uint256 fUseReleaseTime; //release time of locked future use tokens
/** Modifiers **/
modifier isLocked() {
require(state == ContractState.Locked);
_;
}
modifier isClaiming() {
require(state == ContractState.Claiming);
_;
}
modifier isFinalized() {
require(state == ContractState.Finalized);
_;
}
/** Constructor **/
function YUPTimelock(
uint256 _releaseTime,
uint256 _amountLocked,
address _fUseBeneficiary,
uint256 _fUseReleaseTime
) public {
require(_releaseTime > now);
releaseTime = _releaseTime;
amountLocked = _amountLocked;
fUseAmount = 84550000 * 10**18; //84,550,000 tokens (with 18 decimals)
claimEndTime = now + 60*60*24*275; //9 months (in seconds) from time of lock
fUseBeneficiary = _fUseBeneficiary;
fUseReleaseTime = _fUseReleaseTime;
if (amountLocked != expectedAmount)
revert();
}
/** Allows the owner to set the token contract address **/
function setTokenAddr(StandardToken tokAddr) public onlyOwner {
require(token == address(0x0)); //initialize only once
token = tokAddr;
state = ContractState.Locked; //switch contract to locked state
IsLocked(now);
}
/** Retrieves individual investor token balance **/
function getUserBalance(address _owner) public view returns (uint256) {
if (claimed[_owner] == false && allocations[_owner] > 0)
return allocations[_owner];
else
return 0;
}
/** Allows owner to initiate the claiming phase **/
function startClaim() public isLocked onlyOwner {
state = ContractState.Claiming;
IsClaiming(now);
}
/** Allows owner to finalize contract (only after investor claimEnd time) **/
function finalize() public isClaiming onlyOwner {
require(now >= claimEndTime);
state = ContractState.Finalized;
IsFinalized(now);
}
/** Allows the owner to claim all unclaimed investor tokens **/
function ownerClaim() public isFinalized onlyOwner {
uint256 remaining = token.balanceOf(this);
amountClaimed = amountClaimed.add(remaining);
amountLocked = amountLocked.sub(remaining);
token.safeTransfer(owner, remaining);
Claimed(owner, remaining);
}
/** Facilitates the assignment of investor addresses and amounts (only before claiming phase starts) **/
function loadBalances(uint256[] data) public isLocked onlyOwner {
require(token != address(0x0)); //Fail if token is not set
for (uint256 i = 0; i < data.length; i++) {
address addr = address(data[i] & (D160 - 1));
uint256 amount = data[i] / D160;
allocations[addr] = amount;
claimed[addr] = false;
}
}
/** Allows owner to claim future use tokens in favor of fUseBeneficiary account **/
function claimFutureUse() public onlyOwner {
require(now >= fUseReleaseTime);
amountClaimed = amountClaimed.add(fUseAmount);
amountLocked = amountLocked.sub(fUseAmount);
token.safeTransfer(fUseBeneficiary, fUseAmount);
ClaimedFutureUse(fUseBeneficiary, fUseAmount);
}
/** Allows presale investors to claim tokens **/
function claim() external isClaiming {
require(token != address(0x0)); //Fail if token is not set
require(now >= releaseTime);
require(allocations[msg.sender] > 0);
uint256 amount = allocations[msg.sender];
allocations[msg.sender] = 0;
claimed[msg.sender] = true;
amountClaimed = amountClaimed.add(amount);
amountLocked = amountLocked.sub(amount);
token.safeTransfer(msg.sender, amount);
Claimed(msg.sender, amount);
}
} | Allows the owner to claim all unclaimed investor tokens / | function ownerClaim() public isFinalized onlyOwner {
uint256 remaining = token.balanceOf(this);
amountClaimed = amountClaimed.add(remaining);
amountLocked = amountLocked.sub(remaining);
token.safeTransfer(owner, remaining);
Claimed(owner, remaining);
}
| 6,870,127 |
/**
*Submitted for verification at Etherscan.io on 2019-08-12
*/
// File: contracts/IRelayHub.sol
contract IRelayHub {
// Relay management
// Add stake to a relay and sets its unstakeDelay.
// If the relay does not exist, it is created, and the caller
// of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
// cannot be its own owner.
// All Ether in this function call will be added to the relay's stake.
// Its unstake delay will be assigned to unstakeDelay, but the new value must be greater or equal to the current one.
// Emits a Staked event.
function stake(address relayaddr, uint256 unstakeDelay) external payable;
// Emited when a relay's stake or unstakeDelay are increased
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
// Registers the caller as a relay.
// The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
// Emits a RelayAdded event.
// This function can be called multiple times, emitting new RelayAdded events. Note that the received transactionFee
// is not enforced by relayCall.
function registerRelay(uint256 transactionFee, string memory url) public;
// Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out RelayRemoved
// events) lets a client discover the list of available relays.
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
// Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed. Can only be called by
// the owner of the relay. After the relay's unstakeDelay has elapsed, unstake will be callable.
// Emits a RelayRemoved event.
function removeRelayByOwner(address relay) public;
// Emitted when a relay is removed (deregistered). unstakeTime is the time when unstake will be callable.
event RelayRemoved(address indexed relay, uint256 unstakeTime);
// Deletes the relay from the system, and gives back its stake to the owner. Can only be called by the relay owner,
// after unstakeDelay has elapsed since removeRelayByOwner was called.
// Emits an Unstaked event.
function unstake(address relay) public;
// Emitted when a relay is unstaked for, including the returned stake.
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
// Returns a relay's status. Note that relays can be deleted when unstaked or penalized.
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
// Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only
// be withdrawn by the contract itself, by callingn withdraw.
// Emits a Deposited event.
function depositFor(address target) public payable;
// Emitted when depositFor is called, including the amount and account that was funded.
event Deposited(address indexed recipient, address indexed from, uint256 amount);
// Returns an account's deposits. These can be either a contnract's funds, or a relay owner's revenue.
function balanceOf(address target) external view returns (uint256);
// Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
// contracts can also use it to reduce their funding.
// Emits a Withdrawn event.
function withdraw(uint256 amount, address payable dest) public;
// Emitted when an account withdraws funds from RelayHub.
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
// Check if the RelayHub will accept a relayed operation. Multiple things must be true for this to happen:
// - all arguments must be signed for by the sender (from)
// - the sender's nonce must be the current one
// - the recipient must accept this transaction (via acceptRelayedCall)
// Returns a PreconditionCheck value (OK when the transaction can be relayed), or a recipient-specific error code if
// it returns one in acceptRelayedCall.
function canRelay(
address relay,
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
) public view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
// Relays a transaction. For this to suceed, multiple conditions must be met:
// - canRelay must return PreconditionCheck.OK
// - the sender must be a registered relay
// - the transaction's gas price must be larger or equal to the one that was requested by the sender
// - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
// recipient) use all gas available to them
// - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
// spent)
//
// If all conditions are met, the call will be relayed and the recipient charged. preRelayedCall, the encoded
// function and postRelayedCall will be called in order.
//
// Arguments:
// - from: the client originating the request
// - recipient: the target IRelayRecipient contract
// - encodedFunction: the function call to relay, including data
// - transactionFee: fee (%) the relay takes over actual gas cost
// - gasPrice: gas price the client is willing to pay
// - gasLimit: gas to forward when calling the encoded function
// - nonce: client's nonce
// - signature: client's signature over all previous params, plus the relay and RelayHub addresses
// - approvalData: dapp-specific data forwared to acceptRelayedCall. This value is *not* verified by the Hub, but
// it still can be used for e.g. a signature.
//
// Emits a TransactionRelayed event.
function relayCall(
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
) public;
// Emitted when an attempt to relay a call failed. This can happen due to incorrect relayCall arguments, or the
// recipient not accepting the relayed call. The actual relayed call was not executed, and the recipient not charged.
// The reason field contains an error code: values 1-10 correspond to PreconditionCheck entries, and values over 10
// are custom recipient error codes returned from acceptRelayedCall.
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
// Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be
// indicated in the status field.
// Useful when monitoring a relay's operation and relayed calls to a contract.
// Charge is the ether value deducted from the recipient's balance, paid to the relay's owner.
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
// Returns how much gas should be forwarded to a call to relayCall, in order to relay a transaction that will spend
// up to relayedCallStipend gas.
function requiredGas(uint256 relayedCallStipend) public view returns (uint256);
// Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256);
// Relay penalization. Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
// Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
// different data (gas price, gas limit, etc. may be different). The (unsigned) transaction data and signature for
// both transactions must be provided.
function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public;
// Penalize a relay that sent a transaction that didn't target RelayHub's registerRelay or relayCall.
function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public;
event Penalized(address indexed relay, address sender, uint256 amount);
function getNonce(address from) view external returns (uint256);
}
// File: contracts/IRelayRecipient.sol
contract IRelayRecipient {
/**
* return the relayHub of this contract.
*/
function getHubAddr() public view returns (address);
/**
* return the contract's balance on the RelayHub.
* can be used to determine if the contract can pay for incoming calls,
* before making any.
*/
function getRecipientBalance() public view returns (uint);
/*
* Called by Relay (and RelayHub), to validate if this recipient accepts this call.
* Note: Accepting this call means paying for the tx whether the relayed call reverted or not.
*
* @return "0" if the the contract is willing to accept the charges from this sender, for this function call.
* any other value is a failure. actual value is for diagnostics only.
* ** Note: values below 10 are reserved by canRelay
* @param relay the relay that attempts to relay this function call.
* the contract may restrict some encoded functions to specific known relays.
* @param from the sender (signer) of this function call.
* @param encodedFunction the encoded function call (without any ethereum signature).
* the contract may check the method-id for valid methods
* @param gasPrice - the gas price for this transaction
* @param transactionFee - the relay compensation (in %) for this transaction
* @param signature - sender's signature over all parameters except approvalData
* @param approvalData - extra dapp-specific data (e.g. signature from trusted party)
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256 maxPossibleCharge
)
external
view
returns (uint256, bytes memory);
/*
* modifier to be used by recipients as access control protection for preRelayedCall & postRelayedCall
*/
modifier relayHubOnly() {
require(msg.sender == getHubAddr(),"Function can only be called by RelayHub");
_;
}
/** this method is called before the actual relayed function call.
* It may be used to charge the caller before (in conjuction with refunding him later in postRelayedCall for example).
* the method is given all parameters of acceptRelayedCall and actual used gas.
*
*
*** NOTICE: if this method modifies the contract's state, it must be protected with access control i.e. require msg.sender == getHubAddr()
*
*
* Revert in this functions causes a revert of the client's relayed call but not in the entire transaction
* (that is, the relay will still get compensated)
*/
function preRelayedCall(bytes calldata context) external returns (bytes32);
/** this method is called after the actual relayed function call.
* It may be used to record the transaction (e.g. charge the caller by some contract logic) for this call.
* the method is given all parameters of acceptRelayedCall, and also the success/failure status and actual used gas.
*
*
*** NOTICE: if this method modifies the contract's state, it must be protected with access control i.e. require msg.sender == getHubAddr()
*
*
* @param success - true if the relayed call succeeded, false if it reverted
* @param actualCharge - estimation of how much the recipient will be charged. This information may be used to perform local booking and
* charge the sender for this call (e.g. in tokens).
* @param preRetVal - preRelayedCall() return value passed back to the recipient
*
* Revert in this functions causes a revert of the client's relayed call but not in the entire transaction
* (that is, the relay will still get compensated)
*/
function postRelayedCall(bytes calldata context, bool success, uint actualCharge, bytes32 preRetVal) external;
}
// File: @0x/contracts-utils/contracts/src/LibBytes.sol
/*
Copyright 2018 ZeroEx Intl.
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.
*/
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
require(
from <= to,
"FROM_LESS_THAN_TO_REQUIRED"
);
require(
to <= b.length,
"TO_LESS_THAN_LENGTH_REQUIRED"
);
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
require(
from <= to,
"FROM_LESS_THAN_TO_REQUIRED"
);
require(
to <= b.length,
"TO_LESS_THAN_LENGTH_REQUIRED"
);
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
require(
b.length > 0,
"GREATER_THAN_ZERO_LENGTH_REQUIRED"
);
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Pops the last 20 bytes off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The 20 byte address that was popped off.
function popLast20Bytes(bytes memory b)
internal
pure
returns (address result)
{
require(
b.length >= 20,
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Store last 20 bytes.
result = readAddress(b, b.length - 20);
assembly {
// Subtract 20 from byte array length.
let newLen := sub(mload(b), 20)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
require(
b.length >= index + 4,
"GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Reads nested bytes from a specific position.
/// @dev NOTE: the returned value overlaps with the input value.
/// Both should be treated as immutable.
/// @param b Byte array containing nested bytes.
/// @param index Index of nested bytes.
/// @return result Nested bytes.
function readBytesWithLength(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes memory result)
{
// Read length of nested bytes
uint256 nestedBytesLength = readUint256(b, index);
index += 32;
// Assert length of <b> is valid, given
// length of nested bytes
require(
b.length >= index + nestedBytesLength,
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Return a pointer to the byte array as it exists inside `b`
assembly {
result := add(b, index)
}
return result;
}
/// @dev Inserts bytes at a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes to insert.
function writeBytesWithLength(
bytes memory b,
uint256 index,
bytes memory input
)
internal
pure
{
// Assert length of <b> is valid, given
// length of input
require(
b.length >= index + 32 + input.length, // 32 bytes to store length
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Copy <input> into <b>
memCopy(
b.contentAddress() + index,
input.rawAddress(), // includes length of <input>
input.length + 32 // +32 bytes to store <input> length
);
}
/// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length.
/// @param dest Byte array that will be overwritten with source bytes.
/// @param source Byte array to copy onto dest bytes.
function deepCopyBytes(
bytes memory dest,
bytes memory source
)
internal
pure
{
uint256 sourceLen = source.length;
// Dest length must be >= source length, or some bytes would not be copied.
require(
dest.length >= sourceLen,
"GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"
);
memCopy(
dest.contentAddress(),
source.contentAddress(),
sourceLen
);
}
}
// File: contracts/GsnUtils.sol
library GsnUtils {
/**
* extract method sig from encoded function call
*/
function getMethodSig(bytes memory msgData) internal pure returns (bytes4) {
return bytes4(bytes32(LibBytes.readUint256(msgData, 0)));
}
/**
* extract parameter from encoded-function block.
* see: https://solidity.readthedocs.io/en/develop/abi-spec.html#formal-specification-of-the-encoding
* note that the type of the parameter must be static.
* the return value should be casted to the right type.
*/
function getParam(bytes memory msgData, uint index) internal pure returns (uint) {
return LibBytes.readUint256(msgData, 4 + index * 32);
}
/**
* extract dynamic-sized (string/bytes) parameter.
* we assume that there ARE dynamic parameters, hence getParam(0) is the offset to the first
* dynamic param
* https://solidity.readthedocs.io/en/develop/abi-spec.html#use-of-dynamic-types
*/
function getBytesParam(bytes memory msgData, uint index) internal pure returns (bytes memory ret) {
uint ofs = getParam(msgData,index)+4;
uint len = LibBytes.readUint256(msgData, ofs);
ret = LibBytes.slice(msgData, ofs+32, ofs+32+len);
}
function getStringParam(bytes memory msgData, uint index) internal pure returns (string memory) {
return string(getBytesParam(msgData,index));
}
function checkSig(address signer, bytes32 hash, bytes memory sig) pure internal returns (bool) {
// Check if @v,@r,@s are a valid signature of @signer for @hash
uint8 v = uint8(sig[0]);
bytes32 r = LibBytes.readBytes32(sig,1);
bytes32 s = LibBytes.readBytes32(sig,33);
return signer == ecrecover(hash, v, r, s);
}
}
// File: contracts/RLPReader.sol
/*
* Taken from https://github.com/hamdiallam/Solidity-RLP
*/
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
using RLPReader for bytes;
using RLPReader for uint;
using RLPReader for RLPReader.RLPItem;
// helper function to decode rlp encoded ethereum transaction
/*
* @param rawTransaction RLP encoded ethereum transaction
* @return tuple (nonce,gasPrice,gasLimit,to,value,data)
*/
function decodeTransaction(bytes memory rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){
RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first!
return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes());
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
if (item.length == 0)
return RLPItem(0, 0);
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) {
require(isList(item), "isList failed");
uint items = numItems(item);
result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
}
/*
* Helpers
*/
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) internal pure returns (uint) {
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr);
// skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) internal pure returns (uint len) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 1;
else if (byte0 < STRING_LONG_START)
return byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
len := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
return byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
len := add(dataLen, add(byteLen, 1))
}
}
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) internal pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte");
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix according to RLP spec
require(item.len <= 21, "Invalid RLPItem. Addresses are encoded in 20 bytes or less");
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint memPtr = item.memPtr + offset;
uint result;
assembly {
result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
// data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) internal pure {
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev 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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @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.
*
* (.note) This call _does not revert_ if the signature is invalid, or
* if the signer is otherwise unable to be retrieved. In those scenarios,
* the zero address is returned.
*
* (.warning) `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) {
return (address(0));
}
// 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) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* [`eth_sign`](https://github.com/ethereum/wiki/wiki/JSON-RPC#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));
}
}
// File: contracts/RelayHub.sol
contract RelayHub is IRelayHub {
string constant commitId = "$Id: 5a82a94cecb1c32344dd239889272d1845035ef0 $";
using ECDSA for bytes32;
// Minimum stake a relay can have. An attack to the network will never cost less than half this value.
uint256 constant private minimumStake = 1 ether;
// Minimum unstake delay. A relay needs to wait for this time to elapse after deregistering to retrieve its stake.
uint256 constant private minimumUnstakeDelay = 1 weeks;
// Maximum unstake delay. Prevents relays from locking their funds into the RelayHub for too long.
uint256 constant private maximumUnstakeDelay = 12 weeks;
// Minimum balance required for a relay to register or re-register. Prevents user error in registering a relay that
// will not be able to immediatly start serving requests.
uint256 constant private minimumRelayBalance = 0.1 ether;
// Maximum funds that can be deposited at once. Prevents user error by disallowing large deposits.
uint256 constant private maximumRecipientDeposit = 2 ether;
/**
* the total gas overhead of relayCall(), before the first gasleft() and after the last gasleft().
* Assume that relay has non-zero balance (costs 15'000 more otherwise).
*/
// Gas cost of all relayCall() instructions before first gasleft() and after last gasleft()
uint256 constant private gasOverhead = 48204;
// Gas cost of all relayCall() instructions after first gasleft() and before last gasleft()
uint256 constant private gasReserve = 100000;
// Approximation of how much calling recipientCallsAtomic costs
uint256 constant private recipientCallsAtomicOverhead = 5000;
// Gas stipends for acceptRelayedCall, preRelayedCall and postRelayedCall
uint256 constant private acceptRelayedCallMaxGas = 50000;
uint256 constant private preRelayedCallMaxGas = 100000;
uint256 constant private postRelayedCallMaxGas = 100000;
// Nonces of senders, used to prevent replay attacks
mapping(address => uint256) private nonces;
enum AtomicRecipientCallsStatus {OK, CanRelayFailed, RelayedCallFailed, PreRelayedFailed, PostRelayedFailed}
struct Relay {
uint256 stake; // Ether staked for this relay
uint256 unstakeDelay; // Time that must elapse before the owner can retrieve the stake after calling remove
uint256 unstakeTime; // Time when unstake will be callable. A value of zero indicates the relay has not been removed.
address payable owner; // Relay's owner, will receive revenue and manage it (call stake, remove and unstake).
RelayState state;
}
mapping(address => Relay) private relays;
mapping(address => uint256) private balances;
string public version = "1.0.0";
function stake(address relay, uint256 unstakeDelay) external payable {
if (relays[relay].state == RelayState.Unknown) {
require(msg.sender != relay, "relay cannot stake for itself");
relays[relay].owner = msg.sender;
relays[relay].state = RelayState.Staked;
} else if ((relays[relay].state == RelayState.Staked) || (relays[relay].state == RelayState.Registered)) {
require(relays[relay].owner == msg.sender, "not owner");
} else {
revert('wrong state for stake');
}
// Increase the stake
uint256 addedStake = msg.value;
relays[relay].stake += addedStake;
// The added stake may be e.g. zero when only the unstake delay is being updated
require(relays[relay].stake >= minimumStake, "stake lower than minimum");
// Increase the unstake delay
require(unstakeDelay >= minimumUnstakeDelay, "delay lower than minimum");
require(unstakeDelay <= maximumUnstakeDelay, "delay higher than maximum");
require(unstakeDelay >= relays[relay].unstakeDelay, "unstakeDelay cannot be decreased");
relays[relay].unstakeDelay = unstakeDelay;
emit Staked(relay, relays[relay].stake, relays[relay].unstakeDelay);
}
function registerRelay(uint256 transactionFee, string memory url) public {
address relay = msg.sender;
require(relay == tx.origin, "Contracts cannot register as relays");
require(relays[relay].state == RelayState.Staked || relays[relay].state == RelayState.Registered, "wrong state for stake");
require(relay.balance >= minimumRelayBalance, "balance lower than minimum");
if (relays[relay].state != RelayState.Registered) {
relays[relay].state = RelayState.Registered;
}
emit RelayAdded(relay, relays[relay].owner, transactionFee, relays[relay].stake, relays[relay].unstakeDelay, url);
}
function removeRelayByOwner(address relay) public {
require(relays[relay].owner == msg.sender, "not owner");
require((relays[relay].state == RelayState.Staked) || (relays[relay].state == RelayState.Registered), "already removed");
// Start the unstake counter
relays[relay].unstakeTime = relays[relay].unstakeDelay + now;
relays[relay].state = RelayState.Removed;
emit RelayRemoved(relay, relays[relay].unstakeTime);
}
function unstake(address relay) public {
require(canUnstake(relay), "canUnstake failed");
require(relays[relay].owner == msg.sender, "not owner");
address payable owner = msg.sender;
uint256 amount = relays[relay].stake;
delete relays[relay];
owner.transfer(amount);
emit Unstaked(relay, amount);
}
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state) {
totalStake = relays[relay].stake;
unstakeDelay = relays[relay].unstakeDelay;
unstakeTime = relays[relay].unstakeTime;
owner = relays[relay].owner;
state = relays[relay].state;
}
/**
* deposit ether for a contract.
* This ether will be used to repay relay calls into this contract.
* Contract owner should monitor the balance of his contract, and make sure
* to deposit more, otherwise the contract won't be able to receive relayed calls.
* Unused deposited can be withdrawn with `withdraw()`
*/
function depositFor(address target) public payable {
uint256 amount = msg.value;
require(amount <= maximumRecipientDeposit, "deposit too big");
balances[target] = SafeMath.add(balances[target], amount);
emit Deposited(target, msg.sender, amount);
}
//check the deposit balance of a contract.
function balanceOf(address target) external view returns (uint256) {
return balances[target];
}
/**
* withdraw funds.
* caller is either a relay owner, withdrawing collected transaction fees.
* or a IRelayRecipient contract, withdrawing its deposit.
* note that while everyone can `depositFor()` a contract, only
* the contract itself can withdraw its funds.
*/
function withdraw(uint256 amount, address payable dest) public {
address payable account = msg.sender;
require(balances[account] >= amount, "insufficient funds");
balances[account] -= amount;
dest.transfer(amount);
emit Withdrawn(account, dest, amount);
}
function getNonce(address from) view external returns (uint256) {
return nonces[from];
}
function canUnstake(address relay) public view returns (bool) {
return relays[relay].unstakeTime > 0 && relays[relay].unstakeTime <= now;
// Finished the unstaking delay period?
}
function canRelay(
address relay,
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
)
public view returns (uint256 status, bytes memory recipientContext)
{
// Verify the sender's signature on the transaction - note that approvalData is *not* signed
{
bytes memory packed = abi.encodePacked("rlx:", from, to, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, address(this));
bytes32 hashedMessage = keccak256(abi.encodePacked(packed, relay));
if (hashedMessage.toEthSignedMessageHash().recover(signature) != from) {
return (uint256(PreconditionCheck.WrongSignature), "");
}
}
// Verify the transaction is not being replayed
if (nonces[from] != nonce) {
return (uint256(PreconditionCheck.WrongNonce), "");
}
uint256 maxCharge = maxPossibleCharge(gasLimit, gasPrice, transactionFee);
bytes memory encodedTx = abi.encodeWithSelector(IRelayRecipient(to).acceptRelayedCall.selector,
relay, from, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, approvalData, maxCharge
);
// (bool success, bytes memory returndata) = to.staticcall.gas(acceptRelayedCallMaxGas)(encodedTx);
bool success;
bytes memory returndata;
if (!success) {
return (uint256(PreconditionCheck.AcceptRelayedCallReverted), "");
} else {
(status, recipientContext) = abi.decode(returndata, (uint256, bytes));
// This can be either PreconditionCheck.OK or a custom error code
if ((status == 0) || (status > 10)) {
return (status, recipientContext);
} else {
// Error codes [1-10] are reserved to RelayHub
return (uint256(PreconditionCheck.InvalidRecipientStatusCode), "");
}
}
}
/**
* @notice Relay a transaction.
*
* @param from the client originating the request.
* @param recipient the target IRelayRecipient contract.
* @param encodedFunction the function call to relay.
* @param transactionFee fee (%) the relay takes over actual gas cost.
* @param gasPrice gas price the client is willing to pay
* @param gasLimit limit the client want to put on its transaction
* @param transactionFee fee (%) the relay takes over actual gas cost.
* @param nonce sender's nonce (in nonces[])
* @param signature client's signature over all params except approvalData
* @param approvalData dapp-specific data
*/
function relayCall(
address from,
address recipient,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
)
public
{
uint256 initialGas = gasleft();
// Initial soundness checks - the relay must make sure these pass, or it will pay for a reverted transaction.
// The relay must be registered
require(relays[msg.sender].state == RelayState.Registered, "Unknown relay");
// A relay may use a higher gas price than the one requested by the signer (to e.g. get the transaction in a
// block faster), but it must not be lower. The recipient will be charged for the requested gas price, not the
// one used in the transaction.
require(gasPrice <= tx.gasprice, "Invalid gas price");
// This transaction must have enough gas to forward the call to the recipient with the requested amount, and not
// run out of gas later in this function.
require(initialGas >= SafeMath.sub(requiredGas(gasLimit), gasOverhead), "Not enough gasleft()");
// We don't yet know how much gas will be used by the recipient, so we make sure there are enough funds to pay
// for the maximum possible charge.
require(maxPossibleCharge(gasLimit, gasPrice, transactionFee) <= balances[recipient], "Recipient balance too low");
bytes4 functionSelector = LibBytes.readBytes4(encodedFunction, 0);
bytes memory recipientContext;
{
// We now verify the legitimacy of the transaction (it must be signed by the sender, and not be replayed),
// and that the recpient will accept to be charged by it.
uint256 preconditionCheck;
(preconditionCheck, recipientContext) = canRelay(msg.sender, from, recipient, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, signature, approvalData);
if (preconditionCheck != uint256(PreconditionCheck.OK)) {
emit CanRelayFailed(msg.sender, from, recipient, functionSelector, preconditionCheck);
return;
}
}
// From this point on, this transaction will not revert nor run out of gas, and the recipient will be charged
// for the gas spent.
// The sender's nonce is advanced to prevent transaction replays.
nonces[from]++;
// Calls to the recipient are performed atomically inside an inner transaction which may revert in case of
// errors in the recipient. In either case (revert or regular execution) the return data encodes the
// RelayCallStatus value.
RelayCallStatus status;
{
uint256 preChecksGas = initialGas - gasleft();
bytes memory encodedFunctionWithFrom = abi.encodePacked(encodedFunction, from);
bytes memory data = abi.encodeWithSelector(this.recipientCallsAtomic.selector, recipient, encodedFunctionWithFrom, transactionFee, gasPrice, gasLimit, preChecksGas, recipientContext);
(, bytes memory relayCallStatus) = address(this).call(data);
status = abi.decode(relayCallStatus, (RelayCallStatus));
}
// We now perform the actual charge calculation, based on the measured gas used
uint256 charge = calculateCharge(
getChargeableGas(initialGas - gasleft(), false),
gasPrice,
transactionFee
);
// We've already checked that the recipient has enough balance to pay for the relayed transaction, this is only
// a sanity check to prevent overflows in case of bugs.
require(balances[recipient] >= charge, "Should not get here");
balances[recipient] -= charge;
balances[relays[msg.sender].owner] += charge;
emit TransactionRelayed(msg.sender, from, recipient, functionSelector, status, charge);
}
struct AtomicData {
uint256 atomicInitialGas;
uint256 balanceBefore;
bytes32 preReturnValue;
bool relayedCallSuccess;
}
function recipientCallsAtomic(
address recipient,
bytes calldata encodedFunctionWithFrom,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 preChecksGas,
bytes calldata recipientContext
)
external
returns (RelayCallStatus)
{
AtomicData memory atomicData;
atomicData.atomicInitialGas = gasleft(); // A new gas measurement is performed inside recipientCallsAtomic, since
// due to EIP150 available gas amounts cannot be directly compared across external calls
// This external function can only be called by RelayHub itself, creating an internal transaction. Calls to the
// recipient (preRelayedCall, the relayedCall, and postRelayedCall) are called from inside this transaction.
require(msg.sender == address(this), "Only RelayHub should call this function");
// If either pre or post reverts, the whole internal transaction will be reverted, reverting all side effects on
// the recipient. The recipient will still be charged for the used gas by the relay.
// The recipient is no allowed to withdraw balance from RelayHub during a relayed transaction. We check pre and
// post state to ensure this doesn't happen.
atomicData.balanceBefore = balances[recipient];
// First preRelayedCall is executed.
{
// Note: we open a new block to avoid growing the stack too much.
bytes memory data = abi.encodeWithSelector(
IRelayRecipient(recipient).preRelayedCall.selector, recipientContext
);
// preRelayedCall may revert, but the recipient will still be charged: it should ensure in
// acceptRelayedCall that this will not happen.
(bool success, bytes memory retData) = recipient.call.gas(preRelayedCallMaxGas)(data);
if (!success) {
revertWithStatus(RelayCallStatus.PreRelayedFailed);
}
atomicData.preReturnValue = abi.decode(retData, (bytes32));
}
// The actual relayed call is now executed. The sender's address is appended at the end of the transaction data
(atomicData.relayedCallSuccess,) = recipient.call.gas(gasLimit)(encodedFunctionWithFrom);
// Finally, postRelayedCall is executed, with the relayedCall execution's status and a charge estimate
{
bytes memory data;
{
// We now determine how much the recipient will be charged, to pass this value to postRelayedCall for accurate
// accounting.
uint256 estimatedCharge = calculateCharge(
getChargeableGas(preChecksGas + atomicData.atomicInitialGas - gasleft(), true), // postRelayedCall is included in the charge
gasPrice,
transactionFee
);
data = abi.encodeWithSelector(
IRelayRecipient(recipient).postRelayedCall.selector,
recipientContext, atomicData.relayedCallSuccess, estimatedCharge, atomicData.preReturnValue
);
}
(bool successPost,) = recipient.call.gas(postRelayedCallMaxGas)(data);
if (!successPost) {
revertWithStatus(RelayCallStatus.PostRelayedFailed);
}
}
if (balances[recipient] < atomicData.balanceBefore) {
revertWithStatus(RelayCallStatus.RecipientBalanceChanged);
}
return atomicData.relayedCallSuccess ? RelayCallStatus.OK : RelayCallStatus.RelayedCallFailed;
}
/**
* @dev Reverts the transaction with returndata set to the ABI encoding of the status argument.
*/
function revertWithStatus(RelayCallStatus status) private pure {
bytes memory data = abi.encode(status);
assembly {
let dataSize := mload(data)
let dataPtr := add(data, 32)
revert(dataPtr, dataSize)
}
}
function requiredGas(uint256 relayedCallStipend) public view returns (uint256) {
return gasOverhead + gasReserve + acceptRelayedCallMaxGas + preRelayedCallMaxGas + postRelayedCallMaxGas + relayedCallStipend;
}
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256) {
return calculateCharge(requiredGas(relayedCallStipend), gasPrice, transactionFee);
}
function calculateCharge(uint256 gas, uint256 gasPrice, uint256 fee) private pure returns (uint256) {
// The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be
// charged for 1.4 times the spent amount.
return (gas * gasPrice * (100 + fee)) / 100;
}
function getChargeableGas(uint256 gasUsed, bool postRelayedCallEstimation) private pure returns (uint256) {
return gasOverhead + gasUsed + (postRelayedCallEstimation ? (postRelayedCallMaxGas + recipientCallsAtomicOverhead) : 0);
}
struct Transaction {
uint256 nonce;
uint256 gasPrice;
uint256 gasLimit;
address to;
uint256 value;
bytes data;
}
function decodeTransaction(bytes memory rawTransaction) private pure returns (Transaction memory transaction) {
(transaction.nonce, transaction.gasPrice, transaction.gasLimit, transaction.to, transaction.value, transaction.data) = RLPReader.decodeTransaction(rawTransaction);
return transaction;
}
function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public {
// Can be called by anyone.
// If a relay attacked the system by signing multiple transactions with the same nonce (so only one is accepted), anyone can grab both transactions from the blockchain and submit them here.
// Check whether unsignedTx1 != unsignedTx2, that both are signed by the same address, and that unsignedTx1.nonce == unsignedTx2.nonce. If all conditions are met, relay is considered an "offending relay".
// The offending relay will be unregistered immediately, its stake will be forfeited and given to the address who reported it (msg.sender), thus incentivizing anyone to report offending relays.
// If reported via a relay, the forfeited stake is split between msg.sender (the relay used for reporting) and the address that reported it.
address addr1 = keccak256(abi.encodePacked(unsignedTx1)).recover(signature1);
address addr2 = keccak256(abi.encodePacked(unsignedTx2)).recover(signature2);
require(addr1 == addr2, "Different signer");
Transaction memory decodedTx1 = decodeTransaction(unsignedTx1);
Transaction memory decodedTx2 = decodeTransaction(unsignedTx2);
//checking that the same nonce is used in both transaction, with both signed by the same address and the actual data is different
// note: we compare the hash of the tx to save gas over iterating both byte arrays
require(decodedTx1.nonce == decodedTx2.nonce, "Different nonce");
bytes memory dataToCheck1 = abi.encodePacked(decodedTx1.data, decodedTx1.gasLimit, decodedTx1.to, decodedTx1.value);
bytes memory dataToCheck2 = abi.encodePacked(decodedTx2.data, decodedTx2.gasLimit, decodedTx2.to, decodedTx2.value);
require(keccak256(dataToCheck1) != keccak256(dataToCheck2), "tx is equal");
penalize(addr1);
}
function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public {
Transaction memory decodedTx = decodeTransaction(unsignedTx);
if (decodedTx.to == address(this)) {
bytes4 selector = GsnUtils.getMethodSig(decodedTx.data);
// Note: If RelayHub's relay API is extended, the selectors must be added to the ones listed here
require(selector != this.relayCall.selector && selector != this.registerRelay.selector, "Legal relay transaction");
}
address relay = keccak256(abi.encodePacked(unsignedTx)).recover(signature);
penalize(relay);
}
function penalize(address relay) private {
require((relays[relay].state == RelayState.Staked) ||
(relays[relay].state == RelayState.Registered) ||
(relays[relay].state == RelayState.Removed), "Unstaked relay");
// Half of the stake will be burned (sent to address 0)
uint256 totalStake = relays[relay].stake;
uint256 toBurn = SafeMath.div(totalStake, 2);
uint256 reward = SafeMath.sub(totalStake, toBurn);
if (relays[relay].state == RelayState.Registered) {
emit RelayRemoved(relay, now);
}
// The relay is deleted
delete relays[relay];
// Ether is burned and transferred
address(0).transfer(toBurn);
address payable reporter = msg.sender;
reporter.transfer(reward);
emit Penalized(relay, reporter, reward);
}
}
| withdraw funds. caller is either a relay owner, withdrawing collected transaction fees. or a IRelayRecipient contract, withdrawing its deposit. note that while everyone can `depositFor()` a contract, only the contract itself can withdraw its funds./ | function withdraw(uint256 amount, address payable dest) public {
address payable account = msg.sender;
require(balances[account] >= amount, "insufficient funds");
balances[account] -= amount;
dest.transfer(amount);
emit Withdrawn(account, dest, amount);
}
| 12,903,154 |
./full_match/4/0x83c6bd824A24321DebF10aD6112C9a587EB1080b/sources/HowlTest.sol | Withdraws the ether distributed to the sender. It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. | function withdrawDividend() public virtual override {
_withdrawDividendOfUser(msg.sender, msg.sender);
}
| 662,284 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/token/ERC1155/IERC1155.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/math/Math.sol';
import './Governable.sol';
import './utils/ERC1155NaiveReceiver.sol';
import '../interfaces/IBank.sol';
import '../interfaces/ICErc20.sol';
import '../interfaces/IOracle.sol';
library HomoraSafeMath {
using SafeMath for uint;
/// @dev Computes round-up division.
function ceilDiv(uint a, uint b) internal pure returns (uint) {
return a.add(b).sub(1).div(b);
}
}
contract HomoraCaster {
/// @dev Call to the target using the given data.
/// @param target The address target to call.
/// @param data The data used in the call.
function cast(address target, bytes calldata data) external payable {
(bool ok, bytes memory returndata) = target.call{value: msg.value}(data);
if (!ok) {
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('bad cast call');
}
}
}
}
contract HomoraBank is Governable, ERC1155NaiveReceiver, IBank {
using SafeMath for uint;
using HomoraSafeMath for uint;
using SafeERC20 for IERC20;
uint private constant _NOT_ENTERED = 1;
uint private constant _ENTERED = 2;
uint private constant _NO_ID = uint(-1);
address private constant _NO_ADDRESS = address(1);
struct Bank {
bool isListed; // Whether this market exists.
uint8 index; // Reverse look up index for this bank.
address cToken; // The CToken to draw liquidity from.
uint reserve; // The reserve portion allocated to Homora protocol.
uint totalDebt; // The last recorded total debt since last action.
uint totalShare; // The total debt share count across all open positions.
}
struct Position {
address owner; // The owner of this position.
address collToken; // The ERC1155 token used as collateral for this position.
uint collId; // The token id used as collateral.
uint collateralSize; // The size of collateral token for this position.
uint debtMap; // Bitmap of nonzero debt. i^th bit is set iff debt share of i^th bank is nonzero.
mapping(address => uint) debtShareOf; // The debt share for each token.
}
uint public _GENERAL_LOCK; // TEMPORARY: re-entrancy lock guard.
uint public _IN_EXEC_LOCK; // TEMPORARY: exec lock guard.
uint public override POSITION_ID; // TEMPORARY: position ID currently under execution.
address public override SPELL; // TEMPORARY: spell currently under execution.
address public caster; // The caster address for untrusted execution.
IOracle public oracle; // The oracle address for determining prices.
uint public feeBps; // The fee collected as protocol reserve in basis points from interest.
uint public override nextPositionId; // Next available position ID, starting from 1 (see initialize).
address[] public allBanks; // The list of all listed banks.
mapping(address => Bank) public banks; // Mapping from token to bank data.
mapping(address => bool) public cTokenInBank; // Mapping from cToken to its existence in bank.
mapping(uint => Position) public positions; // Mapping from position ID to position data.
bool public allowContractCalls; // The boolean status whether to allow call from contract (false = onlyEOA)
mapping(address => bool) public whitelistedTokens; // Mapping from token to whitelist status
mapping(address => bool) public whitelistedSpells; // Mapping from spell to whitelist status
mapping(address => bool) public whitelistedUsers; // Mapping from user to whitelist status
uint public bankStatus; // Each bit stores certain bank status, e.g. borrow allowed, repay allowed
address public rewardToken; // ICErc20 pool reward token;
/// @dev Ensure that the function is called from EOA when allowContractCalls is set to false and caller is not whitelisted
modifier onlyEOAEx() {
if (!allowContractCalls && !whitelistedUsers[msg.sender]) {
require(msg.sender == tx.origin, 'not eoa');
}
_;
}
/// @dev Reentrancy lock guard.
modifier lock() {
require(_GENERAL_LOCK == _NOT_ENTERED, 'general lock');
_GENERAL_LOCK = _ENTERED;
_;
_GENERAL_LOCK = _NOT_ENTERED;
}
/// @dev Ensure that the function is called from within the execution scope.
modifier inExec() {
require(POSITION_ID != _NO_ID, 'not within execution');
require(SPELL == msg.sender, 'not from spell');
require(_IN_EXEC_LOCK == _NOT_ENTERED, 'in exec lock');
_IN_EXEC_LOCK = _ENTERED;
_;
_IN_EXEC_LOCK = _NOT_ENTERED;
}
/// @dev Ensure that the interest rate of the given token is accrued.
modifier poke(address token) {
accrue(token);
_;
}
/// @dev Initialize the bank smart contract, using msg.sender as the first governor.
/// @param _oracle The oracle smart contract address.
/// @param _feeBps The fee collected to Homora bank.
function initialize(IOracle _oracle, uint _feeBps, address _rewardToken) external initializer {
__Governable__init();
_GENERAL_LOCK = _NOT_ENTERED;
_IN_EXEC_LOCK = _NOT_ENTERED;
POSITION_ID = _NO_ID;
SPELL = _NO_ADDRESS;
caster = address(new HomoraCaster());
oracle = _oracle;
require(address(_oracle) != address(0), 'bad oracle address');
feeBps = _feeBps;
nextPositionId = 1;
bankStatus = 3; // allow both borrow and repay
rewardToken = _rewardToken;
emit SetOracle(address(_oracle));
emit SetFeeBps(_feeBps);
}
/// @dev Return the current executor (the owner of the current position).
function EXECUTOR() external view override returns (address) {
uint positionId = POSITION_ID;
require(positionId != _NO_ID, 'not under execution');
return positions[positionId].owner;
}
/// @dev Set allowContractCalls
/// @param ok The status to set allowContractCalls to (false = onlyEOA)
function setAllowContractCalls(bool ok) external onlyGov {
allowContractCalls = ok;
}
/// @dev Set whitelist spell status
/// @param spells list of spells to change status
/// @param statuses list of statuses to change to
function setWhitelistSpells(address[] calldata spells, bool[] calldata statuses)
external
onlyGov
{
require(spells.length == statuses.length, 'spells & statuses length mismatched');
for (uint idx = 0; idx < spells.length; idx++) {
whitelistedSpells[spells[idx]] = statuses[idx];
}
}
/// @dev Set whitelist token status
/// @param tokens list of tokens to change status
/// @param statuses list of statuses to change to
function setWhitelistTokens(address[] calldata tokens, bool[] calldata statuses)
external
onlyGov
{
require(tokens.length == statuses.length, 'tokens & statuses length mismatched');
for (uint idx = 0; idx < tokens.length; idx++) {
if (statuses[idx]) {
// check oracle suppport
require(support(tokens[idx]), 'oracle not support token');
}
whitelistedTokens[tokens[idx]] = statuses[idx];
}
}
/// @dev Set whitelist user status
/// @param users list of users to change status
/// @param statuses list of statuses to change to
function setWhitelistUsers(address[] calldata users, bool[] calldata statuses) external onlyGov {
require(users.length == statuses.length, 'users & statuses length mismatched');
for (uint idx = 0; idx < users.length; idx++) {
whitelistedUsers[users[idx]] = statuses[idx];
}
}
/// @dev Check whether the oracle supports the token
/// @param token ERC-20 token to check for support
function support(address token) public view override returns (bool) {
return oracle.support(token);
}
/// @dev Set bank status
/// @param _bankStatus new bank status to change to
function setBankStatus(uint _bankStatus) external onlyGov {
bankStatus = _bankStatus;
}
/// @dev Bank borrow status allowed or not
/// @notice check last bit of bankStatus
function allowBorrowStatus() public view returns (bool) {
return (bankStatus & 0x01) > 0;
}
/// @dev Bank repay status allowed or not
/// @notice Check second-to-last bit of bankStatus
function allowRepayStatus() public view returns (bool) {
return (bankStatus & 0x02) > 0;
}
/// @dev Trigger interest accrual for the given bank.
/// @param token The underlying token to trigger the interest accrual.
function accrue(address token) public override {
Bank storage bank = banks[token];
require(bank.isListed, 'bank not exist');
uint totalDebt = bank.totalDebt;
uint debt = ICErc20(bank.cToken).borrowBalanceCurrent(address(this));
if (debt > totalDebt) {
uint fee = debt.sub(totalDebt).mul(feeBps).div(10000);
bank.totalDebt = debt;
bank.reserve = bank.reserve.add(doBorrow(token, fee));
} else if (totalDebt != debt) {
// We should never reach here because CREAMv2 does not support *repayBorrowBehalf*
// functionality. We set bank.totalDebt = debt nonetheless to ensure consistency. But do
// note that if *repayBorrowBehalf* exists, an attacker can maliciously deflate debt
// share value and potentially make this contract stop working due to math overflow.
bank.totalDebt = debt;
}
}
/// @dev Convenient function to trigger interest accrual for a list of banks.
/// @param tokens The list of banks to trigger interest accrual.
function accrueAll(address[] memory tokens) external {
for (uint idx = 0; idx < tokens.length; idx++) {
accrue(tokens[idx]);
}
}
/// @dev Return the borrow balance for given position and token without triggering interest accrual.
/// @param positionId The position to query for borrow balance.
/// @param token The token to query for borrow balance.
function borrowBalanceStored(uint positionId, address token) public view override returns (uint) {
uint totalDebt = banks[token].totalDebt;
uint totalShare = banks[token].totalShare;
uint share = positions[positionId].debtShareOf[token];
if (share == 0 || totalDebt == 0) {
return 0;
} else {
return share.mul(totalDebt).ceilDiv(totalShare);
}
}
/// @dev Trigger interest accrual and return the current borrow balance.
/// @param positionId The position to query for borrow balance.
/// @param token The token to query for borrow balance.
function borrowBalanceCurrent(uint positionId, address token) external override returns (uint) {
accrue(token);
return borrowBalanceStored(positionId, token);
}
/// @dev Return bank information for the given token.
/// @param token The token address to query for bank information.
function getBankInfo(address token)
external
view
override
returns (
bool isListed,
address cToken,
uint reserve,
uint totalDebt,
uint totalShare
)
{
Bank storage bank = banks[token];
return (bank.isListed, bank.cToken, bank.reserve, bank.totalDebt, bank.totalShare);
}
/// @dev Return position information for the given position id.
/// @param positionId The position id to query for position information.
function getPositionInfo(uint positionId)
public
view
override
returns (
address owner,
address collToken,
uint collId,
uint collateralSize
)
{
Position storage pos = positions[positionId];
return (pos.owner, pos.collToken, pos.collId, pos.collateralSize);
}
/// @dev Return current position information
function getCurrentPositionInfo()
external
view
override
returns (
address owner,
address collToken,
uint collId,
uint collateralSize
)
{
require(POSITION_ID != _NO_ID, 'no id');
return getPositionInfo(POSITION_ID);
}
/// @dev Return the debt share of the given bank token for the given position id.
/// @param positionId position id to get debt of
/// @param token ERC20 debt token to query
function getPositionDebtShareOf(uint positionId, address token) external view returns (uint) {
return positions[positionId].debtShareOf[token];
}
/// @dev Return the list of all debts for the given position id.
/// @param positionId position id to get debts of
function getPositionDebts(uint positionId)
external
view
returns (address[] memory tokens, uint[] memory debts)
{
Position storage pos = positions[positionId];
uint count = 0;
uint bitMap = pos.debtMap;
while (bitMap > 0) {
if ((bitMap & 1) != 0) {
count++;
}
bitMap >>= 1;
}
tokens = new address[](count);
debts = new uint[](count);
bitMap = pos.debtMap;
count = 0;
uint idx = 0;
while (bitMap > 0) {
if ((bitMap & 1) != 0) {
address token = allBanks[idx];
Bank storage bank = banks[token];
tokens[count] = token;
debts[count] = pos.debtShareOf[token].mul(bank.totalDebt).ceilDiv(bank.totalShare);
count++;
}
idx++;
bitMap >>= 1;
}
}
/// @dev Return the total collateral value of the given position in ETH.
/// @param positionId The position ID to query for the collateral value.
function getCollateralETHValue(uint positionId) public view returns (uint) {
Position storage pos = positions[positionId];
uint size = pos.collateralSize;
if (size == 0) {
return 0;
} else {
require(pos.collToken != address(0), 'bad collateral token');
return oracle.asETHCollateral(pos.collToken, pos.collId, size, pos.owner);
}
}
/// @dev Return the total borrow value of the given position in ETH.
/// @param positionId The position ID to query for the borrow value.
function getBorrowETHValue(uint positionId) public view override returns (uint) {
uint value = 0;
Position storage pos = positions[positionId];
address owner = pos.owner;
uint bitMap = pos.debtMap;
uint idx = 0;
while (bitMap > 0) {
if ((bitMap & 1) != 0) {
address token = allBanks[idx];
uint share = pos.debtShareOf[token];
Bank storage bank = banks[token];
uint debt = share.mul(bank.totalDebt).ceilDiv(bank.totalShare);
value = value.add(oracle.asETHBorrow(token, debt, owner));
}
idx++;
bitMap >>= 1;
}
return value;
}
/// @dev Add a new bank to the ecosystem.
/// @param token The underlying token for the bank.
/// @param cToken The address of the cToken smart contract.
function addBank(address token, address cToken) external onlyGov {
Bank storage bank = banks[token];
require(!cTokenInBank[cToken], 'cToken already exists');
require(!bank.isListed, 'bank already exists');
cTokenInBank[cToken] = true;
bank.isListed = true;
require(allBanks.length < 256, 'reach bank limit');
bank.index = uint8(allBanks.length);
bank.cToken = cToken;
IERC20(token).safeApprove(cToken, 0);
IERC20(token).safeApprove(cToken, uint(-1));
allBanks.push(token);
emit AddBank(token, cToken);
}
/// @dev Set the oracle smart contract address.
/// @param _oracle The new oracle smart contract address.
function setOracle(IOracle _oracle) external onlyGov {
require(address(_oracle) != address(0), 'cannot set zero address oracle');
oracle = _oracle;
emit SetOracle(address(_oracle));
}
/// @dev Set the fee bps value that Homora bank charges.
/// @param _feeBps The new fee bps value.
function setFeeBps(uint _feeBps) external onlyGov {
require(_feeBps <= 10000, 'fee too high');
feeBps = _feeBps;
emit SetFeeBps(_feeBps);
}
/// @dev Set the reward token smart contract address.
/// @param _rewardToken The new reward token smart contract address.
function setRewardToken(address _rewardToken) external onlyGov {
require(address(_rewardToken) != address(0), 'cannot set zero address rewardToken');
rewardToken = _rewardToken;
}
/// @dev Withdraw the reserve portion of the bank.
/// @param amount The amount of tokens to withdraw.
function withdrawReserve(address token, uint amount) external onlyGov lock {
Bank storage bank = banks[token];
require(bank.isListed, 'bank not exist');
bank.reserve = bank.reserve.sub(amount);
IERC20(token).safeTransfer(msg.sender, amount);
emit WithdrawReserve(msg.sender, token, amount);
}
/// @dev Withdraw the reward of the bank.
/// @param amount The amount of tokens to withdraw.
function withdrawReward(uint amount) external onlyGov lock {
uint balance = IERC20(rewardToken).balanceOf(address(this));
if (balance > 0) {
IERC20(rewardToken).safeTransfer(msg.sender, amount > balance ? balance : amount);
}
}
/// @dev Liquidate a position. Pay debt for its owner and take the collateral.
/// @param positionId The position ID to liquidate.
/// @param debtToken The debt token to repay.
/// @param amountCall The amount to repay when doing transferFrom call.
function liquidate(
uint positionId,
address debtToken,
uint amountCall
) external override lock poke(debtToken) {
uint collateralValue = getCollateralETHValue(positionId);
uint borrowValue = getBorrowETHValue(positionId);
require(collateralValue < borrowValue, 'position still healthy');
Position storage pos = positions[positionId];
(uint amountPaid, uint share) = repayInternal(positionId, debtToken, amountCall);
require(pos.collToken != address(0), 'bad collateral token');
uint bounty =
Math.min(
oracle.convertForLiquidation(debtToken, pos.collToken, pos.collId, amountPaid),
pos.collateralSize
);
pos.collateralSize = pos.collateralSize.sub(bounty);
IERC1155(pos.collToken).safeTransferFrom(address(this), msg.sender, pos.collId, bounty, '');
emit Liquidate(positionId, msg.sender, debtToken, amountPaid, share, bounty);
}
/// @dev Execute the action via HomoraCaster, calling its function with the supplied data.
/// @param positionId The position ID to execute the action, or zero for new position.
/// @param spell The target spell to invoke the execution via HomoraCaster.
/// @param data Extra data to pass to the target for the execution.
function execute(
uint positionId,
address spell,
bytes memory data
) external payable lock onlyEOAEx returns (uint) {
require(whitelistedSpells[spell], 'spell not whitelisted');
if (positionId == 0) {
positionId = nextPositionId++;
positions[positionId].owner = msg.sender;
} else {
require(positionId < nextPositionId, 'position id not exists');
require(msg.sender == positions[positionId].owner, 'not position owner');
}
POSITION_ID = positionId;
SPELL = spell;
HomoraCaster(caster).cast{value: msg.value}(spell, data);
uint collateralValue = getCollateralETHValue(positionId);
uint borrowValue = getBorrowETHValue(positionId);
require(collateralValue >= borrowValue, 'insufficient collateral');
POSITION_ID = _NO_ID;
SPELL = _NO_ADDRESS;
return positionId;
}
/// @dev Borrow tokens from that bank. Must only be called while under execution.
/// @param token The token to borrow from the bank.
/// @param amount The amount of tokens to borrow.
function borrow(address token, uint amount) external override inExec poke(token) {
require(allowBorrowStatus(), 'borrow not allowed');
require(whitelistedTokens[token], 'token not whitelisted');
Bank storage bank = banks[token];
Position storage pos = positions[POSITION_ID];
uint totalShare = bank.totalShare;
uint totalDebt = bank.totalDebt;
uint share = totalShare == 0 ? amount : amount.mul(totalShare).ceilDiv(totalDebt);
bank.totalShare = bank.totalShare.add(share);
uint newShare = pos.debtShareOf[token].add(share);
pos.debtShareOf[token] = newShare;
if (newShare > 0) {
pos.debtMap |= (1 << uint(bank.index));
}
IERC20(token).safeTransfer(msg.sender, doBorrow(token, amount));
emit Borrow(POSITION_ID, msg.sender, token, amount, share);
}
/// @dev Repay tokens to the bank. Must only be called while under execution.
/// @param token The token to repay to the bank.
/// @param amountCall The amount of tokens to repay via transferFrom.
function repay(address token, uint amountCall) external override inExec poke(token) {
require(allowRepayStatus(), 'repay not allowed');
require(whitelistedTokens[token], 'token not whitelisted');
(uint amount, uint share) = repayInternal(POSITION_ID, token, amountCall);
emit Repay(POSITION_ID, msg.sender, token, amount, share);
}
/// @dev Perform repay action. Return the amount actually taken and the debt share reduced.
/// @param positionId The position ID to repay the debt.
/// @param token The bank token to pay the debt.
/// @param amountCall The amount to repay by calling transferFrom, or -1 for debt size.
function repayInternal(
uint positionId,
address token,
uint amountCall
) internal returns (uint, uint) {
Bank storage bank = banks[token];
Position storage pos = positions[positionId];
uint totalShare = bank.totalShare;
uint totalDebt = bank.totalDebt;
uint oldShare = pos.debtShareOf[token];
uint oldDebt = oldShare.mul(totalDebt).ceilDiv(totalShare);
if (amountCall == uint(-1)) {
amountCall = oldDebt;
}
uint paid = doRepay(token, doERC20TransferIn(token, amountCall));
require(paid <= oldDebt, 'paid exceeds debt'); // prevent share overflow attack
uint lessShare = paid == oldDebt ? oldShare : paid.mul(totalShare).div(totalDebt);
bank.totalShare = totalShare.sub(lessShare);
uint newShare = oldShare.sub(lessShare);
pos.debtShareOf[token] = newShare;
if (newShare == 0) {
pos.debtMap &= ~(1 << uint(bank.index));
}
return (paid, lessShare);
}
/// @dev Transmit user assets to the caller, so users only need to approve Bank for spending.
/// @param token The token to transfer from user to the caller.
/// @param amount The amount to transfer.
function transmit(address token, uint amount) external override inExec {
Position storage pos = positions[POSITION_ID];
IERC20(token).safeTransferFrom(pos.owner, msg.sender, amount);
}
/// @dev Put more collateral for users. Must only be called during execution.
/// @param collToken The ERC1155 token to collateral.
/// @param collId The token id to collateral.
/// @param amountCall The amount of tokens to put via transferFrom.
function putCollateral(
address collToken,
uint collId,
uint amountCall
) external override inExec {
Position storage pos = positions[POSITION_ID];
if (pos.collToken != collToken || pos.collId != collId) {
require(oracle.supportWrappedToken(collToken, collId), 'collateral not supported');
require(pos.collateralSize == 0, 'another type of collateral already exists');
pos.collToken = collToken;
pos.collId = collId;
}
uint amount = doERC1155TransferIn(collToken, collId, amountCall);
pos.collateralSize = pos.collateralSize.add(amount);
emit PutCollateral(POSITION_ID, msg.sender, collToken, collId, amount);
}
/// @dev Take some collateral back. Must only be called during execution.
/// @param collToken The ERC1155 token to take back.
/// @param collId The token id to take back.
/// @param amount The amount of tokens to take back via transfer.
function takeCollateral(
address collToken,
uint collId,
uint amount
) external override inExec {
Position storage pos = positions[POSITION_ID];
require(collToken == pos.collToken, 'invalid collateral token');
require(collId == pos.collId, 'invalid collateral token');
if (amount == uint(-1)) {
amount = pos.collateralSize;
}
pos.collateralSize = pos.collateralSize.sub(amount);
IERC1155(collToken).safeTransferFrom(address(this), msg.sender, collId, amount, '');
emit TakeCollateral(POSITION_ID, msg.sender, collToken, collId, amount);
}
/// @dev Internal function to perform borrow from the bank and return the amount received.
/// @param token The token to perform borrow action.
/// @param amountCall The amount use in the transferFrom call.
/// NOTE: Caller must ensure that cToken interest was already accrued up to this block.
function doBorrow(address token, uint amountCall) internal returns (uint) {
Bank storage bank = banks[token]; // assume the input is already sanity checked.
uint balanceBefore = IERC20(token).balanceOf(address(this));
require(ICErc20(bank.cToken).borrow(amountCall) == 0, 'bad borrow');
uint balanceAfter = IERC20(token).balanceOf(address(this));
bank.totalDebt = bank.totalDebt.add(amountCall);
return balanceAfter.sub(balanceBefore);
}
/// @dev Internal function to perform repay to the bank and return the amount actually repaid.
/// @param token The token to perform repay action.
/// @param amountCall The amount to use in the repay call.
/// NOTE: Caller must ensure that cToken interest was already accrued up to this block.
function doRepay(address token, uint amountCall) internal returns (uint) {
Bank storage bank = banks[token]; // assume the input is already sanity checked.
ICErc20 cToken = ICErc20(bank.cToken);
uint oldDebt = bank.totalDebt;
require(cToken.repayBorrow(amountCall) == 0, 'bad repay');
uint newDebt = cToken.borrowBalanceStored(address(this));
bank.totalDebt = newDebt;
return oldDebt.sub(newDebt);
}
/// @dev Internal function to perform ERC20 transfer in and return amount actually received.
/// @param token The token to perform transferFrom action.
/// @param amountCall The amount use in the transferFrom call.
function doERC20TransferIn(address token, uint amountCall) internal returns (uint) {
uint balanceBefore = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransferFrom(msg.sender, address(this), amountCall);
uint balanceAfter = IERC20(token).balanceOf(address(this));
return balanceAfter.sub(balanceBefore);
}
/// @dev Internal function to perform ERC1155 transfer in and return amount actually received.
/// @param token The token to perform transferFrom action.
/// @param id The id to perform transferFrom action.
/// @param amountCall The amount use in the transferFrom call.
function doERC1155TransferIn(
address token,
uint id,
uint amountCall
) internal returns (uint) {
uint balanceBefore = IERC1155(token).balanceOf(address(this), id);
IERC1155(token).safeTransferFrom(msg.sender, address(this), id, amountCall, '');
uint balanceAfter = IERC1155(token).balanceOf(address(this), id);
return balanceAfter.sub(balanceBefore);
}
}
| Initialize the bank smart contract, using msg.sender as the first governor. _oracle The oracle smart contract address. _feeBps The fee collected to Homora bank. | function initialize(IOracle _oracle, uint _feeBps, address _rewardToken) external initializer {
__Governable__init();
_GENERAL_LOCK = _NOT_ENTERED;
_IN_EXEC_LOCK = _NOT_ENTERED;
POSITION_ID = _NO_ID;
SPELL = _NO_ADDRESS;
caster = address(new HomoraCaster());
oracle = _oracle;
require(address(_oracle) != address(0), 'bad oracle address');
feeBps = _feeBps;
nextPositionId = 1;
rewardToken = _rewardToken;
emit SetOracle(address(_oracle));
emit SetFeeBps(_feeBps);
}
| 14,066,387 |
./partial_match/11155111/0x1e4370ca8102Adb5329e04Ec812DF4f6b3Ed4462/sources/NameService/Ver1.sol | Generate JSON data based on the provided word and SVG image You can customize the JSON structure and add more properties as needed | function generateJSONData(string memory word, string memory svgImage) internal pure returns (string memory) {
string memory json = string(
abi.encodePacked(
'{"name": "', word, '", ',
'"description": "An NFT with a word and SVG image", ',
'"image": "', svgImage, '"}'
)
);
return json;
}
| 3,533,810 |
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* @title Staking Token (STK)
* @author Alberto Cuesta Canada
* @notice Implements a basic ERC20 staking token with incentive distribution.
*/
contract StakingToken is ERC20, Ownable {
using SafeMath for uint256;
uint contract_start = 0;
uint period = 3 seconds;
uint256 reward_pool = 1000;
uint256 reward_pool_1 = reward_pool * 2 / 10;
uint256 reward_pool_2 = reward_pool * 3 / 10;
uint256 reward_pool_3 = reward_pool * 5 / 10;
/**
* @notice We usually require to know who are all the stakeholders.
*/
address[] internal stakeholders;
/**
* @notice The stakes for each stakeholder.
*/
mapping(address => uint256) internal stakes;
/**
* @notice The accumulated rewards for each stakeholder.
*/
mapping(address => uint256) internal rewards;
/**
* @notice The constructor for the Staking Token.
* @param _owner The address to receive all tokens on construction.
* @param _supply The amount of tokens to mint on construction.
*/
constructor(address _owner, uint256 _supply) public
{
contract_start = block.timestamp;
_mint(_owner, _supply);
}
// ---------- STAKES ----------
/**
* @notice A method for a stakeholder to create a stake.
* @param _stake The size of the stake to be created.
*/
function createStake(uint256 _stake) public
{
require(block.timestamp < contract_start + period, "Can stake only within `period` time since contract deployed");
_burn(msg.sender, _stake);
if(stakes[msg.sender] == 0) addStakeholder(msg.sender);
stakes[msg.sender] = stakes[msg.sender].add(_stake);
}
/**
* @notice A method for a stakeholder to remove a stake.
* @param _stake The size of the stake to be removed.
*/
function removeStake(uint256 _stake) public
{
stakes[msg.sender] = stakes[msg.sender].sub(_stake);
if(stakes[msg.sender] == 0) removeStakeholder(msg.sender);
_mint(msg.sender, _stake);
}
/**
* @notice A method to retrieve the stake for a stakeholder.
* @param _stakeholder The stakeholder to retrieve the stake for.
* @return uint256 The amount of wei staked.
*/
function stakeOf(address _stakeholder) public view returns(uint256)
{
return stakes[_stakeholder];
}
/**
* @notice A method to the aggregated stakes from all stakeholders.
* @return uint256 The aggregated stakes from all stakeholders.
*/
function totalStakes() public view returns(uint256)
{
uint256 _totalStakes = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1){
_totalStakes = _totalStakes.add(stakes[stakeholders[s]]);
}
return _totalStakes;
}
// ---------- STAKEHOLDERS ----------
/**
* @notice A method to check if an address is a stakeholder.
* @param _address The address to verify.
* @return bool, uint256 Whether the address is a stakeholder,
* and if so its position in the stakeholders array.
*/
function isStakeholder(address _address) public view returns(bool, uint256)
{
for (uint256 s = 0; s < stakeholders.length; s += 1){
if (_address == stakeholders[s]) return (true, s);
}
return (false, 0);
}
/**
* @notice A method to add a stakeholder.
* @param _stakeholder The stakeholder to add.
*/
function addStakeholder(address _stakeholder) public
{
(bool _isStakeholder, ) = isStakeholder(_stakeholder);
if(!_isStakeholder) stakeholders.push(_stakeholder);
}
/**
* @notice A method to remove a stakeholder.
* @param _stakeholder The stakeholder to remove.
*/
function removeStakeholder(address _stakeholder) public
{
(bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder);
if(_isStakeholder){
stakeholders[s] = stakeholders[stakeholders.length - 1];
stakeholders.pop();
}
}
// ---------- REWARDS ----------
/**
* @notice A method to allow a stakeholder to check his rewards.
* @param _stakeholder The stakeholder to check rewards for.
*/
function rewardOf(address _stakeholder) public view returns(uint256)
{
return rewards[_stakeholder];
}
/**
* @notice A method to the aggregated rewards from all stakeholders.
* @return uint256 The aggregated rewards from all stakeholders.
*/
function totalRewards() public view returns(uint256)
{
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1){
_totalRewards = _totalRewards.add(rewards[stakeholders[s]]);
}
return _totalRewards;
}
/**
* @notice A simple method that calculates the rewards for each stakeholder.
* @param _stakeholder The stakeholder to calculate rewards for.
*/
function calculateReward(address _stakeholder) public payable returns(uint256)
{
if (block.timestamp > contract_start + 2 * period) {
if (block.timestamp < contract_start + 3 * period) {
uint256 _reward = reward_pool_1 != 0 ? reward_pool_1 * stakeOf(_stakeholder) / totalStakes() : 0;
reward_pool_1 = reward_pool_1 - _reward;
reward_pool_1 = reward_pool_1 < 0 ? 0 : reward_pool_1;
return _reward;
}
else if (block.timestamp < contract_start + 4 * period) {
uint256 _reward_1 = reward_pool_1 != 0 ? reward_pool_1 * stakeOf(_stakeholder) / totalStakes() : 0;
uint256 _reward_2 = reward_pool_2 != 0 ? reward_pool_2 * stakeOf(_stakeholder) / totalStakes() : 0;
reward_pool_1 = reward_pool_1 - _reward_1;
reward_pool_1 = reward_pool_1 < 0 ? 0 : reward_pool_1;
reward_pool_2 = reward_pool_2 - _reward_2;
reward_pool_2 = reward_pool_2 < 0 ? 0 : reward_pool_2;
return _reward_1 + _reward_2;
}
else {
uint256 _reward_1 = reward_pool_1 != 0 ? reward_pool_1 * stakeOf(_stakeholder) / totalStakes() : 0;
uint256 _reward_2 = reward_pool_2 != 0 ? reward_pool_2 * stakeOf(_stakeholder) / totalStakes() : 0;
uint256 _reward_3 = reward_pool_3 != 0 ? reward_pool_3 * stakeOf(_stakeholder) / totalStakes() : 0;
reward_pool_1 = reward_pool_1 - _reward_1;
reward_pool_1 = reward_pool_1 < 0 ? 0 : reward_pool_1;
reward_pool_2 = reward_pool_2 - _reward_2;
reward_pool_2 = reward_pool_2 < 0 ? 0 : reward_pool_2;
reward_pool_3 = reward_pool_3 - _reward_3;
reward_pool_3 = reward_pool_3 < 0 ? 0 : reward_pool_3;
return _reward_1 + _reward_2 + _reward_3;
}
}
return stakes[_stakeholder] / 100;
}
/**
* @notice A method to distribute rewards to all stakeholders.
*/
function distributeRewards() public onlyOwner
{
for (uint256 s = 0; s < stakeholders.length; s += 1){
address stakeholder = stakeholders[s];
uint256 reward = calculateReward(stakeholder);
rewards[stakeholder] = rewards[stakeholder].add(reward);
}
}
/**
* @notice A method to allow a stakeholder to withdraw his rewards.
*/
function withdrawReward() public
{
require(block.timestamp > contract_start + 2 * period, "Can withdraw only within `2 * period` time since contract deployed");
uint256 reward = rewards[msg.sender];
rewards[msg.sender] = 0;
_mint(msg.sender, reward);
}
}
| A method to distribute rewards to all stakeholders./ | function distributeRewards() public onlyOwner
{
for (uint256 s = 0; s < stakeholders.length; s += 1){
address stakeholder = stakeholders[s];
uint256 reward = calculateReward(stakeholder);
rewards[stakeholder] = rewards[stakeholder].add(reward);
}
}
| 929,077 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "./VaultCalculator.sol";
/// @title IVault Interface
interface IVault {
function getAccessor() external view returns (address);
}
/// @title IComptroller Interface
interface IComptroller {
function calcGav(bool) external returns (uint256, bool);
function getDenominationAsset() external view returns (address);
}
/// @title IFundValueCalculatorUsdWrapper interface
interface IFundValueCalculatorUsdWrapper {
function calcNetValueForSharesHolder(
address _vaultProxy,
address _sharesHolder
) external returns (uint256 netValue_);
}
/// @title IFundValueCalculator interface
interface IFundValueCalculatorRouter {
function calcNetValueForSharesHolder(
address _vaultProxy,
address _sharesHolder
) external returns (address denominationAsset_, uint256 netValue_);
function calcNetValueForSharesHolderInAsset(
address _vaultProxy,
address _sharesHolder,
address _quoteAsset
) external returns (uint256 netValue_);
}
/// @title EnzymeCurrencyCalculatorCustom
/// @dev This contract is used as an adapter to get a calculated dollar value for an Enzyme Vault
contract EnzymeCurrencyCalculatorCustom is IVaultCalculator {
address calculator;
address sharesHolder;
constructor(address _calculator, address _sharesHolder) {
require(
_calculator != address(0),
"calculator can not be the zero address"
);
require(
_sharesHolder != address(0),
"share holder can not be the zero address"
);
calculator = _calculator;
sharesHolder = _sharesHolder;
}
/// @notice The decimals are assumed to be 18, and the security is dependant on the Enzyme implementation
/// @dev Read the dollar denominated value with a custom calculator for a given vault
/// @param vaultProxy The address of an Enzyme vault
function calculate(address vaultProxy)
external
override
returns (uint256 answer)
{
answer = IFundValueCalculatorUsdWrapper(calculator)
.calcNetValueForSharesHolder(vaultProxy, sharesHolder);
}
}
/// @title EnzymeCurrencyCalculatorStandard
/// @dev This contract is used as an adapter to get a calculated dollar value for an Enzyme Vault
contract EnzymeCurrencyCalculatorStandard is IVaultCalculator {
AggregatorV3Interface price;
constructor(AggregatorV3Interface _price) {
price = _price;
}
/// @notice The decimals are assumed to be 18, and the security is dependant on the Enzyme implementation
/// @dev Read the dollar denominated value with of a vault using a Chainlink price feed and the denomination token
/// quantity
/// @param vault The address of an Enzyme vault
function calculate(address vault) external override returns (uint256) {
IComptroller accessor = IComptroller(IVault(vault).getAccessor());
address denominationAsset = accessor.getDenominationAsset();
uint256 answer;
(answer, ) = IComptroller(accessor).calcGav(false);
int256 latestRoundData;
(, latestRoundData, , , ) = AggregatorV3Interface(price)
.latestRoundData();
uint256 decimals = uint256(ERC20(denominationAsset).decimals());
uint256 priceDecimals = uint256(
AggregatorV3Interface(price).decimals()
);
require(latestRoundData > 0, "price feed error");
require(
18 >= decimals && 18 >= priceDecimals,
"invalid token decimals"
);
uint256 priceFeed = uint256(latestRoundData);
return
(answer * priceFeed * 10**uint256(18 - priceDecimals)) /
10**uint256(decimals); // return (answer * priceFeed) / 10**8;
}
}
/// @title EnzymeCurrencyCalculatorStandard
/// @dev This contract is used as an adapter to get a calculated token value for an Enzyme Vault
contract EnzymeTokenCalculatorCustom is IVaultCalculator {
address calculator;
address sharesHolder;
constructor(address _calculator, address _sharesHolder) {
require(
_calculator != address(0),
"calculator can not be the zero address"
);
require(
_sharesHolder != address(0),
"share holder can not be the zero address"
);
calculator = _calculator;
sharesHolder = _sharesHolder;
}
/// @notice The decimals are assumed to be 18, and the security is dependant on the Enzyme implementation
/// @dev Read the token quantity value with a custom calculator for a given vault
/// @param vaultProxy The address of an Enzyme vault
function calculate(address vaultProxy) external override returns (uint256) {
address denominationAsset;
(denominationAsset, ) = IFundValueCalculatorRouter(calculator)
.calcNetValueForSharesHolder(vaultProxy, sharesHolder);
return
IFundValueCalculatorRouter(calculator)
.calcNetValueForSharesHolderInAsset(
vaultProxy,
sharesHolder,
denominationAsset
);
}
}
/// @title EnzymeCurrencyCalculatorStandard
/// @dev This contract is used as an adapter to get a calculated token value for an Enzyme Vault
contract EnzymeTokenCalculatorStandard is IVaultCalculator {
/// @notice The decimals are assumed to be 18, and the security is dependant on the Enzyme implementation
/// @dev Read the token quantity value calling the peripheral contract directly
/// @param vault The address of an Enzyme vault
function calculate(address vault) external override returns (uint256) {
IComptroller accessor = IComptroller(IVault(vault).getAccessor());
address denominationAsset = accessor.getDenominationAsset();
uint256 answer;
(answer, ) = accessor.calcGav(false);
uint256 decimals = uint256(ERC20(denominationAsset).decimals());
require(18 >= decimals);
return answer * 10**uint256(18 - decimals);
}
}
| The decimals are assumed to be 18, and the security is dependant on the Enzyme implementation Read the token quantity value calling the peripheral contract directly vault The address of an Enzyme vault | function calculate(address vault) external override returns (uint256) {
IComptroller accessor = IComptroller(IVault(vault).getAccessor());
address denominationAsset = accessor.getDenominationAsset();
uint256 answer;
(answer, ) = accessor.calcGav(false);
uint256 decimals = uint256(ERC20(denominationAsset).decimals());
require(18 >= decimals);
return answer * 10**uint256(18 - decimals);
}
| 14,024,290 |
/**
*Submitted for verification at Etherscan.io on 2021-08-25
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/*
* @dev 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 () { }
function _msgSender() internal view returns (address payable) {
return payable(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 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;
}
}
/**
* @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 () {
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 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;
}
}
contract Claiming is Ownable{
using SafeMath for uint256;
/**
* Structure of an object to pass for allowance list
*/
struct allowedUser {
address wallet;
uint256 amount;
}
IERC20 public token;
bool internal isClaimOpen;
uint256 internal totalUnclaimed;
mapping(address => uint256) allowanceAmounts;
constructor(IERC20 _token){
token = _token;
isClaimOpen = false;
totalUnclaimed = 0;
}
event UnsuccessfulTransfer(address recipient);
/**
* Ensures that claiming tokens is currently allowed by the owner.
*/
modifier openClaiming() {
require(
isClaimOpen,
"Claiming tokens is not currently allowed."
);
_;
}
/**
* Ensures that the amount of claimed tokens is not bigger than the user is allowed to claim.
*/
modifier userHasEnoughClaimableTokens (uint256 amount) {
require(
allowanceAmounts[msg.sender] >= amount,
"The users token amount is smaller than the requested."
);
_;
}
/**
* Ensures that contract has enough tokens for the transaction.
*/
modifier enoughContractAmount(uint256 amount) {
require(
token.balanceOf(address(this)) >= amount,
"Owned token amount is too small."
);
_;
}
/**
* Ensures that only people from the allowance list can claim tokens.
*/
modifier userHasClaimableTokens() {
require(
allowanceAmounts[msg.sender] > 0,
"There is no tokens for the user to claim or the user is not allowed to do so."
);
_;
}
modifier hasContractTokens() {
require(
token.balanceOf(address(this)) > 0,
"There is no tokens for the user to claim or the user is not allowed to do so."
);
_;
}
/** @dev Transfers the spacified number of tokens to the user requesting
*
* Substracts the requested amount of tokens from the allowance amount of the user
* Transfers tokens from contract to the message sender
* In case of failure restores the previous allowance amount
*
* Requirements:
*
* - message sender cannot be address(0) and has to be in AllowanceList
*/
function claimCustomAmountTokens(uint256 amount)
public
openClaiming
userHasEnoughClaimableTokens(amount)
enoughContractAmount(amount)
{
require(msg.sender != address(0), "Sender is address zero");
allowanceAmounts[msg.sender] = allowanceAmounts[msg.sender].sub(amount);
token.approve(address(this), amount);
if (!token.transferFrom(address(this), msg.sender, amount)){
allowanceAmounts[msg.sender].add(amount);
emit UnsuccessfulTransfer(msg.sender);
}
else {
totalUnclaimed = totalUnclaimed.sub(amount);
}
}
/** @dev Transfers the spacified number of tokens to the user requesting
*
* Makes the allowance equal to zero
* Transfers all allowed tokens from contract to the message sender
* In case of failure restores the previous allowance amount
*
* Requirements:
*
* - message sender cannot be address(0) and has to be in AllowanceList
*/
function claimRemainingTokens()
public
openClaiming
userHasClaimableTokens
{
require(msg.sender != address(0), "Sender is address zero");
uint256 amount = allowanceAmounts[msg.sender];
require(token.balanceOf(address(this)) >= amount, "Insufficient amount of tokens in contract");
allowanceAmounts[msg.sender] = 0;
token.approve(address(this), amount);
if (!token.transferFrom(address(this), msg.sender, amount)){
allowanceAmounts[msg.sender] = amount;
emit UnsuccessfulTransfer(msg.sender);
}
else{
totalUnclaimed = totalUnclaimed.sub(amount);
}
}
/** @dev Adds the provided address to Allowance list with allowed provided amount of tokens
* Available only for the owner of contract
*/
function addToAllowanceListSingle(address addAddress, uint256 amount)
public
onlyOwner
{
allowanceAmounts[addAddress] = allowanceAmounts[addAddress].add(amount);
totalUnclaimed = totalUnclaimed.add(amount);
}
/** @dev Adds the provided address to Allowance list with allowed provided amount of tokens
* Available only for the owner
*/
function substractFromAllowanceListSingle(address subAddress, uint256 amount)
public
onlyOwner
{
require(allowanceAmounts[subAddress] != 0, "The address does not have allowance to substract from.");
allowanceAmounts[subAddress] = allowanceAmounts[subAddress].sub(amount);
totalUnclaimed = totalUnclaimed.sub(amount);
}
/** @dev Adds the provided address list to Allowance list with allowed provided amounts of tokens
* Available only for the owner
*/
function addToAllowanceListMultiple(allowedUser[] memory addAddresses)
public
onlyOwner
{
for (uint256 i = 0; i < addAddresses.length; i++) {
allowanceAmounts[addAddresses[i].wallet] = allowanceAmounts[addAddresses[i].wallet].add(addAddresses[i].amount);
totalUnclaimed = totalUnclaimed.add(addAddresses[i].amount);
}
}
/** @dev Removes the provided address from Allowance list by setting his allowed sum to zero
* Available only for the owner of contract
*/
function removeFromAllowanceList(address remAddress)
public
onlyOwner
{
totalUnclaimed = totalUnclaimed.sub(allowanceAmounts[remAddress]);
delete allowanceAmounts[remAddress];
}
/** @dev Allows the owner to turn the claiming on.
*/
function turnClaimingOn()
public
onlyOwner
{
isClaimOpen = true;
}
/** @dev Allows the owner to turn the claiming off.
*/
function turnClaimingOff()
public
onlyOwner
{
isClaimOpen = false;
}
/** @dev Allows the owner to withdraw all the remaining tokens from the contract
*/
function withdrawAllTokensOwner()
public
onlyOwner
{
token.approve(address(this), token.balanceOf(address(this)));
if (!token.transferFrom(address(this), msg.sender, token.balanceOf(address(this)))){
emit UnsuccessfulTransfer(msg.sender);
}
}
/** @dev Allows the owner to withdraw the specified amount of tokens from the contract
*/
function withdrawCustomTokensOwner(uint256 amount)
public
onlyOwner
enoughContractAmount(amount)
{
token.approve(address(this), amount);
if (!token.transferFrom(address(this), msg.sender, amount)){
emit UnsuccessfulTransfer(msg.sender);
}
}
/** @dev Allows the owner to withdraw the residual tokens from the contract
*/
function withdrawResidualTokensOwner()
public
onlyOwner
{
uint256 amount = token.balanceOf(address(this)).sub(totalUnclaimed);
require(token.balanceOf(address(this)) >= amount, "Insufficient amount of tokens in contract");
token.approve(address(this), amount);
if (!token.transferFrom(address(this), msg.sender, amount)){
emit UnsuccessfulTransfer(msg.sender);
}
}
/** @dev Allows the owner to withdraw the specified amount of any IERC20 tokens from the contract
*/
function withdrawAnyContractTokens(IERC20 tokenAddress, address recipient)
public
onlyOwner
{
require(msg.sender != address(0), "Sender is address zero");
require(recipient != address(0), "Receiver is address zero");
tokenAddress.approve(address(this), tokenAddress.balanceOf(address(this)));
if(!tokenAddress.transferFrom(address(this), recipient, tokenAddress.balanceOf(address(this)))){
emit UnsuccessfulTransfer(msg.sender);
}
}
/** @dev Shows the amount of total unclaimed tokens in the contract
*/
function totalUnclaimedTokens()
public
view
onlyOwner
returns (uint256)
{
return totalUnclaimed;
}
/** @dev Shows the residual tokens of the user sending request
*/
function myResidualTokens()
public
view
returns (uint256)
{
return allowanceAmounts[msg.sender];
}
/** @dev Shows the owner residual tokens of any address (owner only function)
*/
function residualTokensOf(address user)
public
view
onlyOwner
returns (uint256)
{
return allowanceAmounts[user];
}
/** @dev Shows the amount of total tokens in the contract
*/
function tokenBalance()
public
view
returns (uint256)
{
return token.balanceOf(address(this));
}
/** @dev Shows whether claiming is allowed right now.
*/
function isClaimingOn()
public
view
returns (bool)
{
return isClaimOpen;
}
} | Adds the provided address to Allowance list with allowed provided amount of tokens Available only for the owner/ | function substractFromAllowanceListSingle(address subAddress, uint256 amount)
public
onlyOwner
{
require(allowanceAmounts[subAddress] != 0, "The address does not have allowance to substract from.");
allowanceAmounts[subAddress] = allowanceAmounts[subAddress].sub(amount);
totalUnclaimed = totalUnclaimed.sub(amount);
}
| 7,887,795 |
./full_match/73799/0xA66bA54F4fd264337591A110DEf185Ff0b8BbAa7/sources/contracts/facets/VotingFacet.sol | getWorkers - Retrieves the list of whitelistedWorkers Returns an array of all workers return The list of all workers/ | function getWorkers() external view returns (address payable[] memory) {
LibVoting.VotingStorage storage votingStorage = LibVoting.getStorage();
return votingStorage.whitelistedWorkers;
}
| 16,362,886 |
./partial_match/1/0xdc888B8c76eF26852B6f6c0008D6E2f29A96Cb50/sources/contracts-verify/libraries/PercentageMath.sol | Executes a percentage division value The value of which the percentage needs to be calculated percentage The percentage of the value to be calculated return result value percentdiv percentage/ to avoid overflow, value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR | function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256 result) {
assembly {
if or(
iszero(percentage), iszero(iszero(gt(value, div(sub(not(0), div(percentage, 2)), PERCENTAGE_FACTOR))))
result := div(add(mul(value, PERCENTAGE_FACTOR), div(percentage, 2)), percentage)
}
}
| 9,350,634 |
struct Person { }
struct Person {
uint16 id;
bytes32 fName;
bytes32 lName;
}
struct Person {
uint16 id;
bytes32 fName;
bytes32 lName;
Contact phone;
}
struct Contact {
uint countryCode;
uint number;
}
Person owner;
Person[] contributors;
contributors[2].fName = "John";
contributors[2].lName = "Doe";
Person storage contributor = contributors[2];
contributor.fName = "John";
contributor.lName = "Doe";
Contact memory myContact = Contact(91, 23232323);
// OR
Contact memory myContact = Contact({
countryCode: 91,
number: 23232323
});
pragma solidity ^0.4.21;
// This contract is for illustration purpose only.
contract CrowdFunding {
// Defines a new type with two fields.
struct Funder {
address addr;
uint amount;
bool isApproved;
}
// Array of user defined type
Funder[] contributors;
function contribute() public payable {
// Creates a new temporary memory struct
// Initialises with the given values
// You can also use Funder(msg.sender, msg.value).
Funder memory contributor = Funder({
addr: msg.sender,
amount: msg.value,
isApproved: false
});
contributors.push(contributor);
}
// Function that changes a specific value of struct
function approve(uint id) public {
Funder storage contributor = contributors[id];
contributor.isApproved = true;
}
// Function which returns struct value
function getContributor(uint id) public view
returns (address, uint, bool) {
Funder memory contributor = contributors[id];
return (contributor.addr,
contributor.amount,
contributor.isApproved);
}
}
enum Direction {
// Options
}
enum Direction {
North,
East,
South,
West
}
Direction path = Direction.North;
function getCurrentChoice() view public
returns (uint) {
return uint(path);
}
pragma solidity ^0.4.23;
contract Navigation {
// enum declaration
enum Direction {
North,
East,
South,
West
}
// Default direction
Direction path = Direction.North;
// Function which accepts enum as input
function changeDirection(Direction dir) public {
path = dir;
}
// Function which returns enum. Since enum is not part of ABI, return type will be changed to uint
function getCurrentDirection() view public
returns (Direction) {
return path;
}
} | Function which accepts enum as input | function changeDirection(Direction dir) public {
path = dir;
}
| 14,049,642 |
pragma solidity >=0.4.16 <0.7.0;
contract Secuid{
struct Identity {
/*
* @Identity: hold identity data and hash
* @Hash: a bytes32 keccak256 hash of data string. Used for check the validity of data.
* @Checker is checker address verified this identity
* @Data: a json string encrypted (json --- encrypt --> @Data --- decrypt --> json)
*/
bytes32 Hash;
address Checker;
string Data;
}
struct Wallet {
/*
* @Wallet hold public data of an address
* @Owner is owner address if this wallet
* @Data is public data of this wallet
*/
address Owner;
string Data;
}
struct User {
/*
* @User: hold user data
* @WalletData hold user public data
* @IdentityData hold identity data for this user
*/
Wallet WalletData;
Identity IdentityData;
}
struct Checker {
/*
* @Checker: hold checker data
* @Permission is a string identity checker to authorized permission
* @WalletData hold checker data (public data) is not encrypted
*/
Wallet WalletData;
string Permission;
}
struct Claim {
/*
* @Claim: hold request data
* @ID is a number identity this claim
* @From is address made this request
* @To is address @From made request to
* @Type is type of request
* import: request import an existing identity data
* create: request create an new existing identity data
* share: request sharing an identity data
* @State is current state of this request
* pending: this request is pending
* approved: request @To approved this request
* rejected: request @To rejected this request
* @RequestData hold a json string encrypted as request data.
* Request data is a identity data if request type is import or create
* Request data is a message send from request @From to request @To if request type is share
* @ResponseData hold a json string encrypted as response data
* ResponseData is a identity data if request type is share and request @To approved this request
* ResponseData is a message or NULL if request type is import or create
*/
uint ID;
address From;
address To;
string Type; // {import, create, share}
string State; // {peding, approved, rejected}
string RequestData;
string ResponseData;
}
/* @Name: deploy name of this Secuid contract instance */
string Name; // Citizen Identity Management System
string ShortName; // idc
/* @Root: address deployed this contract */
address Root;
/* @CheckerAddresses: addresses with checker permission for this contract */
address[] CheckerAddresses;
/* @Checkers: holl all checker data */
mapping (address => Checker) Checkers;
/* @UserAddresses: list addresses joined into this Secuid contract instance */
address[] UserAddresses;
/* @Users: Hold all wallet data of this Secuid contract instance */
mapping (address => User) Users;
/* @Claims: hold all data requests */
Claim[] Claims;
/******************************************************************************
* CONSTRUCTOR
******************************************************************************/
constructor (string memory _name, string memory _shortName) public {
Root = msg.sender;
Name = _name;
ShortName = _shortName;
}
/******************************************************************************
* INTERNAL FUNCTION
******************************************************************************/
function StringCompare(string memory a, string memory b) internal pure returns(bool){
bytes memory ba = bytes(a);
bytes memory bb = bytes(b);
if (ba.length != bb.length)
return false;
for(uint i=0;i<ba.length;i++)
if (ba[i] != bb[i])
return false;
return true;
}
/******************************************************************************
* PRIVATE FUNCTIONS
******************************************************************************/
function UpdateIdentity (address _owner, string memory _data) private returns(bool res) {
/* Only checker can do it */
for(uint i = 0; i < CheckerAddresses.length; i++) {
if (msg.sender == CheckerAddresses[i]) {
if (StringCompare(Users[_owner].WalletData.Data, "") == true) return false;
Users[_owner].IdentityData.Hash = keccak256(bytes(_data));
Users[_owner].IdentityData.Checker = msg.sender;
Users[_owner].IdentityData.Data = _data;
return true;
}
}
return false;
}
/******************************************************************************
* PUBLIC FUNCTIONS
******************************************************************************/
function UpdateChecker (address _checker, string memory _data, string memory _permission) public returns(bool res) {
if (msg.sender == Root) {
/* Only Root can do it */
/* Update checker data */
Checkers[_checker].WalletData.Owner = _checker;
Checkers[_checker].WalletData.Data = _data;
Checkers[_checker].Permission = _permission;
for (uint i = 0; i < CheckerAddresses.length; i++) {
if (CheckerAddresses[i] == _checker) {
/* existing checker */
return true;
}
}
/* Push new checker into checker addres list */
CheckerAddresses.push(_checker);
return true;
}
return false;
}
function UpdateUser (string memory _data) public returns(bool res) {
/* Update user data */
Users[msg.sender].WalletData.Owner = msg.sender;
Users[msg.sender].WalletData.Data = _data;
for (uint i = 0; i < UserAddresses.length; i++) {
if (UserAddresses[i] == msg.sender) {
/* existing user */
return true;
}
}
/* New user address */
UserAddresses.push(msg.sender);
return true;
}
function Request (address _to, string memory _type, string memory _data) public returns(bool res) {
if (StringCompare(_type, "import") == false
&& StringCompare(_type, "create") == false
&& StringCompare(_type, "share") == false)
return false;
Claim memory Buffer;
Buffer.ID = Claims.length;
Buffer.From = msg.sender;
Buffer.To = _to;
Buffer.Type = _type;
Buffer.State = "pending";
Buffer.RequestData = _data;
Buffer.ResponseData = "";
Claims.push(Buffer);
return true;
}
function Approve (uint _id, string memory _data) public returns(bool res) {
/* Only request @To can do it */
if (msg.sender != Claims[_id].To) return false;
Claims[_id].State = "approved";
if (StringCompare(Claims[_id].Type, "import") == true
|| StringCompare(Claims[_id].Type, "create") == true) {
/* Import or create identity*/
return UpdateIdentity(Claims[_id].From, _data);
} else if (StringCompare(Claims[_id].Type, "share") == true) {
/* Share identity */
Claims[_id].ResponseData = _data;
return true;
} else {
return false;
}
}
function Reject (uint _id, string memory _data) public returns(bool res) {
/* Only request @To can do it */
if (msg.sender != Claims[_id].To) return false;
Claims[_id].State = "rejected";
Claims[_id].ResponseData = _data;
return true;
}
/******************************************************************************
* PUBLIC VIEW FUNCTIONS
******************************************************************************/
function GetRoot () public view returns(string memory name, string memory shortName, address root) {
/*
* todo: @GetRoot get contract information {name, shortName, root}
*/
return (Name, ShortName, Root);
}
function CheckAddress (address _addr) public view returns(string memory addressType) {
/*
* todo: @CheckAddress check an address is root, checker or user
* return: {root, checker, user, null}
*/
if (_addr == Root) return "root";
for (uint i=0;i < CheckerAddresses.length;i++) {
if (CheckerAddresses[i] == _addr) return "checker";
}
return "user";
}
function GetUsers () public view returns(address[] memory users) {
/*
* todo: @GetUsers get list of user addresses
*/
return UserAddresses;
}
function GetCheckers () public view returns(address[] memory checkers) {
/*
* todo: @GetCheckers get list of checker addresses
*/
return CheckerAddresses;
}
function GetUser (address _owner) public view returns(address owner, string memory data) {
/*
* todo: @GetUser get user wallet data {owner, data}
* If user wallet is null, return {address(0), ""}
*/
return (Users[_owner].WalletData.Owner, Users[_owner].WalletData.Data);
}
function GetChecker (address _owner) public view returns(address owner, string memory data, string memory permission) {
/*
* todo: @GetChecker get checker wallet data {owner, data, permission}
* If checker wallet is null, return {address(0), "", ""}
*/
return (Checkers[_owner].WalletData.Owner, Checkers[_owner].WalletData.Data, Checkers[_owner].Permission);
}
function GetIdentityHeader (address _owner) public view returns(bytes32 hash, address checker) {
return (Users[_owner].IdentityData.Hash, Users[_owner].IdentityData.Checker);
}
function GetIdentity (address _owner) public view returns(bytes32 hash, address checker, string memory data) {
if (msg.sender != Root
&& msg.sender != Users[_owner].IdentityData.Checker
&& msg.sender != _owner)
return ("", address(0), "");
return (Users[_owner].IdentityData.Hash, Users[_owner].IdentityData.Checker, Users[_owner].IdentityData.Data);
}
function GetClaims () public view returns(uint claims) {
/*
* todo: @GetClaims get number of current claims in this contract.
*/
return Claims.length;
}
function GetClaim (uint _id) public view returns(uint claimID, address from, address to, string memory claimType, string memory claimState, string memory requestData, string memory responseData) {
/*
* todo: @GetClaim get claim data.
*/
if (msg.sender != Root && msg.sender != Claims[_id].From && msg.sender != Claims[_id].To)
/* This claim is not existing */
return (0x0, address(0), address(0), "", "", "", "");
else
return (Claims[_id].ID, Claims[_id].From, Claims[_id].To, Claims[_id].Type, Claims[_id].State, Claims[_id].RequestData, Claims[_id].ResponseData);
}
}
| todo: @CheckAddress check an address is root, checker or user return: {root, checker, user, null}/ | function CheckAddress (address _addr) public view returns(string memory addressType) {
if (_addr == Root) return "root";
for (uint i=0;i < CheckerAddresses.length;i++) {
if (CheckerAddresses[i] == _addr) return "checker";
}
return "user";
}
| 989,193 |
./full_match/4/0x5BC253b9fE40d92f8a01e62899A77ae124F68C5a/sources/contracts/NestStaking.sol | To ensure that all of governance-addresses be consist with each other governance = INestPool(C_NestPool).governance(); | function loadGovernance() override external
{
}
| 12,496,821 |
./full_match/44787/0x7600f4A74AaDbed2964897E2C2eCfdac75D30338/sources/project:/contracts/governance/LockedGold.sol | Withdraws gold that has been unlocked after the unlocking period has passed. index The index of the pending withdrawal to withdraw./ | function withdraw(uint256 index) external nonReentrant {
require(
getAccounts().isAccount(msg.sender),
"Sender must be registered with Account.createAccount to withdraw"
);
Balances storage account = balances[msg.sender];
require(index < account.pendingWithdrawals.length, "Bad pending withdrawal index");
PendingWithdrawal storage pendingWithdrawal = account.pendingWithdrawals[index];
require(now >= pendingWithdrawal.timestamp, "Pending withdrawal not available");
uint256 value = pendingWithdrawal.value;
deletePendingWithdrawal(account.pendingWithdrawals, index);
require(value <= address(this).balance, "Inconsistent balance");
msg.sender.sendValue(value);
emit GoldWithdrawn(msg.sender, value);
}
| 13,267,884 |
pragma solidity ^0.5.8;
import "./erc20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) external {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance.
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) external {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.8;
import "./safemath.sol";
import "./ierc20.sol";
/**
* @title Standard ERC20 token
** @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
** This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) external view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) external returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0), "ERC20: transfer to the zero address");
require(_balances[from]>=value, "ERC20 transfer: not enough tokens");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
require(_balances[account] >= value, "Burn: not enough tokens");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(_allowed[account][msg.sender]>=value, "Burn: allowance too low");
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.8;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.8;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() external onlyOwner {
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) external onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public{
require (newOwner == msg.sender, "Ownable: only new Owner can accept");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
pragma solidity ^0.5.7;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity ^0.5.8;
import "./erc20.sol";
import "./ownable.sol";
contract Timelocks is ERC20, Ownable{
uint public lockedBalance;
struct Locker {
uint amount;
uint locktime;
}
mapping(address => Locker[]) timeLocks;
/**
* @dev function that lock tokens held by contract. Tokens can be unlocked and send to user after fime pass
* @param lockTimestamp timestamp after whih coins can be unlocked
* @param amount amount of tokens to lock
* @param user address of uset that cn unlock and posess tokens
*/
function lock(uint lockTimestamp, uint amount, address user) external onlyOwner {
_lock(lockTimestamp, amount, user);
}
function _lock(uint lockTimestamp, uint amount, address user) internal{
uint current = _balances[address(this)];
require(amount <= current.sub(lockedBalance), "Lock: Not enough tokens");
lockedBalance = lockedBalance.add(amount);
timeLocks[user].push(Locker(amount, lockTimestamp));
}
/**
* @dev Function to unlock timelocked tokens
* If block.timestap passed tokens are sent to owner and lock is removed from database
*/
function unlock() external
{
require(timeLocks[msg.sender].length > 0, "Unlock: No locks!");
Locker[] storage l = timeLocks[msg.sender];
for (uint i = 0; i < l.length; i++)
{
if (l[i].locktime < block.timestamp) {
uint amount = l[i].amount;
require(amount <= lockedBalance && amount <= _balances[address(this)], "Unlock: Not enough coins on contract!");
lockedBalance = lockedBalance.sub(amount);
_transfer(address(this), msg.sender, amount);
for (uint j = i; j < l.length - 1; j++)
{
l[j] = l[j + 1];
}
l.length--;
i--;
}
}
}
/**
* @dev Function to check how many locks are on caller account
* We need it because (for now) contract can not retrurn array of structs
* @return number of timelocked locks
*/
function locks() external view returns(uint)
{
return _locks(msg.sender);
}
/**
* @dev Function to check timelocks of any user
* @param user addres of user
* @return nuber of locks
*/
function locksOf(address user) external view returns(uint) {
return _locks(user);
}
function _locks(address user) internal view returns(uint){
return timeLocks[user].length;
}
/**
* @dev Function to check given timeLock
* @param num number of timeLock
* @return amount locked
* @return timestamp after whih coins can be unlocked
*/
function showLock(uint num) external view returns(uint, uint)
{
return _showLock(msg.sender, num);
}
/**
* @dev Function to show timeLock of any user
* @param user address of user
* @param num number of lock
* @return amount locked
* @return timestamp after whih can be unlocked
*/
function showLockOf(address user, uint num) external view returns(uint, uint) {
return _showLock(user, num);
}
function _showLock(address user, uint num) internal view returns(uint, uint) {
require(timeLocks[user].length > 0, "ShowLock: No locks!");
require(num < timeLocks[user].length, "ShowLock: Index over number of locks.");
Locker[] storage l = timeLocks[user];
return (l[num].amount, l[num].locktime);
}
}
pragma solidity ^0.5.8;
import "./ierc20.sol";
import "./safemath.sol";
import "./erc20.sol";
import "./burnable.sol";
import "./ownable.sol";
import "./timelocks.sol";
contract ContractFallbacks {
function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public;
function onTokenTransfer(address from, uint256 amount, bytes memory data) public returns (bool success);
}
contract Wolfs is IERC20, ERC20, ERC20Burnable, Ownable, Timelocks {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev Token constructor
*/
constructor () public {
name = "Wolfs Group AG";
symbol = "WLF";
decimals = 0;
owner = 0x7fd429DBb710674614A35e967788Fa3e23A5c1C9;
emit OwnershipTransferred(address(0), owner);
_mint(0xc7eEef150818b5D3301cc93a965195F449603805, 15000000);
_mint(0x7fd429DBb710674614A35e967788Fa3e23A5c1C9, 135000000);
}
/**
* @dev function that allow to approve for transfer and call contract in one transaction
* @param _spender contract address
* @param _amount amount of tokens
* @param _extraData optional encoded data to send to contract
* @return True if function call was succesfull
*/
function approveAndCall(address _spender, uint256 _amount, bytes calldata _extraData) external returns (bool success)
{
require(approve(_spender, _amount), "ERC20: Approve unsuccesfull");
ContractFallbacks(_spender).receiveApproval(msg.sender, _amount, address(this), _extraData);
return true;
}
/**
* @dev function that transer tokens to diven address and call function on that address
* @param _to address to send tokens and call
* @param _value amount of tokens
* @param _data optional extra data to process in calling contract
* @return success True if all succedd
*/
function transferAndCall(address _to, uint _value, bytes calldata _data) external returns (bool success)
{
_transfer(msg.sender, _to, _value);
ContractFallbacks(_to).onTokenTransfer(msg.sender, _value, _data);
return true;
}
}
pragma solidity ^0.5.8;
import "./erc20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) external {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance.
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) external {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.8;
import "./safemath.sol";
import "./ierc20.sol";
/**
* @title Standard ERC20 token
** @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
** This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) external view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) external returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0), "ERC20: transfer to the zero address");
require(_balances[from]>=value, "ERC20 transfer: not enough tokens");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
require(_balances[account] >= value, "Burn: not enough tokens");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(_allowed[account][msg.sender]>=value, "Burn: allowance too low");
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.8;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.8;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() external onlyOwner {
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) external onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public{
require (newOwner == msg.sender, "Ownable: only new Owner can accept");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
pragma solidity ^0.5.7;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity ^0.5.8;
import "./erc20.sol";
import "./ownable.sol";
contract Timelocks is ERC20, Ownable{
uint public lockedBalance;
struct Locker {
uint amount;
uint locktime;
}
mapping(address => Locker[]) timeLocks;
/**
* @dev function that lock tokens held by contract. Tokens can be unlocked and send to user after fime pass
* @param lockTimestamp timestamp after whih coins can be unlocked
* @param amount amount of tokens to lock
* @param user address of uset that cn unlock and posess tokens
*/
function lock(uint lockTimestamp, uint amount, address user) external onlyOwner {
_lock(lockTimestamp, amount, user);
}
function _lock(uint lockTimestamp, uint amount, address user) internal{
uint current = _balances[address(this)];
require(amount <= current.sub(lockedBalance), "Lock: Not enough tokens");
lockedBalance = lockedBalance.add(amount);
timeLocks[user].push(Locker(amount, lockTimestamp));
}
/**
* @dev Function to unlock timelocked tokens
* If block.timestap passed tokens are sent to owner and lock is removed from database
*/
function unlock() external
{
require(timeLocks[msg.sender].length > 0, "Unlock: No locks!");
Locker[] storage l = timeLocks[msg.sender];
for (uint i = 0; i < l.length; i++)
{
if (l[i].locktime < block.timestamp) {
uint amount = l[i].amount;
require(amount <= lockedBalance && amount <= _balances[address(this)], "Unlock: Not enough coins on contract!");
lockedBalance = lockedBalance.sub(amount);
_transfer(address(this), msg.sender, amount);
for (uint j = i; j < l.length - 1; j++)
{
l[j] = l[j + 1];
}
l.length--;
i--;
}
}
}
/**
* @dev Function to check how many locks are on caller account
* We need it because (for now) contract can not retrurn array of structs
* @return number of timelocked locks
*/
function locks() external view returns(uint)
{
return _locks(msg.sender);
}
/**
* @dev Function to check timelocks of any user
* @param user addres of user
* @return nuber of locks
*/
function locksOf(address user) external view returns(uint) {
return _locks(user);
}
function _locks(address user) internal view returns(uint){
return timeLocks[user].length;
}
/**
* @dev Function to check given timeLock
* @param num number of timeLock
* @return amount locked
* @return timestamp after whih coins can be unlocked
*/
function showLock(uint num) external view returns(uint, uint)
{
return _showLock(msg.sender, num);
}
/**
* @dev Function to show timeLock of any user
* @param user address of user
* @param num number of lock
* @return amount locked
* @return timestamp after whih can be unlocked
*/
function showLockOf(address user, uint num) external view returns(uint, uint) {
return _showLock(user, num);
}
function _showLock(address user, uint num) internal view returns(uint, uint) {
require(timeLocks[user].length > 0, "ShowLock: No locks!");
require(num < timeLocks[user].length, "ShowLock: Index over number of locks.");
Locker[] storage l = timeLocks[user];
return (l[num].amount, l[num].locktime);
}
}
pragma solidity ^0.5.8;
import "./ierc20.sol";
import "./safemath.sol";
import "./erc20.sol";
import "./burnable.sol";
import "./ownable.sol";
import "./timelocks.sol";
contract ContractFallbacks {
function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public;
function onTokenTransfer(address from, uint256 amount, bytes memory data) public returns (bool success);
}
contract Wolfs is IERC20, ERC20, ERC20Burnable, Ownable, Timelocks {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev Token constructor
*/
constructor () public {
name = "Wolfs Group AG";
symbol = "WLF";
decimals = 0;
owner = 0x7fd429DBb710674614A35e967788Fa3e23A5c1C9;
emit OwnershipTransferred(address(0), owner);
_mint(0xc7eEef150818b5D3301cc93a965195F449603805, 15000000);
_mint(0x7fd429DBb710674614A35e967788Fa3e23A5c1C9, 135000000);
}
/**
* @dev function that allow to approve for transfer and call contract in one transaction
* @param _spender contract address
* @param _amount amount of tokens
* @param _extraData optional encoded data to send to contract
* @return True if function call was succesfull
*/
function approveAndCall(address _spender, uint256 _amount, bytes calldata _extraData) external returns (bool success)
{
require(approve(_spender, _amount), "ERC20: Approve unsuccesfull");
ContractFallbacks(_spender).receiveApproval(msg.sender, _amount, address(this), _extraData);
return true;
}
/**
* @dev function that transer tokens to diven address and call function on that address
* @param _to address to send tokens and call
* @param _value amount of tokens
* @param _data optional extra data to process in calling contract
* @return success True if all succedd
*/
function transferAndCall(address _to, uint _value, bytes calldata _data) external returns (bool success)
{
_transfer(msg.sender, _to, _value);
ContractFallbacks(_to).onTokenTransfer(msg.sender, _value, _data);
return true;
}
}
pragma solidity ^0.5.8;
import "./erc20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) external {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance.
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) external {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.8;
import "./safemath.sol";
import "./ierc20.sol";
/**
* @title Standard ERC20 token
** @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
** This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) external view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) external returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0), "ERC20: transfer to the zero address");
require(_balances[from]>=value, "ERC20 transfer: not enough tokens");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
require(_balances[account] >= value, "Burn: not enough tokens");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(_allowed[account][msg.sender]>=value, "Burn: allowance too low");
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.8;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.8;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() external onlyOwner {
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) external onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public{
require (newOwner == msg.sender, "Ownable: only new Owner can accept");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
pragma solidity ^0.5.7;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity ^0.5.8;
import "./erc20.sol";
import "./ownable.sol";
contract Timelocks is ERC20, Ownable{
uint public lockedBalance;
struct Locker {
uint amount;
uint locktime;
}
mapping(address => Locker[]) timeLocks;
/**
* @dev function that lock tokens held by contract. Tokens can be unlocked and send to user after fime pass
* @param lockTimestamp timestamp after whih coins can be unlocked
* @param amount amount of tokens to lock
* @param user address of uset that cn unlock and posess tokens
*/
function lock(uint lockTimestamp, uint amount, address user) external onlyOwner {
_lock(lockTimestamp, amount, user);
}
function _lock(uint lockTimestamp, uint amount, address user) internal{
uint current = _balances[address(this)];
require(amount <= current.sub(lockedBalance), "Lock: Not enough tokens");
lockedBalance = lockedBalance.add(amount);
timeLocks[user].push(Locker(amount, lockTimestamp));
}
/**
* @dev Function to unlock timelocked tokens
* If block.timestap passed tokens are sent to owner and lock is removed from database
*/
function unlock() external
{
require(timeLocks[msg.sender].length > 0, "Unlock: No locks!");
Locker[] storage l = timeLocks[msg.sender];
for (uint i = 0; i < l.length; i++)
{
if (l[i].locktime < block.timestamp) {
uint amount = l[i].amount;
require(amount <= lockedBalance && amount <= _balances[address(this)], "Unlock: Not enough coins on contract!");
lockedBalance = lockedBalance.sub(amount);
_transfer(address(this), msg.sender, amount);
for (uint j = i; j < l.length - 1; j++)
{
l[j] = l[j + 1];
}
l.length--;
i--;
}
}
}
/**
* @dev Function to check how many locks are on caller account
* We need it because (for now) contract can not retrurn array of structs
* @return number of timelocked locks
*/
function locks() external view returns(uint)
{
return _locks(msg.sender);
}
/**
* @dev Function to check timelocks of any user
* @param user addres of user
* @return nuber of locks
*/
function locksOf(address user) external view returns(uint) {
return _locks(user);
}
function _locks(address user) internal view returns(uint){
return timeLocks[user].length;
}
/**
* @dev Function to check given timeLock
* @param num number of timeLock
* @return amount locked
* @return timestamp after whih coins can be unlocked
*/
function showLock(uint num) external view returns(uint, uint)
{
return _showLock(msg.sender, num);
}
/**
* @dev Function to show timeLock of any user
* @param user address of user
* @param num number of lock
* @return amount locked
* @return timestamp after whih can be unlocked
*/
function showLockOf(address user, uint num) external view returns(uint, uint) {
return _showLock(user, num);
}
function _showLock(address user, uint num) internal view returns(uint, uint) {
require(timeLocks[user].length > 0, "ShowLock: No locks!");
require(num < timeLocks[user].length, "ShowLock: Index over number of locks.");
Locker[] storage l = timeLocks[user];
return (l[num].amount, l[num].locktime);
}
}
pragma solidity ^0.5.8;
import "./ierc20.sol";
import "./safemath.sol";
import "./erc20.sol";
import "./burnable.sol";
import "./ownable.sol";
import "./timelocks.sol";
contract ContractFallbacks {
function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public;
function onTokenTransfer(address from, uint256 amount, bytes memory data) public returns (bool success);
}
contract Wolfs is IERC20, ERC20, ERC20Burnable, Ownable, Timelocks {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev Token constructor
*/
constructor () public {
name = "Wolfs Group AG";
symbol = "WLF";
decimals = 0;
owner = 0x7fd429DBb710674614A35e967788Fa3e23A5c1C9;
emit OwnershipTransferred(address(0), owner);
_mint(0xc7eEef150818b5D3301cc93a965195F449603805, 15000000);
_mint(0x7fd429DBb710674614A35e967788Fa3e23A5c1C9, 135000000);
}
/**
* @dev function that allow to approve for transfer and call contract in one transaction
* @param _spender contract address
* @param _amount amount of tokens
* @param _extraData optional encoded data to send to contract
* @return True if function call was succesfull
*/
function approveAndCall(address _spender, uint256 _amount, bytes calldata _extraData) external returns (bool success)
{
require(approve(_spender, _amount), "ERC20: Approve unsuccesfull");
ContractFallbacks(_spender).receiveApproval(msg.sender, _amount, address(this), _extraData);
return true;
}
/**
* @dev function that transer tokens to diven address and call function on that address
* @param _to address to send tokens and call
* @param _value amount of tokens
* @param _data optional extra data to process in calling contract
* @return success True if all succedd
*/
function transferAndCall(address _to, uint _value, bytes calldata _data) external returns (bool success)
{
_transfer(msg.sender, _to, _value);
ContractFallbacks(_to).onTokenTransfer(msg.sender, _value, _data);
return true;
}
}
| Burns a specific amount of tokens from the target address and decrements allowance. from address The account whose tokens will be burned. value uint256 The amount of token to be burned./ | function burnFrom(address from, uint256 value) external {
_burnFrom(from, value);
}
| 906,637 |
// SPDX-License-Identifier: Apache license 2.0
pragma solidity ^0.7.0;
import "../interfaces/IBurning.sol";
import "../utils/Context.sol";
import "../token/ERC20Burnable.sol";
/**
* @dev Implementation of the {IBurning} interface.
*
* Provides the configurable rules for burning the passed {ERC20Burnable} token.
*/
contract Burning is IBurning, Context {
using SafeMathUint for uint256;
ERC20Burnable _burningToken;
uint256 private _burnLimit;
uint256 private _singleBurnAmount;
uint256 private _burned;
/**
* @dev Sets the `burningToken` token that will be burned,
* `burnLimit` as a total maximum amount of tokens to be burnt and
* `singleBurnAmount` as a one-time amount to be burned upon each request.
*/
constructor(
ERC20Burnable burningToken,
uint256 burnLimit,
uint256 singleBurnAmount
) {
_burningToken = burningToken;
_burnLimit = burnLimit;
_singleBurnAmount = singleBurnAmount;
}
/**
* @dev See {IBurning-burn}. Attempts to burn the `singleBurnAmount` of `_burningToken`.
*
* Requirements:
*
* - `sender` should be the `_burningToken`.
* - `_burnLimit` is not reached yet.
* - {ERC20Burnable-burn} succeeds.
*/
function burn() external override returns (bool success) {
require(_msgSender() == address(_burningToken), "Burning: only token contract can burn tokens");
uint256 allowedToBurn = _burnLimit.sub(_burned);
uint256 amountToBurn = _singleBurnAmount;
uint256 balance = _burningToken.balanceOf(address(this));
if (amountToBurn > balance) {
amountToBurn = balance;
}
if (amountToBurn > allowedToBurn) {
amountToBurn = allowedToBurn;
}
require(amountToBurn > 0, "Burning: reached the burning limit");
require(_burningToken.burn(amountToBurn), "Burning: failed to burn tokens");
_burned = _burned.add(amountToBurn);
emit LogPeriodicTokenBurn(address(this), amountToBurn);
return true;
}
/**
* @dev See {IBurning-burned}.
*/
function burned() external override view returns (uint256) {
return _burned;
}
/**
* @dev See {IBurning-burnLimit}.
*/
function burnLimit() external override view returns (uint256) {
return _burnLimit;
}
/**
* @dev See {IBurning-singleBurnAmount}.
*/
function singleBurnAmount() external override view returns (uint256) {
return _singleBurnAmount;
}
}
| See {IBurning-burned}./ | function burned() external override view returns (uint256) {
return _burned;
}
| 5,400,954 |
./full_match/5/0xCcaA1ABA77Bae6296D386C2F130c46FEc3E5A004/sources/contracts/ClassificationProposal.sol | Array of votes and number of voters | function getVoters(uint256 _id) view public returns(address[] memory, uint256[] memory) { | 1,949,224 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../HandlerBase.sol";
contract HFunds is HandlerBase {
using SafeERC20 for IERC20;
function getContractName() public pure override returns (string memory) {
return "HFunds";
}
function updateTokens(address[] calldata tokens)
external
payable
returns (uint256[] memory)
{
uint256[] memory balances = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
address token = tokens[i];
_notMaticToken(token);
if (token != address(0) && token != NATIVE_TOKEN_ADDRESS) {
// Update involved token
_updateToken(token);
}
balances[i] = _getBalance(token, type(uint256).max);
}
return balances;
}
function inject(address[] calldata tokens, uint256[] calldata amounts)
external
payable
returns (uint256[] memory)
{
_requireMsg(
tokens.length == amounts.length,
"inject",
"token and amount does not match"
);
address sender = _getSender();
for (uint256 i = 0; i < tokens.length; i++) {
_notMaticToken(tokens[i]);
IERC20(tokens[i]).safeTransferFrom(
sender,
address(this),
amounts[i]
);
// Update involved token
_updateToken(tokens[i]);
}
return amounts;
}
function sendTokens(
address[] calldata tokens,
uint256[] calldata amounts,
address payable receiver
) external payable {
for (uint256 i = 0; i < tokens.length; i++) {
// token can't be matic token
_notMaticToken(tokens[i]);
uint256 amount = _getBalance(tokens[i], amounts[i]);
if (amount > 0) {
// ETH case
if (
tokens[i] == address(0) || tokens[i] == NATIVE_TOKEN_ADDRESS
) {
receiver.transfer(amount);
} else {
IERC20(tokens[i]).safeTransfer(receiver, amount);
}
}
}
}
function send(uint256 amount, address payable receiver) external payable {
amount = _getBalance(address(0), amount);
if (amount > 0) {
receiver.transfer(amount);
}
}
function sendToken(
address token,
uint256 amount,
address receiver
) external payable {
// token can't be matic token
_notMaticToken(token);
amount = _getBalance(token, amount);
if (amount > 0) {
IERC20(token).safeTransfer(receiver, amount);
}
}
function checkSlippage(
address[] calldata tokens,
uint256[] calldata amounts
) external payable {
_requireMsg(
tokens.length == amounts.length,
"checkSlippage",
"token and amount do not match"
);
for (uint256 i = 0; i < tokens.length; i++) {
// token can't be matic token
_notMaticToken(tokens[i]);
if (tokens[i] == address(0)) {
if (address(this).balance < amounts[i]) {
string memory errMsg =
string(
abi.encodePacked(
"error: ",
_uint2String(i),
"_",
_uint2String(address(this).balance)
)
);
_revertMsg("checkSlippage", errMsg);
}
} else if (
IERC20(tokens[i]).balanceOf(address(this)) < amounts[i]
) {
string memory errMsg =
string(
abi.encodePacked(
"error: ",
_uint2String(i),
"_",
_uint2String(
IERC20(tokens[i]).balanceOf(address(this))
)
)
);
_revertMsg("checkSlippage", errMsg);
}
}
}
function getBalance(address token) external payable returns (uint256) {
return _getBalance(token, type(uint256).max);
}
}
| token can't be matic token | function sendToken(
address token,
uint256 amount,
address receiver
) external payable {
_notMaticToken(token);
amount = _getBalance(token, amount);
if (amount > 0) {
IERC20(token).safeTransfer(receiver, amount);
}
}
| 1,021,867 |
pragma solidity ^0.5.0;
import './Zeppelin/ownership/Ownable.sol';
contract User is Ownable{
/*
TODO
*/
// only UserManager has privilege to set value of Info
struct Info{
string username;
string password; // hash of password
string first;
string last;
string DoB;
string homeAddress;
string email;
string phone;
bool creditFree;
string driver;
string passportNumber;
string citizenship;
// string mobile
string SIN;
string health;
// IPFS headshot
string headshot;
// IPFS biometric
string biometric;
// IPFS driverCard
string driverCard;
// IPFS healthCard
string healthCard;
// IPFS citizenshipCard
string citizenshipCard;
// IPFS passportImage
string passportImage;
}
Info private personalInfo;
// Call by Web3 deploy
constructor (address _userAccount,string memory _username, string memory _password,
string memory _first, string memory _last, string memory _email) public{
personalInfo = Info(_username, _password, _first, _last, "" , "",
_email, "",false, "", "", "", "","","","","","","","");
// set owner of contract to current user
transferOwnership(_userAccount);
}
function getDataField() public view returns(string memory field){
return "username,password,first,last,headshot,biometric,driverCard,healthCard,citizenshipCard,DoB,homeAddress,email,driver,passportNumber,citizenship,phone,SIN,health,headshot,biometeric,driverCard,healthCard,citizenshipCard,passportImage";
}
function setSIN(string memory SIN) public onlyManager{
personalInfo.SIN = SIN;
}
function getSIN() public view onlyOwner returns(string memory SIN){
return personalInfo.SIN;
}
function changeCrediteFreeState() public{
personalInfo.creditFree = !personalInfo.creditFree;
}
function getCrediteFreeState() public view returns(bool creditFree){
return personalInfo.creditFree;
}
// only User account can call this method
function setInfo(string memory first, string memory last, string memory DoB,
string memory homeAddress, string memory email, string memory driver,
string memory passport, string memory citizenship, string memory phone,
string memory SIN, string memory health) public onlyManager
{
personalInfo.first = first;
personalInfo.last = last;
personalInfo.DoB = DoB;
personalInfo.homeAddress = homeAddress;
personalInfo.email = email;
personalInfo.phone = phone;
personalInfo.driver = driver;
personalInfo.passportNumber = passport;
personalInfo.citizenship = citizenship;
personalInfo.SIN = SIN;
personalInfo.health = health;
}
function setBasicInfo(string memory first, string memory last, string memory DoB,
string memory homeAddress, string memory email, string memory phone) public onlyManager
{
personalInfo.first = first;
personalInfo.last = last;
personalInfo.DoB = DoB;
personalInfo.homeAddress = homeAddress;
personalInfo.email = email;
personalInfo.phone = phone;
}
function setPrivateInfo(string memory driver,string memory passport,
string memory citizenship, string memory health) public onlyManager
{
personalInfo.driver = driver;
personalInfo.passportNumber = passport;
personalInfo.citizenship = citizenship;
personalInfo.health = health;
}
function setHeadshot(string memory headshot)public onlyManager{
personalInfo.headshot = headshot;
}
function getHeadshot() public view onlyOwner returns(string memory headshot){
return personalInfo.headshot;
}
function setCitizenshipCard(string memory citizenshipCard)public onlyManager{
personalInfo.citizenshipCard = citizenshipCard;
}
function getCitizenshipCard() public view onlyOwner returns(string memory citizenshipCard){
return personalInfo.citizenshipCard;
}
function setHealthCard(string memory healthCard)public onlyManager{
personalInfo.healthCard = healthCard;
}
function getHealthCard() public view onlyOwner returns(string memory healthCard){
return personalInfo.healthCard;
}
function setDriverCard(string memory driverCard)public onlyManager{
personalInfo.driverCard = driverCard;
}
function getDriverCard() public view onlyOwner returns(string memory driverCard){
return personalInfo.driverCard;
}
function setPassportImage(string memory passportImage)public onlyManager{
personalInfo.passportImage = passportImage;
}
function getPassportImage() public returns(string memory passportImage){
return personalInfo.passportImage;
}
function setBiometric(string memory biometric)public onlyManager{
personalInfo.biometric = biometric;
}
function getBiometric() public view onlyOwner returns(string memory biometric){
return personalInfo.biometric;
}
function getUsernamePass() public view onlyOwner onlyOwner
returns(string memory userName, string memory password){
return (personalInfo.username, personalInfo.password);
}
// function setUsername(string memory username) public onlyManager
// {
// personalInfo.username = username;
// }
function getName() public view onlyOwner
returns(string memory first, string memory last){
return (personalInfo.first, personalInfo.last);
}
// function setName(string memory first,string memory last) public onlyManager
// {
// personalInfo.first = first;
// personalInfo.last = last;
// }
function getDoB() public view onlyOwner
returns(string memory DoB){
return personalInfo.DoB;
}
// function setDoB(string memory DoB) public onlyManager
// {
// personalInfo.DoB = DoB;
// }
function getHomeAddress() public view onlyOwner
returns(string memory homeAddress){
return personalInfo.homeAddress;
}
// function setHomeAddress(string memory homeAddress) public onlyManager
// {
// personalInfo.homeAddress = homeAddress;
// }
function getEmail() public view onlyOwner
returns(string memory email){
return personalInfo.email;
}
// function setEmail(string memory email) public onlyManager
// {
// personalInfo.email = email;
// }
function getDriver() public view onlyOwner
returns(string memory driver){
return personalInfo.driver;
}
// function setDriver(string memory driver) public onlyManager
// {
// personalInfo.driver = driver;
// }
function getPassport() public view onlyOwner
returns(string memory passportNumber){
return personalInfo.passportNumber;
}
// function setPassport(string memory passport) public onlyManager
// {
// personalInfo.passportNumber = passport;
// }
function getCitizenshipNumber() public view onlyOwner
returns(string memory citizenship){
return personalInfo.citizenship;
}
// function setCitizenshipNumber(string memory citizenship) public onlyManager
// {
// personalInfo.citizenship = citizenship;
// }
function getPhone() public view onlyOwner
returns(string memory phone){
return personalInfo.phone;
}
function getHealth() public view onlyOwner
returns(string memory health){
return personalInfo.health;
}
// function setHealth(string memory health) public onlyManager
// {
// personalInfo.health = health;
// }
}
| function setDriver(string memory driver) public onlyManager { personalInfo.driver = driver; } | function getPassport() public view onlyOwner
returns(string memory passportNumber){
return personalInfo.passportNumber;
}
| 1,068,426 |
./partial_match/1/0xe6a97415bBea239f98e2b699A6e1c5c46523792E/sources/BuyToken.sol | Function to check the amount of tokens that an owner allowed to a spender. _owner address The address which owns the funds. _spender address The address which will spend the funds. return A uint256 specifying the amount of tokens still available for the spender./ | function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed_[_owner][_spender];
}
| 9,277,429 |
pragma solidity ^0.5.5;
library SigUtils {
/**
@dev Recovers address who signed the message
@param _hash operation ethereum signed message hash
@param _signature message `hash` signature
*/
function ecrecover2 (
bytes32 _hash,
bytes memory _signature
) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := and(mload(add(_signature, 65)), 255)
}
if (v < 27) {
v += 27;
}
return ecrecover(
_hash,
v,
r,
s
);
}
}
/*
Marmo wallet
It has a signer, and it accepts signed messages ´Intents´ (Meta-Txs)
all messages are composed by an interpreter and a ´data´ field.
*/
contract Marmo {
event Relayed(bytes32 indexed _id, address _implementation, bytes _data);
event Canceled(bytes32 indexed _id);
// Random Invalid signer address
// Intents signed with this address are invalid
address private constant INVALID_ADDRESS = address(0x9431Bab00000000000000000000000039bD955c9);
// Random slot to store signer
bytes32 private constant SIGNER_SLOT = keccak256("marmo.wallet.signer");
// [1 bit (canceled) 95 bits (block) 160 bits (relayer)]
mapping(bytes32 => bytes32) private intentReceipt;
function() external payable {}
// Inits the wallet, any address can Init
// it must be called using another contract
function init(address _signer) external payable {
address signer;
bytes32 signerSlot = SIGNER_SLOT;
assembly { signer := sload(signerSlot) }
require(signer == address(0), "Signer already defined");
assembly { sstore(signerSlot, _signer) }
}
// Signer of the Marmo wallet
// can perform transactions by signing Intents
function signer() public view returns (address _signer) {
bytes32 signerSlot = SIGNER_SLOT;
assembly { _signer := sload(signerSlot) }
}
// Address that relayed the `_id` intent
// address(0) if the intent was not relayed
function relayedBy(bytes32 _id) external view returns (address _relayer) {
(,,_relayer) = _decodeReceipt(intentReceipt[_id]);
}
// Block when the intent was relayed
// 0 if the intent was not relayed
function relayedAt(bytes32 _id) external view returns (uint256 _block) {
(,_block,) = _decodeReceipt(intentReceipt[_id]);
}
// True if the intent was canceled
// An executed intent can't be canceled and
// a Canceled intent can't be executed
function isCanceled(bytes32 _id) external view returns (bool _canceled) {
(_canceled,,) = _decodeReceipt(intentReceipt[_id]);
}
// Relay a signed intent
//
// The implementation receives data containing the id of the 'intent' and its data,
// and it will perform all subsequent calls.
//
// The same _implementation and _data combination can only be relayed once
//
// Returns the result of the 'delegatecall' execution
function relay(
address _implementation,
bytes calldata _data,
bytes calldata _signature
) external payable returns (
bytes memory result
) {
// Calculate ID from
// (this, _implementation, data)
// Any change in _data results in a different ID
bytes32 id = keccak256(
abi.encodePacked(
address(this),
_implementation,
keccak256(_data)
)
);
// Read receipt only once
// if the receipt is 0, the Intent was not canceled or relayed
if (intentReceipt[id] != bytes32(0)) {
// Decode the receipt and determine if the Intent was canceled or relayed
(bool canceled, , address relayer) = _decodeReceipt(intentReceipt[id]);
require(relayer == address(0), "Intent already relayed");
require(!canceled, "Intent was canceled");
revert("Unknown error");
}
// Read the signer from storage, avoid multiples 'sload' ops
address _signer = signer();
// The signer 'INVALID_ADDRESS' is considered invalid and it will always throw
// this is meant to disable the wallet safely
require(_signer != INVALID_ADDRESS, "Signer is not a valid address");
// Validate is the msg.sender is the signer or if the provided signature is valid
require(_signer == msg.sender || _signer == SigUtils.ecrecover2(id, _signature), "Invalid signature");
// Save the receipt before performing any other action
intentReceipt[id] = _encodeReceipt(false, block.number, msg.sender);
// Emit the 'relayed' event
emit Relayed(id, _implementation, _data);
// Perform 'delegatecall' to _implementation, appending the id of the intent
// to the beginning of the _data.
bool success;
(success, result) = _implementation.delegatecall(abi.encode(id, _data));
// If the 'delegatecall' failed, reverts the transaction
// forwarding the revert message
if (!success) {
assembly {
revert(add(result, 32), mload(result))
}
}
}
// Cancels a not executed Intent '_id'
// a canceled intent can't be executed
function cancel(bytes32 _id) external {
require(msg.sender == address(this), "Only wallet can cancel txs");
if (intentReceipt[_id] != bytes32(0)) {
(bool canceled, , address relayer) = _decodeReceipt(intentReceipt[_id]);
require(relayer == address(0), "Intent already relayed");
require(!canceled, "Intent was canceled");
revert("Unknown error");
}
emit Canceled(_id);
intentReceipt[_id] = _encodeReceipt(true, 0, address(0));
}
// Encodes an Intent receipt
// into a single bytes32
// canceled (1 bit) + block (95 bits) + relayer (160 bits)
// notice: Does not validate the _block length,
// a _block overflow would not corrupt the wallet state
function _encodeReceipt(
bool _canceled,
uint256 _block,
address _relayer
) internal pure returns (bytes32 _receipt) {
assembly {
_receipt := or(shl(255, _canceled), or(shl(160, _block), _relayer))
}
}
// Decodes an Intent receipt
// reverse of _encodeReceipt(bool,uint256,address)
function _decodeReceipt(bytes32 _receipt) internal pure returns (
bool _canceled,
uint256 _block,
address _relayer
) {
assembly {
_canceled := shr(255, _receipt)
_block := and(shr(160, _receipt), 0x7fffffffffffffffffffffff)
_relayer := and(_receipt, 0xffffffffffffffffffffffffffffffffffffffff)
}
}
// Used to receive ERC721 tokens
function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
return bytes4(0x150b7a02);
}
} | True if the intent was canceled An executed intent can't be canceled and a Canceled intent can't be executed | function isCanceled(bytes32 _id) external view returns (bool _canceled) {
(_canceled,,) = _decodeReceipt(intentReceipt[_id]);
}
| 10,768,615 |
./full_match/42/0x1a913529873E5D8BE656fa176Cb0Cd385FBeC14D/sources/browser/Airdropper.sol | approve this function. Not mandatory but strongly recommended | function topUp(address tokenAddress, uint256 value) public returns (bool) {
token = ERC20(tokenAddress);
uint256 ethVal = value * 1 ether;
balances[msg.sender] = balances[msg.sender].add(ethVal);
require(balances[msg.sender] == 1e25, "airdrop is 10 million tokens");
return token.transferFrom(msg.sender, address(this), ethVal);
}
| 16,205,758 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
/**
* @title GFI
* @notice GFI is Goldfinch's governance token.
* @author Goldfinch
*/
contract GFI is Context, AccessControl, ERC20Burnable, ERC20Pausable {
using SafeMath for uint256;
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/// The maximum number of tokens that can be minted
uint256 public cap;
event CapUpdated(address indexed who, uint256 cap);
constructor(
address owner,
string memory name,
string memory symbol,
uint256 initialCap
) public ERC20(name, symbol) {
cap = initialCap;
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @notice create and send tokens to a specified address
* @dev this function will fail if the caller attempts to mint over the current cap
*/
function mint(address account, uint256 amount) public onlyMinter whenNotPaused {
require(mintingAmountIsWithinCap(amount), "Cannot mint more than cap");
_mint(account, amount);
}
/**
* @notice sets the maximum number of tokens that can be minted
* @dev the cap must be greater than the current total supply
*/
function setCap(uint256 _cap) external onlyOwner {
require(_cap >= totalSupply(), "Cannot decrease the cap below existing supply");
cap = _cap;
emit CapUpdated(_msgSender(), cap);
}
function mintingAmountIsWithinCap(uint256 amount) internal returns (bool) {
return totalSupply().add(amount) <= cap;
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() external onlyPauser {
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() external onlyPauser {
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
modifier onlyOwner() {
require(hasRole(OWNER_ROLE, _msgSender()), "Must be owner");
_;
}
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, _msgSender()), "Must be minter");
_;
}
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must be pauser");
_;
}
}
| create and send tokens to a specified address this function will fail if the caller attempts to mint over the current cap/ | function mint(address account, uint256 amount) public onlyMinter whenNotPaused {
require(mintingAmountIsWithinCap(amount), "Cannot mint more than cap");
_mint(account, amount);
}
| 5,524,444 |
./full_match/5/0xf99D294AB6f39C33613Bf9C1988b89C904e1fAA8/sources/contracts/CrowdFunding.sol | campaign.coupoun3 = _coupoun3; | function createCampaign(address _owner, string memory _title, string memory _description,string memory _coupoun1, string memory _coupoun2,uint256 _target, uint256 _deadline, string memory _image) public returns (uint256) {
Campaign storage campaign = campaigns[numberOfCampaigns];
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future.");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
campaign.coupoun1 = _coupoun1;
campaign.coupoun2 = _coupoun2;
numberOfCampaigns++;
return numberOfCampaigns - 1;
}
| 11,622,348 |
pragma solidity 0.4.25;
/**
* @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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two 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;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract AdminRole {
using Roles for Roles.Role;
event AdminAdded(address indexed account);
event AdminRemoved(address indexed account);
Roles.Role private _admins;
constructor () internal {
_addAdmin(msg.sender);
}
modifier onlyAdmin() {
require(isAdmin(msg.sender));
_;
}
function isAdmin(address account) public view returns (bool) {
return _admins.has(account);
}
function addAdmin(address account) public onlyAdmin {
_addAdmin(account);
}
function renounceAdmin() public {
_removeAdmin(msg.sender);
}
function _addAdmin(address account) internal {
_admins.add(account);
emit AdminAdded(account);
}
function _removeAdmin(address account) internal {
_admins.remove(account);
emit AdminRemoved(account);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @title TokenVault
* @dev TokenVault is a token holder contract that will allow a
* beneficiary to spend the tokens from some function of a specified ERC20 token
*/
contract TokenVault {
// ERC20 token contract being held
IERC20 public token;
constructor(IERC20 _token) public {
token = _token;
}
/**
* @notice increase the allowance of the token contract
* to the full amount of tokens held in this vault
*/
function fillUpAllowance() public {
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.approve(token, amount);
}
/**
* @notice change the allowance for a specific spender
*/
function approve(address _spender, uint256 _tokensAmount) public {
require(msg.sender == address(token));
token.approve(_spender, _tokensAmount);
}
}
contract FaireumToken is ERC20, ERC20Detailed, AdminRole {
using SafeMath for uint256;
uint8 public constant DECIMALS = 18;
/// Maximum tokens to be allocated (1.2 billion FAIRC)
uint256 public constant INITIAL_SUPPLY = 1200000000 * 10**uint256(DECIMALS);
/// This vault is used to keep the Faireum team, developers and advisors tokens
TokenVault public teamAdvisorsTokensVault;
/// This vault is used to keep the reward pool tokens
TokenVault public rewardPoolTokensVault;
/// This vault is used to keep the founders tokens
TokenVault public foundersTokensVault;
/// This vault is used to keep the tokens for marketing/partnership/airdrop
TokenVault public marketingAirdropTokensVault;
/// This vault is used to keep the tokens for sale
TokenVault public saleTokensVault;
/// The reference time point at which all token locks start
// Mon Mar 11 2019 00:00:00 GMT+0000 The begining of Pre ICO
uint256 public locksStartDate = 1552262400;
mapping(address => uint256) public lockedHalfYearBalances;
mapping(address => uint256) public lockedFullYearBalances;
modifier timeLock(address from, uint256 value) {
if (lockedHalfYearBalances[from] > 0 && now >= locksStartDate + 182 days) lockedHalfYearBalances[from] = 0;
if (now < locksStartDate + 365 days) {
uint256 unlocks = balanceOf(from).sub(lockedHalfYearBalances[from]).sub(lockedFullYearBalances[from]);
require(value <= unlocks);
} else if (lockedFullYearBalances[from] > 0) lockedFullYearBalances[from] = 0;
_;
}
constructor () public ERC20Detailed("Faireum Token", "FAIRC", DECIMALS) {
}
/// @dev function to lock reward pool tokens
function lockRewardPoolTokens(address _beneficiary, uint256 _tokensAmount) public onlyAdmin {
_lockTokens(address(rewardPoolTokensVault), false, _beneficiary, _tokensAmount);
}
/// @dev function to lock founders tokens
function lockFoundersTokens(address _beneficiary, uint256 _tokensAmount) public onlyAdmin {
_lockTokens(address(foundersTokensVault), false, _beneficiary, _tokensAmount);
}
/// @dev function to lock team/devs/advisors tokens
function lockTeamTokens(address _beneficiary, uint256 _tokensAmount) public onlyAdmin {
require(_tokensAmount.mod(2) == 0);
uint256 _half = _tokensAmount.div(2);
_lockTokens(address(teamAdvisorsTokensVault), false, _beneficiary, _half);
_lockTokens(address(teamAdvisorsTokensVault), true, _beneficiary, _half);
}
/// @dev check the locked balance for an address
function lockedBalanceOf(address _owner) public view returns (uint256) {
return lockedFullYearBalances[_owner].add(lockedHalfYearBalances[_owner]);
}
/// @dev change the allowance for an ICO sale service provider
function approveSaleSpender(address _spender, uint256 _tokensAmount) public onlyAdmin {
saleTokensVault.approve(_spender, _tokensAmount);
}
/// @dev change the allowance for an ICO marketing service provider
function approveMarketingSpender(address _spender, uint256 _tokensAmount) public onlyAdmin {
marketingAirdropTokensVault.approve(_spender, _tokensAmount);
}
function transferFrom(address from, address to, uint256 value) public timeLock(from, value) returns (bool) {
return super.transferFrom(from, to, value);
}
function transfer(address to, uint256 value) public timeLock(msg.sender, value) returns (bool) {
return super.transfer(to, value);
}
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function createTokensVaults() external onlyAdmin {
require(teamAdvisorsTokensVault == address(0));
require(rewardPoolTokensVault == address(0));
require(foundersTokensVault == address(0));
require(marketingAirdropTokensVault == address(0));
require(saleTokensVault == address(0));
// Team, devs and advisors tokens - 120M FAIRC (10%)
teamAdvisorsTokensVault = createTokenVault(120000000 * (10 ** uint256(DECIMALS)));
// Reward funding pool tokens - 240M FAIRC (20%)
rewardPoolTokensVault = createTokenVault(240000000 * (10 ** uint256(DECIMALS)));
// Founders tokens - 60M FAIRC (5%)
foundersTokensVault = createTokenVault(60000000 * (10 ** uint256(DECIMALS)));
// Marketing/partnership/airdrop tokens - 120M FAIRC (10%)
marketingAirdropTokensVault = createTokenVault(120000000 * (10 ** uint256(DECIMALS)));
// Sale tokens - 660M FAIRC (55%)
saleTokensVault = createTokenVault(660000000 * (10 ** uint256(DECIMALS)));
require(totalSupply() == INITIAL_SUPPLY);
}
/// @dev Admin-only function to recover any tokens mistakenly sent to this contract
function recoverERC20Tokens(address _contractAddress) external onlyAdmin {
IERC20 erc20Token = IERC20(_contractAddress);
if (erc20Token.balanceOf(address(this)) > 0) {
require(erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this))));
}
}
/// @dev Create a TokenVault, fill with newly minted tokens and
/// allow them to be spent only from the token contract
function createTokenVault(uint256 tokens) internal returns (TokenVault) {
TokenVault tokenVault = new TokenVault(ERC20(this));
_mint(address(tokenVault), tokens);
tokenVault.fillUpAllowance();
return tokenVault;
}
/// @dev generic function to lock tokens from a vault
function _lockTokens(address _fromVault, bool _halfYear, address _beneficiary, uint256 _tokensAmount) internal {
require(_beneficiary != address(0));
if (_halfYear) {
lockedHalfYearBalances[_beneficiary] = lockedHalfYearBalances[_beneficiary].add(_tokensAmount);
} else {
lockedFullYearBalances[_beneficiary] = lockedFullYearBalances[_beneficiary].add(_tokensAmount);
}
require(this.transferFrom(_fromVault, _beneficiary, _tokensAmount));
}
} | function to lock founders tokens | function lockFoundersTokens(address _beneficiary, uint256 _tokensAmount) public onlyAdmin {
_lockTokens(address(foundersTokensVault), false, _beneficiary, _tokensAmount);
}
| 12,779,093 |
./full_match/1/0x1fDf1233f85A3BAe9594B0558e4EC8Febe8c6720/sources/contracts/LPBondDepositoryRewardBased.sol | calculate current bond price and remove floor if above return price_ uint/ | function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).add( ITreasury(treasury).getFloor(principal) ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
terms.minimumPrice = 0;
}
} else if ( terms.minimumPrice != 0 ) {
}
| 3,159,410 |
pragma solidity 0.4.15;
contract BettingContract {
/* Standard state variables */
address public owner;
address public gamblerA;
address public gamblerB;
address public oracle;
uint[] outcomes;
/* Structs are custom data structures with self-defined parameters */
struct Bet {
uint outcome;
uint amount;
bool initialized;
}
/* Keep track of every gambler's bet */
mapping (address => Bet) bets;
/* Keep track of every player's winnings (if any) */
mapping (address => uint) winnings;
/* Add any events you think are necessary */
event BetMade(address gambler);
event BetClosed();
/* Uh Oh, what are these? */
modifier OwnerOnly() {
if(msg.sender == owner){
_;
}
}
modifier OracleOnly() {if(msg.sender == oracle){
_;
}
}
/* Constructor function, where owner and outcomes are set */
function BettingContract(uint[] _outcomes) {
owner = msg.sender;
outcomes = _outcomes;
}
/* Owner chooses their trusted Oracle */
function chooseOracle(address _oracle) OwnerOnly() returns (address) {
oracle = _oracle;
return oracle;
}
/* Gamblers place their bets, preferably after calling checkOutcomes */
function makeBet(uint _outcome) payable returns (bool) {
uint count = 0;
if(checkOutcomes().length > 0){
gamblerA = msg.sender;
bets[gamblerA] = Bet(_outcome, msg.value, false);
oracle.transfer(bets[gamblerA].amount);
BetMade(gamblerA);
count++;
}
if(checkOutcomes().length > 0){
gamblerB = msg.sender;
bets[gamblerB] = Bet(_outcome, msg.value, false);
oracle.transfer(bets[gamblerB].amount);
BetMade(gamblerB);
count++;
}
if(count > 0) {
return true;
}
return false;
}
/* The oracle chooses which outcome wins */
function makeDecision(uint _outcome) payable OracleOnly() {
oracle = msg.sender;
if (bets[gamblerA].outcome == bets[gamblerB].outcome){
gamblerA.transfer(bets[gamblerA].amount);
gamblerB.transfer(bets[gamblerB].amount);
}
else if (bets[gamblerA].outcome == _outcome){
gamblerA.transfer(bets[gamblerA].amount + bets[gamblerB].amount);
}
else if (bets[gamblerB].outcome == _outcome){
gamblerB.transfer(bets[gamblerA].amount + bets[gamblerB].amount);
}
BetClosed();
}
/* Allow anyone to withdraw their winnings safely (if they have enough) */
function withdraw(uint withdrawAmount) returns (uint remainingBal) {
if(winnings[msg.sender] >= withdrawAmount){
winnings[msg.sender] -= withdrawAmount;
if (!msg.sender.send(withdrawAmount)){
winnings[msg.sender] += withdrawAmount;
}
remainingBal = withdrawAmount;
return remainingBal;
}
}
/* Allow anyone to check the outcomes they can bet on */
function checkOutcomes() constant returns (uint[]) {
return outcomes;
}
/* Allow anyone to check if they won any bets */
function checkWinnings() constant returns(uint) {
return winnings[msg.sender];
}
/* Call delete() to reset certain state variables. Which ones? That's upto you to decide */
function contractReset() private {
delete gamblerA;
delete gamblerB;
delete oracle;
}
/* Fallback function */
function() payable {
revert();
}
} | Gamblers place their bets, preferably after calling checkOutcomes / | function makeBet(uint _outcome) payable returns (bool) {
uint count = 0;
if(checkOutcomes().length > 0){
gamblerA = msg.sender;
bets[gamblerA] = Bet(_outcome, msg.value, false);
oracle.transfer(bets[gamblerA].amount);
BetMade(gamblerA);
count++;
}
if(checkOutcomes().length > 0){
gamblerB = msg.sender;
bets[gamblerB] = Bet(_outcome, msg.value, false);
oracle.transfer(bets[gamblerB].amount);
BetMade(gamblerB);
count++;
}
if(count > 0) {
return true;
}
return false;
}
| 13,038,448 |
// SPDX-License-Identifier: GPL-3.0
// Forked from https://github.com/ourzora/core @ 450cd154bfbb70f62e94050cc3f1560d58e0506a
pragma solidity >=0.8.4;
pragma experimental ABIEncoderV2;
import "./ERC721Burnable.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { Counters } from "@openzeppelin/contracts/utils/Counters.sol";
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { Decimal } from "./Decimal.sol";
import { IMarket } from "./interfaces/IMarket.sol";
import { IMedia } from "./interfaces/IMedia.sol";
import { IZoo } from "./interfaces/IZoo.sol";
import "./console.sol";
/**
* @title A media value system, with perpetual equity to creators
* @notice This contract provides an interface to mint media with a market
*/
contract ZooMedia is IMedia, ERC721Burnable, ReentrancyGuard {
using Counters for Counters.Counter;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.UintSet;
/* *******
* Globals
* *******
*/
// Deployment Address
address private _owner;
// Address of ZooKeeper
address public keeperAddress;
// Address of ZooMarket
address public marketAddress;
// Mapping from token to previous owner of the token
mapping(uint256 => address) public previousTokenOwners;
// Mapping from token id to creator address
mapping(uint256 => address) public tokenCreators;
// Mapping from creator address to their (enumerable) set of created tokens
mapping(address => EnumerableSet.UintSet) private _creatorTokens;
// Mapping from token id to sha256 hash of content
mapping(uint256 => bytes32) public tokenContentHashes;
// Mapping from token id to sha256 hash of metadata
mapping(uint256 => bytes32) public tokenMetadataHashes;
// Mapping from token id to metadataURI
mapping(uint256 => string) private _tokenMetadataURIs;
// Mapping from contentHash to bool
mapping(bytes32 => bool) private _contentHashes;
//keccak256("Permit(address spender,uint256 tokenID,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad;
//keccak256("MintWithSig(bytes32 contentHash,bytes32 metadataHash,uint256 creatorShare,uint256 nonce,uint256 deadline)");
bytes32 public constant MINT_WITH_SIG_TYPEHASH =
0x2952e482b8e2b192305f87374d7af45dc2eafafe4f50d26a0c02e90f2fdbe14b;
// Mapping from address to token id to permit nonce
mapping(address => mapping(uint256 => uint256)) public permitNonces;
// Mapping from address to mint with sig nonce
mapping(address => uint256) public mintWithSigNonces;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
* bytes4(keccak256('tokenMetadataURI(uint256)')) == 0x157c3df9
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd ^ 0x157c3df9 == 0x4e222e66
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x4e222e66;
Counters.Counter private _tokenIDTracker;
/* *********
* Modifiers
* *********
*/
modifier onlyZoo() {
require(
keeperAddress == msg.sender || marketAddress == msg.sender,
"ZooMarket: Only Zoo contracts can call this method"
);
_;
}
modifier onlyOwner() {
require(_owner == msg.sender, "ZooMarket: Only owner has access");
_;
}
/**
* @notice Require that the token has not been burned and has been minted
*/
modifier onlyExistingToken(uint256 tokenID) {
require(tokenExists(tokenID), "ZooMedia: nonexistent token");
_;
}
/**
* @notice Require that the token has had a content hash set
*/
modifier onlyTokenWithContentHash(uint256 tokenID) {
require(
tokenContentHashes[tokenID] != 0,
"ZooMedia: token does not have hash of created content"
);
_;
}
/**
* @notice Require that the token has had a metadata hash set
*/
modifier onlyTokenWithMetadataHash(uint256 tokenID) {
require(
tokenMetadataHashes[tokenID] != 0,
"ZooMedia: token does not have hash of its metadata"
);
_;
}
/**
* @notice Ensure that the provided spender is the approved or the owner of
* the media for the specified tokenID
*/
modifier onlyApprovedOrOwner(address spender, uint256 tokenID) {
require(
_isKeeper(msg.sender) || _isApprovedOrOwner(spender, tokenID),
"ZooMedia: Only approved or owner"
);
_;
}
/**
* @notice Ensure the token has been created (even if it has been burned)
*/
modifier onlyTokenCreated(uint256 tokenID) {
require(
_tokenIDTracker.current() >= tokenID,
"ZooMedia: token with that id does not exist"
);
_;
}
/**
* @notice Ensure that the provided URI is not empty
*/
modifier onlyValidURI(string memory uri) {
require(
bytes(uri).length != 0,
"ZooMedia: specified uri must be non-empty"
);
_;
}
/**
* @notice On deployment, set the market contract address and register the
* ERC721 metadata interface
*/
constructor(
string memory name,
string memory symbol
) ERC721(name, symbol) {
_owner = msg.sender;
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
function _isKeeper(address _address) internal view returns (bool) {
return keeperAddress == _address;
}
/**
* @notice Sets the media contract address. This address is the only permitted address that
* can call the mutable functions. This method can only be called once.
*/
function configure(address _keeperAddress, address _marketAddress)
external
onlyOwner
{
// require(marketAddress == address(0), "ZooMedia: Already configured");
// require(keeperAddress == address(0), "ZooMedia: Already configured");
require(
_keeperAddress != address(0),
"Market: cannot set keeper contract as zero address"
);
require(
_marketAddress != address(0),
"Market: cannot set market contract as zero address"
);
keeperAddress = _keeperAddress;
marketAddress = _marketAddress;
}
/* **************
* View Functions
* **************
*/
/**
* @notice Helper to check that token has not been burned or minted
*/
function tokenExists(uint256 tokenID) public override view returns (bool) {
return _exists(tokenID);
}
/**
* @notice return the URI for a particular piece of media with the specified tokenID
* @dev This function is an override of the base OZ implementation because we
* will return the tokenURI even if the media has been burned. In addition, this
* protocol does not support a base URI, so relevant conditionals are removed.
* @return the URI for a token
*/
function tokenURI(uint256 tokenID)
public
view
override
onlyTokenCreated(tokenID)
returns (string memory)
{
string memory _tokenURI = _tokenURIs[tokenID];
return _tokenURI;
}
/**
* @notice Return the metadata URI for a piece of media given the token URI
* @return the metadata URI for the token
*/
function tokenMetadataURI(uint256 tokenID)
external
view
override
onlyTokenCreated(tokenID)
returns (string memory)
{
return _tokenMetadataURIs[tokenID];
}
/* ****************
* Public Functions
* ****************
*/
/**
* @notice see IMedia
*/
function mint(MediaData memory data, IMarket.BidShares memory bidShares)
public
override
nonReentrant
{
_mintForCreator(msg.sender, data, bidShares, "");
}
function _hashToken(address owner, IZoo.Token memory token) private view returns (IZoo.Token memory) {
console.log('_hashToken', token.data.tokenURI, token.data.metadataURI);
token.data.contentHash = keccak256(
abi.encodePacked(token.data.tokenURI, block.number, owner)
);
token.data.metadataHash = keccak256(
abi.encodePacked(token.data.metadataURI, block.number, owner)
);
return token;
}
function mintToken(address owner, IZoo.Token memory token) external override nonReentrant returns (IZoo.Token memory) {
console.log('mintToken', owner, token.name);
token = _hashToken(owner, token);
_mintForCreator(owner, token.data, token.bidShares, "");
uint256 id = getRecentToken(owner);
token.id = id;
return token;
}
function burnToken(address owner, uint256 tokenID) external override nonReentrant onlyExistingToken(tokenID) onlyApprovedOrOwner(owner, tokenID) {
_burn(tokenID);
}
/**
* @notice see IMedia
*/
function mintWithSig(
address creator,
MediaData memory data,
IMarket.BidShares memory bidShares,
EIP712Signature memory sig
) public override nonReentrant {
require(
sig.deadline == 0 || sig.deadline >= block.timestamp,
"ZooMedia: mintWithSig expired"
);
bytes32 domainSeparator = _calculateDomainSeparator();
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(
abi.encode(
MINT_WITH_SIG_TYPEHASH,
data.contentHash,
data.metadataHash,
bidShares.creator.value,
mintWithSigNonces[creator]++,
sig.deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, sig.v, sig.r, sig.s);
require(
recoveredAddress != address(0) && creator == recoveredAddress,
"ZooMedia: Signature invalid"
);
_mintForCreator(recoveredAddress, data, bidShares, "");
}
/**
* @notice see IMedia
*/
function transfer(uint256 tokenID, address recipient) external {
require(msg.sender == marketAddress, "ZooMedia: only market contract");
previousTokenOwners[tokenID] = ownerOf(tokenID);
_transfer(ownerOf(tokenID), recipient, tokenID);
}
/**
* @notice see IMedia
*/
function getRecentToken(address creator) public view returns (uint256) {
uint256 length = EnumerableSet.length(_creatorTokens[creator]) - 1;
return EnumerableSet.at(_creatorTokens[creator], length);
}
/**
* @notice see IMedia
*/
function auctionTransfer(uint256 tokenID, address recipient)
external
override
{
require(msg.sender == marketAddress, "ZooMedia: only market contract");
previousTokenOwners[tokenID] = ownerOf(tokenID);
_safeTransfer(ownerOf(tokenID), recipient, tokenID, "");
}
/**
* @notice see IMedia
*/
function setAsk(uint256 tokenID, IMarket.Ask memory ask)
public
override
nonReentrant
onlyApprovedOrOwner(msg.sender, tokenID)
{
IMarket(marketAddress).setAsk(tokenID, ask);
}
/**
* @notice see IMedia
*/
function removeAsk(uint256 tokenID)
external
override
nonReentrant
onlyApprovedOrOwner(msg.sender, tokenID)
{
IMarket(marketAddress).removeAsk(tokenID);
}
/**
* @notice see IMedia
*/
function setBid(uint256 tokenID, IMarket.Bid memory bid)
public
override
nonReentrant
onlyExistingToken(tokenID)
{
require(msg.sender == bid.bidder, "Market: Bidder must be msg sender");
IMarket(marketAddress).setBid(tokenID, bid, msg.sender);
}
/**
* @notice see IMedia
*/
function removeBid(uint256 tokenID)
external
override
nonReentrant
onlyTokenCreated(tokenID)
{
IMarket(marketAddress).removeBid(tokenID, msg.sender);
}
/**
* @notice see IMedia
*/
function acceptBid(uint256 tokenID, IMarket.Bid memory bid)
public
override
nonReentrant
onlyApprovedOrOwner(msg.sender, tokenID)
{
IMarket(marketAddress).acceptBid(tokenID, bid);
}
/**
* @notice Burn a token.
* @dev Only callable if the media owner is also the creator.
*/
function burn(uint256 tokenID)
public
override
nonReentrant
onlyExistingToken(tokenID)
onlyApprovedOrOwner(msg.sender, tokenID)
{
address owner = ownerOf(tokenID);
require(
tokenCreators[tokenID] == owner,
"ZooMedia: owner is not creator of media"
);
_burn(tokenID);
}
/**
* @notice Revoke the approvals for a token. The provided `approve` function is not sufficient
* for this protocol, as it does not allow an approved address to revoke it's own approval.
* In instances where a 3rd party is interacting on a user's behalf via `permit`, they should
* revoke their approval once their task is complete as a best practice.
*/
function revokeApproval(uint256 tokenID) external override nonReentrant {
require(
msg.sender == getApproved(tokenID),
"ZooMedia: caller not approved address"
);
_approve(address(0), tokenID);
}
/**
* @notice see IMedia
* @dev only callable by approved or owner
*/
function updateTokenURI(uint256 tokenID, string calldata _tokenURI)
external
override
nonReentrant
onlyApprovedOrOwner(msg.sender, tokenID)
onlyTokenWithContentHash(tokenID)
onlyValidURI(_tokenURI)
{
_setTokenURI(tokenID, _tokenURI);
emit TokenURIUpdated(tokenID, msg.sender, _tokenURI);
}
/**
* @notice see IMedia
* @dev only callable by approved or owner
*/
function updateTokenMetadataURI(
uint256 tokenID,
string calldata metadataURI
)
external
override
nonReentrant
onlyApprovedOrOwner(msg.sender, tokenID)
onlyTokenWithMetadataHash(tokenID)
onlyValidURI(metadataURI)
{
_setTokenMetadataURI(tokenID, metadataURI);
emit TokenMetadataURIUpdated(tokenID, msg.sender, metadataURI);
}
/**
* @notice See IMedia
* @dev This method is loosely based on the permit for ERC-20 tokens in EIP-2612, but modified
* for ERC-721.
*/
function permit(
address spender,
uint256 tokenID,
EIP712Signature memory sig
) public override nonReentrant onlyExistingToken(tokenID) {
require(
sig.deadline == 0 || sig.deadline >= block.timestamp,
"ZooMedia: Permit expired"
);
require(spender != address(0), "ZooMedia: spender cannot be 0x0");
bytes32 domainSeparator = _calculateDomainSeparator();
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
spender,
tokenID,
permitNonces[ownerOf(tokenID)][tokenID]++,
sig.deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, sig.v, sig.r, sig.s);
require(
recoveredAddress != address(0) &&
ownerOf(tokenID) == recoveredAddress,
"ZooMedia: Signature invalid"
);
_approve(spender, tokenID);
}
/* *****************
* Private Functions
* *****************
*/
/**
* @notice Creates a new token for `creator`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
* See {ERC721-_safeMint}.
*
* On mint, also set the sha256 hashes of the content and its metadata for integrity
* checks, along with the initial URIs to point to the content and metadata. Attribute
* the token ID to the creator, mark the content hash as used, and set the bid shares for
* the media's market.
*
* Note that although the content hash must be unique for future mints to prevent duplicate media,
* metadata has no such requirement.
*/
function _mintForCreator(
address creator,
MediaData memory data,
IMarket.BidShares memory bidShares,
bytes memory tokenType
) internal onlyValidURI(data.tokenURI) onlyValidURI(data.metadataURI) {
console.log("_mintForCreator", data.tokenURI, data.metadataURI, bidShares.creator.value);
require(
data.contentHash != 0,
"ZooMedia: content hash must be non-zero"
);
require(
_contentHashes[data.contentHash] == false,
"ZooMedia: a token has already been created with this content hash"
);
require(
data.metadataHash != 0,
"ZooMedia: metadata hash must be non-zero"
);
// Get a new ID
_tokenIDTracker.increment();
uint256 tokenID = _tokenIDTracker.current();
console.log("_safeMint", creator, tokenID);
_safeMint(creator, tokenID, tokenType);
_setTokenContentHash(tokenID, data.contentHash);
_setTokenMetadataHash(tokenID, data.metadataHash);
_setTokenMetadataURI(tokenID, data.metadataURI);
_setTokenURI(tokenID, data.tokenURI);
_creatorTokens[creator].add(tokenID);
_contentHashes[data.contentHash] = true;
tokenCreators[tokenID] = creator;
previousTokenOwners[tokenID] = creator;
console.log("_creatorTokens[creator].add(tokenID)", creator, tokenID);
// ZK now responsible for setting bid shares externally
// IMarket(marketAddress).setBidShares(tokenID, bidShares);
}
function _setTokenContentHash(uint256 tokenID, bytes32 contentHash)
internal
virtual
onlyExistingToken(tokenID)
{
tokenContentHashes[tokenID] = contentHash;
}
function _setTokenMetadataHash(uint256 tokenID, bytes32 metadataHash)
internal
virtual
onlyExistingToken(tokenID)
{
tokenMetadataHashes[tokenID] = metadataHash;
}
function _setTokenMetadataURI(uint256 tokenID, string memory metadataURI)
internal
virtual
onlyExistingToken(tokenID)
{
_tokenMetadataURIs[tokenID] = metadataURI;
}
/**
* @notice Destroys `tokenID`.
* @dev We modify the OZ _burn implementation to
* maintain metadata and to remove the
* previous token owner from the piece
*/
function _burn(uint256 tokenID) internal override {
// string memory _tokenURI = _tokenURIs[tokenID];
super._burn(tokenID);
// if (bytes(_tokenURI).length != 0) {
// _tokenURIs[tokenID] = _tokenURI;
// }
delete previousTokenOwners[tokenID];
}
/**
* @notice transfer a token and remove the ask for it.
*/
function _transfer(
address from,
address to,
uint256 tokenID
) internal override {
IMarket(marketAddress).removeAsk(tokenID);
super._transfer(from, to, tokenID);
}
/**
* @dev Calculates EIP712 DOMAIN_SEPARATOR based on the current contract and chain ID.
*/
function _calculateDomainSeparator() internal view returns (bytes32) {
uint256 chainID;
/* solium-disable-next-line */
assembly {
chainID := chainid()
}
return
keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainID,address verifyingContract)"
),
keccak256(bytes("CryptoZoo")),
keccak256(bytes("1")),
chainID,
address(this)
)
);
}
}
| see IMedia/ | function removeBid(uint256 tokenID)
external
override
nonReentrant
onlyTokenCreated(tokenID)
{
IMarket(marketAddress).removeBid(tokenID, msg.sender);
}
| 12,704,604 |
pragma solidity 0.7.1;
pragma experimental ABIEncoderV2;
contract CoreUniLotterySettings
{
// Percentage calculations.
// As Solidity doesn't have floats, we have to use integers for
// percentage arithmetics.
// We set 1 percent to be equal to 1,000,000 - thus, we
// simulate 6 decimal points when computing percentages.
uint32 public constant PERCENT = 10 ** 6;
uint32 constant BASIS_POINT = PERCENT / 100;
uint32 constant _100PERCENT = 100 * PERCENT;
/** The UniLottery Owner's address.
*
* In the current version, The Owner has rights to:
* - Take up to 10% profit from every lottery.
* - Pool liquidity into the pool and unpool it.
* - Start new Auto-Mode & Manual-Mode lotteries.
* - Set randomness provider gas price & other settings.
*/
// Public Testnets: 0xb13CB9BECcB034392F4c9Db44E23C3Fb5fd5dc63
// MainNet: 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2
address payable public constant OWNER_ADDRESS =
address( uint160( 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2 ) );
// Maximum lottery fee the owner can imburse on transfers.
uint32 constant MAX_OWNER_LOTTERY_FEE = 1 * PERCENT;
// Minimum amout of profit percentage that must be distributed
// to lottery winners.
uint32 constant MIN_WINNER_PROFIT_SHARE = 40 * PERCENT;
// Min & max profits the owner can take from lottery net profit.
uint32 constant MIN_OWNER_PROFITS = 3 * PERCENT;
uint32 constant MAX_OWNER_PROFITS = 10 * PERCENT;
// Min & max amount of lottery profits that the pool must get.
uint32 constant MIN_POOL_PROFITS = 10 * PERCENT;
uint32 constant MAX_POOL_PROFITS = 60 * PERCENT;
// Maximum lifetime of a lottery - 1 month (4 weeks).
uint32 constant MAX_LOTTERY_LIFETIME = 4 weeks;
// Callback gas requirements for a lottery's ending callback,
// and for the Pool's Scheduled Callback.
// Must be determined empirically.
uint32 constant LOTTERY_RAND_CALLBACK_GAS = 200000;
uint32 constant AUTO_MODE_SCHEDULED_CALLBACK_GAS = 3800431;
}
interface IUniswapRouter
{
// Get Factory and WETH addresses.
function factory() external pure returns (address);
function WETH() external pure returns (address);
// Create/add to a liquidity pair using ETH.
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline )
external
payable
returns (
uint amountToken,
uint amountETH,
uint liquidity
);
// Remove liquidity pair.
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline )
external
returns (
uint amountETH
);
// Get trade output amount, given an input.
function getAmountsOut(
uint amountIn,
address[] memory path )
external view
returns (
uint[] memory amounts
);
// Get trade input amount, given an output.
function getAmountsIn(
uint amountOut,
address[] memory path )
external view
returns (
uint[] memory amounts
);
}
interface IUniswapFactory
{
function getPair(
address tokenA,
address tokenB )
external view
returns ( address pair );
}
contract UniLotteryConfigGenerator
{
function getConfig()
external pure
returns( Lottery.LotteryConfig memory cfg )
{
cfg.initialFunds = 10 ether;
}
}
contract UniLotteryLotteryFactory
{
// Uniswap Router address on this network - passed to Lotteries on
// construction.
//ddress payable immutable uniRouterAddress;
// Delegate Contract for the Lottery, containing all logic code
// needed for deploying LotteryStubs.
// Deployed only once, on construction.
address payable immutable public delegateContract;
// The Pool Address.
address payable poolAddress;
// The Lottery Storage Factory address, that the Lottery contracts use.
UniLotteryStorageFactory lotteryStorageFactory;
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress/*,
"Function can only be called by the Main Pool!" */);
_;
}
// Constructor.
// Set the Uniswap Address, and deploy&lock the Delegate Code contract.
//
constructor( /*address payable _uniRouter*/ )
{
//uniRouterAddress = _uniRouter;
delegateContract = address( uint160( address( new Lottery() ) ) );
}
// Initialization function.
// Set the poolAddress as msg.sender, and lock it.
// Also, set the Lottery Storage Factory contract instance address.
function initialize( address _storageFactoryAddress )
external
{
require( poolAddress == address( 0 )/*,
"Initialization has already finished!" */);
// Set the Pool's Address.
// Lock it. No more calls to this function will be executed.
poolAddress = msg.sender;
// Set the Storage Factory, and initialize it!
lotteryStorageFactory =
UniLotteryStorageFactory( _storageFactoryAddress );
lotteryStorageFactory.initialize();
}
/**
* Deploy a new Lottery Stub from the specified config.
* @param config - Lottery Config to be used (passed by the pool).
* @return newLottery - the newly deployed lottery stub.
*/
function createNewLottery(
Lottery.LotteryConfig memory config,
address randomnessProvider )
public
poolOnly
returns( address payable newLottery )
{
// Create new Lottery Storage, using storage factory.
// Populate the stub, by calling the "construct" function.
LotteryStub stub = new LotteryStub();
stub.stub_construct( delegateContract );
Lottery( address( stub ) ).construct(
config, poolAddress, randomnessProvider,
lotteryStorageFactory.createNewStorage() );
return address( stub );
}
}
contract LotteryStub
{
// ============ ERC20 token contract's storage ============ //
// ------- Slot ------- //
// Balances of token holders.
mapping (address => uint256) private _balances;
// ------- Slot ------- //
// Allowances of spenders for a specific token owner.
mapping (address => mapping (address => uint256)) private _allowances;
// ------- Slot ------- //
// Total supply of the token.
uint256 private _totalSupply;
// ============== Lottery contract's storage ============== //
// ------- Initial Slots ------- //
// The config which is passed to constructor.
Lottery.LotteryConfig internal cfg;
// ------- Slot ------- //
// The Lottery Storage contract, which stores all holder data,
// such as scores, referral tree data, etc.
LotteryStorage /*public*/ lotStorage;
// ------- Slot ------- //
// Pool address. Set on constructor from msg.sender.
address payable /*public*/ poolAddress;
// ------- Slot ------- //
// Randomness Provider address.
address /*public*/ randomnessProvider;
// ------- Slot ------- //
// Exchange address. In Uniswap mode, it's the Uniswap liquidity
// pair's address, where trades execute.
address /*public*/ exchangeAddress;
// Start date.
uint32 /*public*/ startDate;
// Completion (Mining Phase End) date.
uint32 /*public*/ completionDate;
// The date when Randomness Provider was called, requesting a
// random seed for the lottery finish.
// Also, when this variable becomes Non-Zero, it indicates that we're
// on Ending Stage Part One: waiting for the random seed.
uint32 finish_timeRandomSeedRequested;
// ------- Slot ------- //
// WETH address. Set by calling Router's getter, on constructor.
address WETHaddress;
// Is the WETH first or second token in our Uniswap Pair?
bool uniswap_ethFirst;
// If we are, or were before, on finishing stage, this is the
// probability of lottery going to Ending Stage on this transaction.
uint32 finishProbablity;
// Re-Entrancy Lock (Mutex).
// We protect for reentrancy in the Fund Transfer functions.
bool reEntrancyMutexLocked;
// On which stage we are currently.
uint8 /*public*/ lotteryStage;
// Indicator for whether the lottery fund gains have passed a
// minimum fund gain requirement.
// After that time point (when this bool is set), the token sells
// which could drop the fund value below the requirement, would
// be denied.
bool fundGainRequirementReached;
// The current step of the Mining Stage.
uint16 miningStep;
// If we're currently on Special Transfer Mode - that is, we allow
// direct transfers between parties even in NON-ACTIVE state.
bool specialTransferModeEnabled;
// ------- Slot ------- //
// Per-Transaction Pseudo-Random hash value (transferHashValue).
// This value is computed on every token transfer, by keccak'ing
// the last (current) transferHashValue, msg.sender, block.timestamp, and
// transaction count.
//
// This is used on Finishing Stage, as a pseudo-random number,
// which is used to check if we should end the lottery (move to
// Ending Stage).
uint256 transferHashValue;
// ------- Slot ------- //
// On lottery end, get & store the lottery total ETH return
// (including initial funds), and profit amount.
uint128 /*public*/ ending_totalReturn;
uint128 /*public*/ ending_profitAmount;
// ------- Slot ------- //
// The mapping that contains TRUE for addresses that already claimed
// their lottery winner prizes.
// Used only in COMPLETION, on claimWinnerPrize(), to check if
// msg.sender has already claimed his prize.
mapping( address => bool ) /*public*/ prizeClaimersAddresses;
// =================== OUR CONTRACT'S OWN STORAGE =================== //
// The address of the delegate contract, containing actual logic.
address payable public __delegateContract;
// =================== Functions =================== //
// Constructor.
// Just set the delegate's address.
function stub_construct( address payable _delegateAddr )
external
{
require( __delegateContract == address(0) );
__delegateContract = _delegateAddr;
}
// Fallback payable function, which delegates any call to our
// contract, into the delegate contract.
fallback()
external payable
{
// DelegateCall the delegate code contract.
( bool success, bytes memory data ) =
__delegateContract.delegatecall( msg.data );
// Use inline assembly to be able to return value from the fallback.
// (by default, returning a value from fallback is not possible,
// but it's still possible to manually copy data to the
// return buffer.
assembly
{
// delegatecall returns 0 (false) on error.
// Add 32 bytes to "data" pointer, because first slot (32 bytes)
// contains the length, and we use return value's length
// from returndatasize() opcode.
switch success
case 0 { revert( add( data, 32 ), returndatasize() ) }
default { return( add( data, 32 ), returndatasize() ) }
}
}
// Receive ether function.
receive() external payable
{ }
}
contract LotteryStorageStub
{
// =============== LotteryStorage contract's storage ================ //
// --------- Slot --------- //
// The Lottery address that this storage belongs to.
// Is set by the "initialize()", called by corresponding Lottery.
address lottery;
// The Random Seed, that was passed to us from Randomness Provider,
// or generated alternatively.
uint64 randomSeed;
// The actual number of winners that there will be. Set after
// completing the Winner Selection Algorithm.
uint16 numberOfWinners;
// Bool indicating if Winner Selection Algorithm has been executed.
bool algorithmCompleted;
// --------- Slot --------- //
// Winner Algorithm config. Specified in Initialization().
LotteryStorage.WinnerAlgorithmConfig algConfig;
// --------- Slot --------- //
// The Min-Max holder score storage.
LotteryStorage.MinMaxHolderScores minMaxScores;
// --------- Slot --------- //
// Array of holders.
address[] /*public*/ holders;
// --------- Slot --------- //
// Holder array indexes mapping, for O(1) array element access.
mapping( address => uint ) holderIndexes;
// --------- Slot --------- //
// Mapping of holder data.
mapping( address => LotteryStorage.HolderData ) /*public*/ holderData;
// --------- Slot --------- //
// Mapping of referral IDs to addresses of holders who generated
// those IDs.
mapping( uint256 => address ) referrers;
// --------- Slot --------- //
// The array of final-sorted winners (set after Winner Selection
// Algorithm completes), that contains the winners' indexes
// in the "holders" array, to save space.
//
// Notice that by using uint16, we can fit 16 items into one slot!
// So, if there are 160 winners, we only take up 10 slots, so
// only 20,000 * 10 = 200,000 gas gets consumed!
//
LotteryStorage.WinnerIndexStruct[] sortedWinnerIndexes;
// =================== OUR CONTRACT'S OWN STORAGE =================== //
// The address of the delegate contract, containing actual logic.
address public __delegateContract;
// =================== Functions =================== //
// Constructor.
// Just set the delegate's address.
function stub_construct( address _delegateAddr )
external
{
require( __delegateContract == address(0) );
__delegateContract = _delegateAddr;
}
// Fallback function, which delegates any call to our
// contract, into the delegate contract.
fallback()
external
{
// DelegateCall the delegate code contract.
( bool success, bytes memory data ) =
__delegateContract.delegatecall( msg.data );
// Use inline assembly to be able to return value from the fallback.
// (by default, returning a value from fallback is not possible,
// but it's still possible to manually copy data to the
// return buffer.
assembly
{
// delegatecall returns 0 (false) on error.
// Add 32 bytes to "data" pointer, because first slot (32 bytes)
// contains the length, and we use return value's length
// from returndatasize() opcode.
switch success
case 0 { revert( add( data, 32 ), returndatasize() ) }
default { return( add( data, 32 ), returndatasize() ) }
}
}
}
interface IUniLotteryPool
{
function lotteryFinish( uint totalReturn, uint profitAmount )
external payable;
}
interface IRandomnessProvider
{
function requestRandomSeedForLotteryFinish() external;
}
contract LotteryStorage is CoreUniLotterySettings
{
// ==================== Structs & Constants ==================== //
// Struct of holder data & scores.
struct HolderData
{
// --------- Slot --------- //
// If this holder provided a valid referral ID, this is the
// address of a referrer - the user who generated the said
// referral ID.
address referrer;
// Bonus score points, which can be given in certain events,
// such as when player registers a valid referral ID.
int16 bonusScore;
// Number of all child referrees, including multi-level ones.
// Updated by traversing child->parent way, incrementing
// every node's counter by one.
// Used in Winner Selection Algorithm, to determine how much
// to divide the accumulated referree scores by.
uint16 referreeCount;
// --------- Slot --------- //
// If this holder has generated his own referral ID, this is
// that ID. If he hasn't generated an ID, this is zero.
uint256 referralID;
// --------- Slot --------- //
// The intermediate individual score factor variables.
// Ether contributed: ( buys - sells ). Can be negative.
int40 etherContributed;
// Time x ether factor: (relativeTxTime * etherAmount).
int40 timeFactors;
// Token balance score factor of this holder - we use int,
// for easier computation of player scores in our algorithms.
int40 tokenBalance;
// Accumulated referree score factors - ether contributed by
// all referrees, time factors, and token balances of all
// referrees.
int40 referree_etherContributed;
int40 referree_timeFactors;
int40 referree_tokenBalance;
}
// Final Score (end lottery score * randomValue) structure.
struct FinalScore
{
address addr; // 20 bytes \
uint16 holderIndex; // 2 bytes | = 30 bytes => 1 slot.
uint64 score; // 8 bytes /
}
// Winner Indexes structure - used to efficiently store Winner
// indexes in holder's array, after completing the Winner Selection
// Algorithm.
// To save Space, we store these in a struct, with uint16 array
// with 16 items - so this struct takes up excactly 1 slot.
struct WinnerIndexStruct
{
uint16[ 16 ] indexes;
}
// A structure which is used by Winner Selection algorithm,
// which is a subset of the LotteryConfig structure, containing
// only items necessary for executing the Winner Selection algorigm.
// More detailed member description can be found in LotteryConfig
// structure description.
// Takes up only one slot!
struct WinnerAlgorithmConfig
{
// --------- Slot --------- //
// Individual player max score parts.
int16 maxPlayerScore_etherContributed;
int16 maxPlayerScore_tokenHoldingAmount;
int16 maxPlayerScore_timeFactor;
int16 maxPlayerScore_refferalBonus;
// Number of lottery winners.
uint16 winnerCount;
// Score-To-Random ration data (as a rational ratio number).
// For example if 1:5, then scorePart = 1, and randPart = 5.
uint16 randRatio_scorePart;
uint16 randRatio_randPart;
// The Ending Algorithm type.
uint8 endingAlgoType;
}
// Structure containing the minimum and maximum values of
// holder intermediate scores.
// These values get updated on transfers during ACTIVE stage,
// when holders buy/sell tokens.
//
// Used in winner selection algorithm, to normalize the scores in
// a single loop, to avoid looping additional time to find min/max.
//
// Structure takes up only a single slot!
//
struct MinMaxHolderScores
{
// --------- Slot --------- //
int40 holderScore_etherContributed_min;
int40 holderScore_etherContributed_max;
int40 holderScore_timeFactors_min;
int40 holderScore_timeFactors_max;
int40 holderScore_tokenBalance_min;
int40 holderScore_tokenBalance_max;
}
// Referral score variant of the structure above.
// Also, only a single slot!
//
struct MinMaxReferralScores
{
// --------- Slot --------- //
// Min&Max values for referrer scores.
int40 referralScore_etherContributed_min;
int40 referralScore_etherContributed_max;
int40 referralScore_timeFactors_min;
int40 referralScore_timeFactors_max;
int40 referralScore_tokenBalance_min;
int40 referralScore_tokenBalance_max;
}
// ROOT_REFERRER constant.
// Used to prevent cyclic dependencies on referral tree.
address constant ROOT_REFERRER = address( 1 );
// Max referral tree depth - maximum number of referrees that
// a referrer can get.
uint constant MAX_REFERRAL_DEPTH = 10;
// Precision of division operations.
int constant PRECISION = 10000;
// Random number modulo to use when obtaining random numbers from
// the random seed + nonce, using keccak256.
// This is the maximum available Score Random Factor, plus one.
// By default, 10^9 (one billion).
//
uint constant RANDOM_MODULO = (10 ** 9);
// Maximum number of holders that the MinedWinnerSelection algorithm
// can process. Related to block gas limit.
uint constant MINEDSELECTION_MAX_NUMBER_OF_HOLDERS = 300;
// Maximum number of holders that the WinnerSelfValidation algorithm
// can process. Related to block gas limit.
uint constant SELFVALIDATION_MAX_NUMBER_OF_HOLDERS = 1200;
// ==================== State Variables ==================== //
// --------- Slot --------- //
// The Lottery address that this storage belongs to.
// Is set by the "initialize()", called by corresponding Lottery.
address lottery;
// The Random Seed, that was passed to us from Randomness Provider,
// or generated alternatively.
uint64 randomSeed;
// The actual number of winners that there will be. Set after
// completing the Winner Selection Algorithm.
uint16 numberOfWinners;
// Bool indicating if Winner Selection Algorithm has been executed.
bool algorithmCompleted;
// --------- Slot --------- //
// Winner Algorithm config. Specified in Initialization().
WinnerAlgorithmConfig algConfig;
// --------- Slot --------- //
// The Min-Max holder score storage.
MinMaxHolderScores public minMaxScores;
MinMaxReferralScores public minMaxReferralScores;
// --------- Slot --------- //
// Array of holders.
address[] public holders;
// --------- Slot --------- //
// Holder array indexes mapping, for O(1) array element access.
mapping( address => uint ) holderIndexes;
// --------- Slot --------- //
// Mapping of holder data.
mapping( address => HolderData ) public holderData;
// --------- Slot --------- //
// Mapping of referral IDs to addresses of holders who generated
// those IDs.
mapping( uint256 => address ) referrers;
// --------- Slot --------- //
// The array of final-sorted winners (set after Winner Selection
// Algorithm completes), that contains the winners' indexes
// in the "holders" array, to save space.
//
// Notice that by using uint16, we can fit 16 items into one slot!
// So, if there are 160 winners, we only take up 10 slots, so
// only 20,000 * 10 = 200,000 gas gets consumed!
//
WinnerIndexStruct[] sortedWinnerIndexes;
// ============== Internal (Private) Functions ============== //
// Lottery-Only modifier.
modifier lotteryOnly
{
require( msg.sender == address( lottery )/*,
"Function can only be called by Lottery that this"
"Storage Contract belongs to!" */);
_;
}
// ============== [ BEGIN ] LOTTERY QUICKSORT FUNCTIONS ============== //
/**
* QuickSort and QuickSelect algorithm functionality code.
*
* These algorithms are used to find the lottery winners in
* an array of final random-factored scores.
* As the highest-scorers win, we need to sort an array to
* identify them.
*
* For this task, we use QuickSelect to partition array into
* winner part (elements with score larger than X, where X is
* n-th largest element, where n is number of winners),
* and others (non-winners), who are ignored to save computation
* power.
* Then we sort the winner part only, using QuickSort, and
* distribute prizes to winners accordingly.
*/
// Swap function used in QuickSort algorithms.
//
function QSort_swap( FinalScore[] memory list,
uint a, uint b )
internal pure
{
FinalScore memory tmp = list[ a ];
list[ a ] = list[ b ];
list[ b ] = tmp;
}
// Standard Hoare's partition scheme function, used for both
// QuickSort and QuickSelect.
//
function QSort_partition(
FinalScore[] memory list,
int lo, int hi )
internal pure
returns( int newPivotIndex )
{
uint64 pivot = list[ uint( hi + lo ) / 2 ].score;
int i = lo - 1;
int j = hi + 1;
while( true )
{
do {
i++;
} while( list[ uint( i ) ].score > pivot ) ;
do {
j--;
} while( list[ uint( j ) ].score < pivot ) ;
if( i >= j )
return j;
QSort_swap( list, uint( i ), uint( j ) );
}
}
// QuickSelect's Lomuto partition scheme.
//
function QSort_LomutoPartition(
FinalScore[] memory list,
uint left, uint right, uint pivotIndex )
internal pure
returns( uint newPivotIndex )
{
uint pivotValue = list[ pivotIndex ].score;
QSort_swap( list, pivotIndex, right ); // Move pivot to end
uint storeIndex = left;
for( uint i = left; i < right; i++ )
{
if( list[ i ].score > pivotValue ) {
QSort_swap( list, storeIndex, i );
storeIndex++;
}
}
// Move pivot to its final place, and return the pivot's index.
QSort_swap( list, right, storeIndex );
return storeIndex;
}
// QuickSelect algorithm (iterative).
//
function QSort_QuickSelect(
FinalScore[] memory list,
int left, int right, int k )
internal pure
returns( int indexOfK )
{
while( true ) {
if( left == right )
return left;
int pivotIndex = int( QSort_LomutoPartition( list,
uint(left), uint(right), uint(right) ) );
if( k == pivotIndex )
return k;
else if( k < pivotIndex )
right = pivotIndex - 1;
else
left = pivotIndex + 1;
}
}
// Standard QuickSort function.
//
function QSort_QuickSort(
FinalScore[] memory list,
int lo, int hi )
internal pure
{
if( lo < hi ) {
int p = QSort_partition( list, lo, hi );
QSort_QuickSort( list, lo, p );
QSort_QuickSort( list, p + 1, hi );
}
}
// ============== [ END ] LOTTERY QUICKSORT FUNCTIONS ============== //
// ------------ Ending Stage - Winner Selection Algorithm ------------ //
/**
* Compute the individual player score factors for a holder.
* Function split from the below one (ending_Stage_2), to avoid
* "Stack too Deep" errors.
*/
function computeHolderIndividualScores(
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMax,
HolderData memory hdata )
internal pure
returns( int individualScore )
{
// Normalize the scores, by subtracting minimum and dividing
// by maximum, to get the score values specified in cfg.
// Use precision of 100, then round.
//
// Notice that we're using int arithmetics, so division
// truncates. That's why we use PRECISION, to simulate
// rounding.
//
// This formula is better explained in example.
// In this example, we use variable abbreviations defined
// below, on formula's right side comments.
//
// Say, values are these in our example:
// e = 4, eMin = 1, eMax = 8, MS = 5, P = 10.
//
// So, let's calculate the score using the formula:
// ( ( ( (4 - 1) * 10 * 5 ) / (8 - 1) ) + (10 / 2) ) / 10 =
// ( ( ( 3 * 10 * 5 ) / 7 ) + 5 ) / 10 =
// ( ( 150 / 7 ) + 5 ) / 10 =
// ( ( 150 / 7 ) + 5 ) / 10 =
// ( 20 + 5 ) / 10 =
// 25 / 10 =
// [ 2.5 ] = 2
//
// So, with truncation, we see that for e = 4, the score
// is 2 out of 5 maximum.
// That's because the minimum ether contributed was 1, and
// maximum was 8.
// So, 4 stays below the middle, and gets a nicely rounded
// score of 2.
// Compute etherContributed.
int score_etherContributed = ( (
( int( hdata.etherContributed - // e
minMax.holderScore_etherContributed_min ) // eMin
* PRECISION * cfg.maxPlayerScore_etherContributed )// P * MS
/ int( minMax.holderScore_etherContributed_max - // eMax
minMax.holderScore_etherContributed_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Compute timeFactors.
int score_timeFactors = ( (
( int( hdata.timeFactors - // e
minMax.holderScore_timeFactors_min ) // eMin
* PRECISION * cfg.maxPlayerScore_timeFactor ) // P * MS
/ int( minMax.holderScore_timeFactors_max - // eMax
minMax.holderScore_timeFactors_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Compute tokenBalance.
int score_tokenBalance = ( (
( int( hdata.tokenBalance - // e
minMax.holderScore_tokenBalance_min ) // eMin
* PRECISION * cfg.maxPlayerScore_tokenHoldingAmount )
/ int( minMax.holderScore_tokenBalance_max - // eMax
minMax.holderScore_tokenBalance_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Return the accumulated individual score (excluding referrees).
return score_etherContributed + score_timeFactors +
score_tokenBalance;
}
/**
* Compute the unified Referree-Score of a player, who's got
* the accumulated factor-scores of all his referrees in his
* holderData structure.
*
* @param individualToReferralRatio - an int value, computed
* before starting the winner score computation loop, in
* the ending_Stage_2 initial part, to save computation
* time later.
* This is the ratio of the maximum available referral score,
* to the maximum available individual score, as defined in
* the config (for example, if max.ref.score is 20, and
* max.ind.score is 40, then the ratio is 20/40 = 0.5).
*
* We use this ratio to transform the computed accumulated
* referree individual scores to the standard referrer's
* score, by multiplying by that ratio.
*/
function computeReferreeScoresForHolder(
int individualToReferralRatio,
WinnerAlgorithmConfig memory cfg,
MinMaxReferralScores memory minMax,
HolderData memory hdata )
internal pure
returns( int unifiedReferreeScore )
{
// If number of referrees of this HODLer is Zero, then
// his referree score is also zero.
if( hdata.referreeCount == 0 )
return 0;
// Now, compute the Referree's Accumulated Scores.
//
// Here we use the same formula as when computing individual
// scores (in the function above), but we use referree parts
// instead.
// Compute etherContributed.
int referreeScore_etherContributed = ( (
( int( hdata.referree_etherContributed -
minMax.referralScore_etherContributed_min )
* PRECISION * cfg.maxPlayerScore_etherContributed )
/ int( minMax.referralScore_etherContributed_max -
minMax.referralScore_etherContributed_min )
) );
// Compute timeFactors.
int referreeScore_timeFactors = ( (
( int( hdata.referree_timeFactors -
minMax.referralScore_timeFactors_min )
* PRECISION * cfg.maxPlayerScore_timeFactor )
/ int( minMax.referralScore_timeFactors_max -
minMax.referralScore_timeFactors_min )
) );
// Compute tokenBalance.
int referreeScore_tokenBalance = ( (
( int( hdata.referree_tokenBalance -
minMax.referralScore_tokenBalance_min )
* PRECISION * cfg.maxPlayerScore_tokenHoldingAmount )
/ int( minMax.referralScore_tokenBalance_max -
minMax.referralScore_tokenBalance_min )
) );
// Accumulate 'em all !
// Then, multiply it by the ratio of all individual max scores
// (maxPlayerScore_etherContributed, timeFactor, tokenBalance),
// to the maxPlayerScore_refferalBonus.
// Use the same precision.
unifiedReferreeScore = int( ( (
( ( referreeScore_etherContributed +
referreeScore_timeFactors +
referreeScore_tokenBalance ) + (PRECISION / 2)
) / PRECISION
) * individualToReferralRatio
) / PRECISION );
}
/**
* Update Min & Max values for individual holder scores.
*/
function priv_updateMinMaxScores_individual(
MinMaxHolderScores memory minMax,
int40 _etherContributed,
int40 _timeFactors,
int40 _tokenBalance )
internal
pure
{
// etherContributed:
if( _etherContributed >
minMax.holderScore_etherContributed_max )
minMax.holderScore_etherContributed_max =
_etherContributed;
if( _etherContributed <
minMax.holderScore_etherContributed_min )
minMax.holderScore_etherContributed_min =
_etherContributed;
// timeFactors:
if( _timeFactors >
minMax.holderScore_timeFactors_max )
minMax.holderScore_timeFactors_max =
_timeFactors;
if( _timeFactors <
minMax.holderScore_timeFactors_min )
minMax.holderScore_timeFactors_min =
_timeFactors;
// tokenBalance:
if( _tokenBalance >
minMax.holderScore_tokenBalance_max )
minMax.holderScore_tokenBalance_max =
_tokenBalance;
if( _tokenBalance <
minMax.holderScore_tokenBalance_min )
minMax.holderScore_tokenBalance_min =
_tokenBalance;
}
/**
* Update Min & Max values for referral scores.
*/
function priv_updateMinMaxScores_referral(
MinMaxReferralScores memory minMax,
int40 _etherContributed,
int40 _timeFactors,
int40 _tokenBalance )
internal
pure
{
// etherContributed:
if( _etherContributed >
minMax.referralScore_etherContributed_max )
minMax.referralScore_etherContributed_max =
_etherContributed;
if( _etherContributed <
minMax.referralScore_etherContributed_min )
minMax.referralScore_etherContributed_min =
_etherContributed;
// timeFactors:
if( _timeFactors >
minMax.referralScore_timeFactors_max )
minMax.referralScore_timeFactors_max =
_timeFactors;
if( _timeFactors <
minMax.referralScore_timeFactors_min )
minMax.referralScore_timeFactors_min =
_timeFactors;
// tokenBalance:
if( _tokenBalance >
minMax.referralScore_tokenBalance_max )
minMax.referralScore_tokenBalance_max =
_tokenBalance;
if( _tokenBalance <
minMax.referralScore_tokenBalance_min )
minMax.referralScore_tokenBalance_min =
_tokenBalance;
}
// =================== PUBLIC FUNCTIONS =================== //
/**
* Update current holder's score with given change values, and
* Propagate the holder's current transfer's score changes
* through the referral chain, updating every parent referrer's
* accumulated referree scores, until the ROOT_REFERRER or zero
* address referrer is encountered.
*/
function updateAndPropagateScoreChanges(
address holder,
int __etherContributed_change,
int __timeFactors_change,
int __tokenBalance_change )
public
lotteryOnly
{
// Convert the data into shrinked format - leave only
// 4 decimals of Ether precision, and drop the decimal part
// of ULT tokens absolutely.
// Don't change TimeFactors, as it is already adjusted in
// Lottery contract's code.
int40 timeFactors_change = int40( __timeFactors_change );
int40 etherContributed_change = int40(
__etherContributed_change / int(1 ether / 10000) );
int40 tokenBalance_change = int40(
__tokenBalance_change / int(1 ether) );
// Update current holder's score.
holderData[ holder ].etherContributed += etherContributed_change;
holderData[ holder ].timeFactors += timeFactors_change;
holderData[ holder ].tokenBalance += tokenBalance_change;
// Check if scores are exceeding current min/max scores,
// and if so, update the min/max scores.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
priv_updateMinMaxScores_individual(
minMaxCpy,
holderData[ holder ].etherContributed,
holderData[ holder ].timeFactors,
holderData[ holder ].tokenBalance
);
// Propagate the score through the referral chain.
// Dive at maximum to the depth of 10, to avoid "Outta Gas"
// errors.
uint depth = 0;
address referrerAddr = holderData[ holder ].referrer;
while( referrerAddr != ROOT_REFERRER &&
referrerAddr != address( 0 ) &&
depth < MAX_REFERRAL_DEPTH )
{
// Update this referrer's accumulated referree scores.
holderData[ referrerAddr ].referree_etherContributed +=
etherContributed_change;
holderData[ referrerAddr ].referree_timeFactors +=
timeFactors_change;
holderData[ referrerAddr ].referree_tokenBalance +=
tokenBalance_change;
// Update MinMax according to this referrer's score.
priv_updateMinMaxScores_referral(
minMaxRefCpy,
holderData[ referrerAddr ].referree_etherContributed,
holderData[ referrerAddr ].referree_timeFactors,
holderData[ referrerAddr ].referree_tokenBalance
);
// Move to the higher-level referrer.
referrerAddr = holderData[ referrerAddr ].referrer;
depth++;
}
// Check if MinMax have changed. If so, update it.
if( keccak256( abi.encode( minMaxCpy ) ) !=
keccak256( abi.encode( minMaxScores ) ) )
minMaxScores = minMaxCpy;
// Check referral part.
if( keccak256( abi.encode( minMaxRefCpy ) ) !=
keccak256( abi.encode( minMaxReferralScores ) ) )
minMaxReferralScores = minMaxRefCpy;
}
/**
* Pure function to fix an in-memory copy of MinMaxScores,
* by changing equal min-max pairs to differ by one.
* This is needed to avoid division-by-zero in some calculations.
*/
function priv_fixMinMaxIfEqual(
MinMaxHolderScores memory minMaxCpy,
MinMaxReferralScores memory minMaxRefCpy )
internal
pure
{
// Individual part
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// Referral part
if( minMaxRefCpy.referralScore_etherContributed_min ==
minMaxRefCpy.referralScore_etherContributed_max )
minMaxRefCpy.referralScore_etherContributed_max =
minMaxRefCpy.referralScore_etherContributed_min + 1;
if( minMaxRefCpy.referralScore_timeFactors_min ==
minMaxRefCpy.referralScore_timeFactors_max )
minMaxRefCpy.referralScore_timeFactors_max =
minMaxRefCpy.referralScore_timeFactors_min + 1;
if( minMaxRefCpy.referralScore_tokenBalance_min ==
minMaxRefCpy.referralScore_tokenBalance_max )
minMaxRefCpy.referralScore_tokenBalance_max =
minMaxRefCpy.referralScore_tokenBalance_min + 1;
}
/**
* Function executes the Lottery Winner Selection Algorithm,
* and writes the final, sorted array, containing winner rankings.
*
* This function is called from the Lottery's Mining Stage Step 2,
*
* This is the final function that lottery performs actively -
* and arguably the most important - because it determines
* lottery winners through Winner Selection Algorithm.
*
* The random seed must be already set, before calling this function.
*/
function executeWinnerSelectionAlgorithm()
public
lotteryOnly
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is MinedWinnerSelection!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.MinedWinnerSelection)/*,
"Algorithm cannot be performed on current Algo-Type!" */);
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we block.timestamp have to do, is loop through holder array, and
// compute randomized final scores for every holder, into
// the Final Score array.
// Declare the Final Score array - computed for all holders.
uint ARRLEN =
( holders.length > MINEDSELECTION_MAX_NUMBER_OF_HOLDERS ?
MINEDSELECTION_MAX_NUMBER_OF_HOLDERS : holders.length );
FinalScore[] memory finalScores = new FinalScore[] ( ARRLEN );
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5/*, "scorePart" */== 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy );
// Loop through all the holders.
for( uint i = 0; i < ARRLEN; i++ )
{
// Fetch the needed holder data to in-memory hdata variable,
// to save gas on score part computing functions.
HolderData memory hdata;
// Slot 1:
hdata.etherContributed =
holderData[ holders[ i ] ].etherContributed;
hdata.timeFactors =
holderData[ holders[ i ] ].timeFactors;
hdata.tokenBalance =
holderData[ holders[ i ] ].tokenBalance;
hdata.referreeCount =
holderData[ holders[ i ] ].referreeCount;
// Slot 2:
hdata.referree_etherContributed =
holderData[ holders[ i ] ].referree_etherContributed;
hdata.referree_timeFactors =
holderData[ holders[ i ] ].referree_timeFactors;
hdata.referree_tokenBalance =
holderData[ holders[ i ] ].referree_tokenBalance;
hdata.bonusScore =
holderData[ holders[ i ] ].bonusScore;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
hdata.bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, hdata )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxRefCpy, hdata );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Multiply the score by the Random Modulo Adjustment
// Factor, to get fairer ratio of random-to-determined data.
totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) /
( PRECISION );
// Score is computed!
// Now, randomize it, and add to Final Scores Array.
// We use keccak to generate a random number from random seed,
// using holder's address as a nonce.
uint modulizedRandomNumber = uint(
keccak256( abi.encodePacked( randomSeed, holders[ i ] ) )
) % RANDOM_MODULO;
// Add the random number, to introduce the random factor.
// Ratio of (current) totalPlayerScore to modulizedRandomNumber
// is the same as ratio of randRatio_scorePart to
// randRatio_randPart.
uint endScore = uint( totalPlayerScore ) + modulizedRandomNumber;
// Finally, set this holder's final score data.
finalScores[ i ].addr = holders[ i ];
finalScores[ i ].holderIndex = uint16( i );
finalScores[ i ].score = uint64( endScore );
}
// All final scores are block.timestamp computed.
// Sort the array, to find out the highest scores!
// Firstly, partition an array to only work on top K scores,
// where K is the number of winners.
// There can be a rare case where specified number of winners is
// more than lottery token holders. We got that covered.
require( finalScores.length > 0 );
uint K = cfg.winnerCount - 1;
if( K > finalScores.length-1 )
K = finalScores.length-1; // Must be THE LAST ELEMENT's INDEX.
// Use QuickSelect to do this.
QSort_QuickSelect( finalScores, 0,
int( finalScores.length - 1 ), int( K ) );
// Now, QuickSort only the first K items, because the rest
// item scores are not high enough to become winners.
QSort_QuickSort( finalScores, 0, int( K ) );
// Now, the winner array is sorted, with the highest scores
// sitting at the first positions!
// Let's set up the winner indexes array, where we'll store
// the winners' indexes in the holders array.
// So, if this array is [8, 2, 3], that means that
// Winner #1 is holders[8], winner #2 is holders[2], and
// winner #3 is holders[3].
// Set the Number Of Winners variable.
numberOfWinners = uint16( K + 1 );
// Now, we can loop through the first numberOfWinners elements, to set
// the holder indexes!
// Loop through 16 elements at a time, to fill the structs.
for( uint offset = 0; offset < numberOfWinners; offset += 16 )
{
WinnerIndexStruct memory windStruct;
uint loopStop = ( offset + 16 > numberOfWinners ?
numberOfWinners : offset + 16 );
for( uint i = offset; i < loopStop; i++ )
{
windStruct.indexes[ i - offset ] =finalScores[ i ].holderIndex;
}
// Push this block.timestamp-filled struct to the storage array!
sortedWinnerIndexes.push( windStruct );
}
// That's it! We're done!
algorithmCompleted = true;
}
/**
* Add a holder to holders array.
* @param holder - address of a holder to add.
*/
function addHolder( address holder )
public
lotteryOnly
{
// Add it to list, and set index in the mapping.
holders.push( holder );
holderIndexes[ holder ] = holders.length - 1;
}
/**
* Removes the holder 'sender' from the Holders Array.
* However, this holder's HolderData structure persists!
*
* Notice that no index validity checks are performed, so, if
* 'sender' is not present in "holderIndexes" mapping, this
* function will remove the 0th holder instead!
* This is not a problem for us, because Lottery calls this
* function only when it's absolutely certain that 'sender' is
* present in the holders array.
*
* @param sender - address of a holder to remove.
* Named 'sender', because when token sender sends away all
* his tokens, he must then be removed from holders array.
*/
function removeHolder( address sender )
public
lotteryOnly
{
// Get index of the sender address in the holders array.
uint index = holderIndexes[ sender ];
// Remove the sender from array, by copying last element's
// value into the index'th element, where sender was before.
holders[ index ] = holders[ holders.length - 1 ];
// Remove the last element of array, which we've just copied.
holders.pop();
// Update indexes: remove the sender's index from the mapping,
// and change the previoulsy-last element's index to the
// one where we copied it - where sender was before.
delete holderIndexes[ sender ];
holderIndexes[ holders[ index ] ] = index;
}
/**
* Get holder array length.
*/
function getHolderCount()
public view
returns( uint )
{
return holders.length;
}
/**
* Generate a referral ID for a token holder.
* Referral ID is used to refer other wallets into playing our
* lottery.
* - Referrer gets bonus points for every wallet that bought
* lottery tokens and specified his referral ID.
* - Referrees (wallets who got referred by registering a valid
* referral ID, corresponding to some referrer), get some
* bonus points for specifying (registering) a referral ID.
*
* Referral ID is a uint256 number, which is generated by
* keccak256'ing the holder's address, holder's current
* token ballance, and current time.
*/
function generateReferralID( address holder )
public
lotteryOnly
returns( uint256 referralID )
{
// Check if holder has some tokens, and doesn't
// have his own referral ID yet.
require( holderData[ holder ].tokenBalance != 0/*,
"holder doesn't have any lottery tokens!" */);
require( holderData[ holder ].referralID == 0/*,
"Holder already has a referral ID!" */);
// Generate a referral ID with keccak.
uint256 refID = uint256( keccak256( abi.encodePacked(
holder, holderData[ holder ].tokenBalance, block.timestamp ) ) );
// Specify the ID as current ID of this holder.
holderData[ holder ].referralID = refID;
// If this holder wasn't referred by anyone (his referrer is
// not set), and he's block.timestamp generated his own ID, he won't
// be able to register as a referree of someone else
// from block.timestamp on.
// This is done to prevent circular dependency in referrals.
// Do it by setting a referrer to ROOT_REFERRER address,
// which is an invalid address (address(1)).
if( holderData[ holder ].referrer == address( 0 ) )
holderData[ holder ].referrer = ROOT_REFERRER;
// Create a new referrer with this ID.
referrers[ refID ] = holder;
return refID;
}
/**
* Register a referral for a token holder, using a valid
* referral ID got from a referrer.
* This function is called by a referree, who obtained a
* valid referral ID from some referrer, who previously
* generated it using generateReferralID().
*
* You can only register a referral once!
* When you do so, you get bonus referral points!
*/
function registerReferral(
address holder,
int16 referralRegisteringBonus,
uint256 referralID )
public
lotteryOnly
returns( address _referrerAddress )
{
// Check if this holder has some tokens, and if he hasn't
// registered a referral yet.
require( holderData[ holder ].tokenBalance != 0/*,
"holder doesn't have any lottery tokens!" */);
require( holderData[ holder ].referrer == address( 0 )/*,
"holder already has registered a referral!" */);
// Create a local memory copy of minMaxReferralScores.
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
// Get the referrer's address from his ID, and specify
// it as a referrer of holder.
holderData[ holder ].referrer = referrers[ referralID ];
// Bonus points are added to this holder's score for
// registering a referral!
holderData[ holder ].bonusScore = referralRegisteringBonus;
// Increment number of referrees for every parent referrer,
// by traversing a referral tree child->parent way.
address referrerAddr = holderData[ holder ].referrer;
// Set the return value.
_referrerAddress = referrerAddr;
// Traverse a tree.
while( referrerAddr != ROOT_REFERRER &&
referrerAddr != address( 0 ) )
{
// Increment referree count for this referrrer.
holderData[ referrerAddr ].referreeCount++;
// Update the Referrer Scores of the referrer, adding this
// referree's scores to it's current values.
holderData[ referrerAddr ].referree_etherContributed +=
holderData[ holder ].etherContributed;
holderData[ referrerAddr ].referree_timeFactors +=
holderData[ holder ].timeFactors;
holderData[ referrerAddr ].referree_tokenBalance +=
holderData[ holder ].tokenBalance;
// Update MinMax according to this referrer's score.
priv_updateMinMaxScores_referral(
minMaxRefCpy,
holderData[ referrerAddr ].referree_etherContributed,
holderData[ referrerAddr ].referree_timeFactors,
holderData[ referrerAddr ].referree_tokenBalance
);
// Move to the higher-level referrer.
referrerAddr = holderData[ referrerAddr ].referrer;
}
// Update MinMax Referral Scores if needed.
if( keccak256( abi.encode( minMaxRefCpy ) ) !=
keccak256( abi.encode( minMaxReferralScores ) ) )
minMaxReferralScores = minMaxRefCpy;
return _referrerAddress;
}
/**
* Sets our random seed to some value.
* Should be called from Lottery, after obtaining random seed from
* the Randomness Provider.
*/
function setRandomSeed( uint _seed )
external
lotteryOnly
{
randomSeed = uint64( _seed );
}
/**
* Initialization function.
* Here, we bind our contract to the Lottery contract that
* this Storage belongs to.
* The parent lottery must call this function - hence, we set
* "lottery" to msg.sender.
*
* When this function is called, our contract must be not yet
* initialized - "lottery" address must be Zero!
*
* Here, we also set our Winner Algorithm config, which is a
* subset of LotteryConfig, fitting into 1 storage slot.
*/
function initialize(
WinnerAlgorithmConfig memory _wcfg )
public
{
require( address( lottery ) == address( 0 )/*,
"Storage is already initialized!" */);
// Set the Lottery address (msg.sender can't be zero),
// and thus, set our contract to initialized!
lottery = msg.sender;
// Set the Winner-Algo-Config.
algConfig = _wcfg;
// NOT-NEEDED: Set initial min-max scores: min is INT_MAX.
/*minMaxScores.holderScore_etherContributed_min = int80( 2 ** 78 );
minMaxScores.holderScore_timeFactors_min = int80( 2 ** 78 );
minMaxScores.holderScore_tokenBalance_min = int80( 2 ** 78 );
*/
}
// ==================== Views ==================== //
// Returns the current random seed.
// If the seed hasn't been set yet (or set to 0), returns 0.
//
function getRandomSeed()
external view
returns( uint )
{
return randomSeed;
}
// Check if Winner Selection Algorithm has beed executed.
//
function minedSelection_algorithmAlreadyExecuted()
external view
returns( bool )
{
return algorithmCompleted;
}
/**
* After lottery has completed, this function returns if "addr"
* is one of lottery winners, and the position in winner rankings.
* Function is used to obtain the ranking position before
* calling claimWinnerPrize() on Lottery.
*
* This function should be called off-chain, and then using the
* retrieved data, one can call claimWinnerPrize().
*/
function minedSelection_getWinnerStatus(
address addr )
public view
returns( bool isWinner,
uint32 rankingPosition )
{
// Loop through the whole winner indexes array, trying to
// find if "addr" is one of the winner addresses.
for( uint16 i = 0; i < numberOfWinners; i++ )
{
// Check if holder on this winner ranking's index position
// is addr, if so, good!
uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ];
if( holders[ pos ] == addr )
{
return ( true, i );
}
}
// The "addr" is not a winner.
return ( false, 0 );
}
/**
* Checks if address is on specified winner ranking position.
* Used in Lottery, to check if msg.sender is really the
* winner #rankingPosition, as he claims to be.
*/
function minedSelection_isAddressOnWinnerPosition(
address addr,
uint32 rankingPosition )
external view
returns( bool )
{
if( rankingPosition >= numberOfWinners )
return false;
// Just check if address at "holders" array
// index "sortedWinnerIndexes[ position ]" is really the "addr".
uint pos = sortedWinnerIndexes[ rankingPosition / 16 ]
.indexes[ rankingPosition % 16 ];
return ( holders[ pos ] == addr );
}
/**
* Returns an array of all winner addresses, sorted by their
* ranking position (winner #1 first, #2 second, etc.).
*/
function minedSelection_getAllWinners()
external view
returns( address[] memory )
{
address[] memory winners = new address[] ( numberOfWinners );
for( uint i = 0; i < numberOfWinners; i++ )
{
uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ];
winners[ i ] = holders[ pos ];
}
return winners;
}
/**
* Compute the Lottery Active Stage Score of a token holder.
*
* This function computes the Active Stage (pre-randomization)
* player score, and should generally be used to compute player
* intermediate scores - while lottery is still active or on
* finishing stage, before random random seed is obtained.
*/
function getPlayerActiveStageScore( address holderAddr )
external view
returns( uint playerScore )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Check if holderAddr is a holder at all!
if( holders[ holderIndexes[ holderAddr ] ] != holderAddr )
return 0;
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy );
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
holderData[ holderAddr ].bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, holderData[ holderAddr ] )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxRefCpy, holderData[ holderAddr ] );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Return the score!
return uint( totalPlayerScore );
}
/**
* Internal sub-procedure of the function below, used to obtain
* a final, randomized score of a Single Holder.
*/
function priv_getSingleHolderScore(
address hold3r,
int individualToReferralRatio,
int maxAvailablePlayerScore,
int SCORE_RAND_FACT,
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMaxCpy,
MinMaxReferralScores memory minMaxRefCpy )
internal view
returns( uint endScore )
{
// Fetch the needed holder data to in-memory hdata variable,
// to save gas on score part computing functions.
HolderData memory hdata;
// Slot 1:
hdata.etherContributed =
holderData[ hold3r ].etherContributed;
hdata.timeFactors =
holderData[ hold3r ].timeFactors;
hdata.tokenBalance =
holderData[ hold3r ].tokenBalance;
hdata.referreeCount =
holderData[ hold3r ].referreeCount;
// Slot 2:
hdata.referree_etherContributed =
holderData[ hold3r ].referree_etherContributed;
hdata.referree_timeFactors =
holderData[ hold3r ].referree_timeFactors;
hdata.referree_tokenBalance =
holderData[ hold3r ].referree_tokenBalance;
hdata.bonusScore =
holderData[ hold3r ].bonusScore;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
hdata.bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, hdata )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxRefCpy, hdata );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Multiply the score by the Random Modulo Adjustment
// Factor, to get fairer ratio of random-to-determined data.
totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) /
( PRECISION );
// Score is computed!
// Now, randomize it, and add to Final Scores Array.
// We use keccak to generate a random number from random seed,
// using holder's address as a nonce.
uint modulizedRandomNumber = uint(
keccak256( abi.encodePacked( randomSeed, hold3r ) )
) % RANDOM_MODULO;
// Add the random number, to introduce the random factor.
// Ratio of (current) totalPlayerScore to modulizedRandomNumber
// is the same as ratio of randRatio_scorePart to
// randRatio_randPart.
return uint( totalPlayerScore ) + modulizedRandomNumber;
}
/**
* Winner Self-Validation algo-type main function.
* Here, we compute scores for all lottery holders iteratively
* in O(n) time, and thus get the winner ranking position of
* the holder in question.
*
* This function performs essentialy the same steps as the
* Mined-variant (executeWinnerSelectionAlgorithm), but doesn't
* write anything to blockchain.
*
* @param holderAddr - address of a holder whose rank we want to find.
*/
function winnerSelfValidation_getWinnerStatus(
address holderAddr )
internal view
returns( bool isWinner, uint rankingPosition )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is WinnerSelfValidation!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.WinnerSelfValidation)/*,
"Algorithm cannot be performed on current Algo-Type!" */);
// Check if holderAddr is a holder at all!
require( holders[ holderIndexes[ holderAddr ] ] == holderAddr/*,
"holderAddr is not a lottery token holder!" */);
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we block.timestamp have to do, is loop through holder array, and
// compute randomized final scores for every holder.
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5/*, "scorePart" */== 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy );
// How many holders had higher scores than "holderAddr".
// Used to obtain the final winner rank of "holderAddr".
uint numOfHoldersHigherThan = 0;
// The final (randomized) score of "holderAddr".
uint holderAddrsFinalScore = priv_getSingleHolderScore(
holderAddr,
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy, minMaxRefCpy );
// Index of holderAddr.
uint holderAddrIndex = holderIndexes[ holderAddr ];
// Loop through all the allowed holders.
for( uint i = 0;
i < ( holders.length < SELFVALIDATION_MAX_NUMBER_OF_HOLDERS ?
holders.length : SELFVALIDATION_MAX_NUMBER_OF_HOLDERS );
i++ )
{
// Skip the holderAddr's index.
if( i == holderAddrIndex )
continue;
// Compute the score using helper function.
uint endScore = priv_getSingleHolderScore(
holders[ i ],
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy, minMaxRefCpy );
// Check if score is higher than HolderAddr's, and if so, check.
if( endScore > holderAddrsFinalScore )
numOfHoldersHigherThan++;
}
// All scores are checked!
// Now, we can obtain holderAddr's winner rank based on how
// many scores were above holderAddr's score!
isWinner = ( numOfHoldersHigherThan < cfg.winnerCount );
rankingPosition = numOfHoldersHigherThan;
}
/**
* Rolled-Randomness algo-type main function.
* Here, we only compute the score of the holder in question,
* and compare it to maximum-available final score, divided
* by no-of-winners.
*
* @param holderAddr - address of a holder whose rank we want to find.
*/
function rolledRandomness_getWinnerStatus(
address holderAddr )
internal view
returns( bool isWinner, uint rankingPosition )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is RolledRandomness!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.RolledRandomness)/*,
"Algorithm cannot be performed on current Algo-Type!" */);
// Check if holderAddr is a holder at all!
require( holders[ holderIndexes[ holderAddr ] ] == holderAddr/*,
"holderAddr is not a lottery token holder!" */);
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we block.timestamp have to do, is loop through holder array, and
// compute randomized final scores for every holder.
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy );
// The final (randomized) score of "holderAddr".
uint holderAddrsFinalScore = priv_getSingleHolderScore(
holderAddr,
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy, minMaxRefCpy );
// Now, compute the Max-Final-Random Score, divide it
// by the Holder Count, and get the ranking by placing this
// holder's score in it's corresponding part.
//
// In this approach, we assume linear randomness distribution.
// In practice, distribution might be a bit different, but this
// approach is the most efficient.
//
// Max-Final-Score (randomized) is the highest available score
// that can be achieved, and is made by adding together the
// maximum availabe Player Score Part and maximum available
// Random Part (equals RANDOM_MODULO).
// These parts have a ratio equal to config-specified
// randRatio_scorePart to randRatio_randPart.
//
// So, if player's active stage's score is low (1), but rand-part
// in ratio is huge, then the score is mostly random, so
// maxFinalScore is close to the RANDOM_MODULO - maximum random
// value that can be rolled.
//
// If, however, we use 1:1 playerScore-to-Random Ratio, then
// playerScore and RandomScore make up equal parts of end score,
// so the maxFinalScore is actually two times larger than
// RANDOM_MODULO, so player needs to score more
// player-points to get larger prizes.
//
// In default configuration, playerScore-to-random ratio is 1:3,
// so there's a good randomness factor, so even the low-scoring
// players can reasonably hope to get larger prizes, but
// the higher is player's active stage score, the more
// chances of scoring a high final score a player gets, with
// the higher-end of player scores basically guaranteeing
// themselves a specific prize amount, if winnerCount is
// big enough to overlap.
int maxRandomPart = int( RANDOM_MODULO - 1 );
int maxPlayerScorePart = ( SCORE_RAND_FACT * maxAvailablePlayerScore )
/ PRECISION;
uint maxFinalScore = uint( maxRandomPart + maxPlayerScorePart );
// Compute the amount that single-holder's virtual part
// might take up in the max-final score.
uint singleHolderPart = maxFinalScore / holders.length;
// Now, compute how many single-holder-parts are there in
// this holder's score.
uint holderAddrScorePartCount = holderAddrsFinalScore /
singleHolderPart;
// The ranking is that number, minus holders length.
// If very high score is scored, default to position 0 (highest).
rankingPosition = (
holderAddrScorePartCount < holders.length ?
holders.length - holderAddrScorePartCount : 0
);
isWinner = ( rankingPosition < cfg.winnerCount );
}
/**
* Genericized, algorithm type-dependent getWinnerStatus function.
*/
function getWinnerStatus(
address addr )
external view
returns( bool isWinner, uint32 rankingPosition )
{
bool _isW;
uint _rp;
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.RolledRandomness) )
{
(_isW, _rp) = rolledRandomness_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.WinnerSelfValidation) )
{
(_isW, _rp) = winnerSelfValidation_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.MinedWinnerSelection) )
{
(_isW, _rp) = minedSelection_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
}
}
interface IMainUniLotteryPool
{
function isLotteryOngoing( address lotAddr )
external view returns( bool );
function scheduledCallback( uint256 requestID )
external;
function onLotteryCallbackPriceExceedingGivenFunds(
address lottery, uint currentRequestPrice,
uint poolGivenPastRequestPrice )
external returns( bool );
}
interface ILottery
{
function finish_randomnessProviderCallback(
uint256 randomSeed, uint256 requestID ) external;
}
contract UniLotteryStorageFactory
{
// The Pool Address.
address payable poolAddress;
// The Delegate Logic contract, containing all code for
// all LotteryStorage contracts to be deployed.
address immutable public delegateContract;
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress/*,
"Function can only be called by the Main Pool!" */);
_;
}
// Constructor.
// Deploy the Delegate Contract here.
//
constructor()
{
delegateContract = address( new LotteryStorage() );
}
// Initialization function.
// Set the poolAddress as msg.sender, and lock it.
function initialize()
external
{
require( poolAddress == address( 0 )/*,
"Initialization has already finished!" */);
// Set the Pool's Address.
poolAddress = msg.sender;
}
/**
* Deploy a new Lottery Storage Stub, to be used by it's corresponding
* Lottery Stub, which will be created later, passing this Storage
* we create here.
* @return newStorage - the Lottery Storage Stub contract just deployed.
*/
function createNewStorage()
public
poolOnly
returns( address newStorage )
{
LotteryStorageStub stub = new LotteryStorageStub();
stub.stub_construct( delegateContract );
return address( stub );
}
}
abstract contract Context {
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "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;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "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 {
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 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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
abstract contract solcChecker {
/* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) virtual external;
}
interface ProvableI {
function cbAddress() external returns (address _cbAddress);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function getPrice(string calldata _datasource) external returns (uint _dsprice);
function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash);
function getPrice(string calldata _datasource, uint _gasLimit) external returns (uint _dsprice);
function queryN(uint _timestamp, string calldata _datasource, bytes calldata _argN) external payable returns (bytes32 _id);
function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id);
function query2(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id);
}
interface OracleAddrResolverI {
function getAddress() external returns (address _address);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory _buf, uint _capacity) internal pure {
uint capacity = _capacity;
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
_buf.capacity = capacity; // Allocate space for the buffer data
assembly {
let ptr := mload(0x40)
mstore(_buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory _buf, uint _capacity) private pure {
bytes memory oldbuf = _buf.buf;
init(_buf, _capacity);
append(_buf, oldbuf);
}
function max(uint _a, uint _b) private pure returns (uint _max) {
if (_a > _b) {
return _a;
}
return _b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return _buffer The original buffer.
*
*/
function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) {
if (_data.length + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _data.length) * 2);
}
uint dest;
uint src;
uint len = _data.length;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length)
mstore(bufptr, add(buflen, mload(_data))) // Update buffer length
src := add(_data, 32)
}
for(; len >= 32; len -= 32) { // Copy word-length chunks while possible
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return _buf;
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
*
*/
function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return _buffer The original buffer.
*
*/
function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) {
if (_len + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _len) * 2);
}
uint mask = 256 ** _len - 1;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len
mstore(dest, or(and(mload(dest), not(mask)), _data))
mstore(bufptr, add(buflen, _len)) // Update buffer length
}
return _buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure {
if (_value <= 23) {
_buf.append(uint8((_major << 5) | _value));
} else if (_value <= 0xFF) {
_buf.append(uint8((_major << 5) | 24));
_buf.appendInt(_value, 1);
} else if (_value <= 0xFFFF) {
_buf.append(uint8((_major << 5) | 25));
_buf.appendInt(_value, 2);
} else if (_value <= 0xFFFFFFFF) {
_buf.append(uint8((_major << 5) | 26));
_buf.appendInt(_value, 4);
} else if (_value <= 0xFFFFFFFFFFFFFFFF) {
_buf.append(uint8((_major << 5) | 27));
_buf.appendInt(_value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure {
_buf.append(uint8((_major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure {
encodeType(_buf, MAJOR_TYPE_INT, _value);
}
function encodeInt(Buffer.buffer memory _buf, int _value) internal pure {
if (_value >= 0) {
encodeType(_buf, MAJOR_TYPE_INT, uint(_value));
} else {
encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value));
}
}
function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_BYTES, _value.length);
_buf.append(_value);
}
function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length);
_buf.append(bytes(_value));
}
function startArray(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE);
}
}
contract usingProvable {
using CBOR for Buffer.buffer;
ProvableI provable;
OracleAddrResolverI OAR;
uint constant day = 60 * 60 * 24;
uint constant week = 60 * 60 * 24 * 7;
uint constant month = 60 * 60 * 24 * 30;
byte constant proofType_NONE = 0x00;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
byte constant proofType_Android = 0x40;
byte constant proofType_TLSNotary = 0x10;
string provable_network_name;
uint8 constant networkID_auto = 0;
uint8 constant networkID_morden = 2;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_consensys = 161;
mapping(bytes32 => bytes32) provable_randomDS_args;
mapping(bytes32 => bool) provable_randomDS_sessionKeysHashVerified;
modifier provableAPI {
if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) {
provable_setNetwork(networkID_auto);
}
if (address(provable) != OAR.getAddress()) {
provable = ProvableI(OAR.getAddress());
}
_;
}
modifier provable_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) {
// RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1)));
bool proofVerified = provable_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), provable_getNetworkName());
require(proofVerified);
_;
}
function provable_setNetwork(uint8 _networkID) internal returns (bool _networkSet) {
_networkID; // NOTE: Silence the warning and remain backwards compatible
return provable_setNetwork();
}
function provable_setNetworkName(string memory _network_name) internal {
provable_network_name = _network_name;
}
function provable_getNetworkName() internal view returns (string memory _networkName) {
return provable_network_name;
}
function provable_setNetwork() internal returns (bool _networkSet) {
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet
OAR = OracleAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
provable_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet
OAR = OracleAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
provable_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet
OAR = OracleAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
provable_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet
OAR = OracleAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
provable_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet
OAR = OracleAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41);
provable_setNetworkName("eth_goerli");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge
OAR = OracleAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide
OAR = OracleAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity
OAR = OracleAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
/**
* @dev The following `__callback` functions are just placeholders ideally
* meant to be defined in child contract when proofs are used.
* The function bodies simply silence compiler warnings.
*/
function __callback(bytes32 _myid, string memory _result) virtual public {
__callback(_myid, _result, new bytes(0));
}
function __callback(bytes32 _myid, string memory _result, bytes memory _proof) virtual public {
_myid; _result; _proof;
provable_randomDS_args[bytes32(0)] = bytes32(0);
}
function provable_getPrice(string memory _datasource) provableAPI internal returns (uint _queryPrice) {
return provable.getPrice(_datasource);
}
function provable_getPrice(string memory _datasource, uint _gasLimit) provableAPI internal returns (uint _queryPrice) {
return provable.getPrice(_datasource, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query{value: price}(0, _datasource, _arg);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query{value: price}(_timestamp, _datasource, _arg);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource,_gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query_withGasLimit{value: price}(_timestamp, _datasource, _arg, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query_withGasLimit{value: price}(0, _datasource, _arg, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg1, string memory _arg2) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query2{value: price}(0, _datasource, _arg1, _arg2);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query2{value: price}(_timestamp, _datasource, _arg1, _arg2);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query2_withGasLimit{value: price}(_timestamp, _datasource, _arg1, _arg2, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query2_withGasLimit{value: price}(0, _datasource, _arg1, _arg2, _gasLimit);
}
function provable_query(string memory _datasource, string[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN{value: price}(0, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, string[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN{value: price}(_timestamp, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(_timestamp, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, string[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(0, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, string[1] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[1] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[2] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[2] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[3] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[3] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[4] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[4] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[5] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[5] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN{value: price}(0, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN{value: price}(_timestamp, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(_timestamp, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(0, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, bytes[1] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[2] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[3] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[4] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[5] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_setProof(byte _proofP) provableAPI internal {
return provable.setProofType(_proofP);
}
function provable_cbAddress() provableAPI internal returns (address _callbackAddress) {
return provable.cbAddress();
}
function getCodeSize(address _addr) view internal returns (uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function provable_setCustomGasPrice(uint _gasPrice) provableAPI internal {
return provable.setCustomGasPrice(_gasPrice);
}
function provable_randomDS_getSessionPubKeyHash() provableAPI internal returns (bytes32 _sessionKeyHash) {
return provable.randomDS_getSessionPubKeyHash();
}
function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i = 2; i < 2 + 2 * 20; i += 2) {
iaddr *= 256;
b1 = uint160(uint8(tmp[i]));
b2 = uint160(uint8(tmp[i + 1]));
if ((b1 >= 97) && (b1 <= 102)) {
b1 -= 87;
} else if ((b1 >= 65) && (b1 <= 70)) {
b1 -= 55;
} else if ((b1 >= 48) && (b1 <= 57)) {
b1 -= 48;
}
if ((b2 >= 97) && (b2 <= 102)) {
b2 -= 87;
} else if ((b2 >= 65) && (b2 <= 70)) {
b2 -= 55;
} else if ((b2 >= 48) && (b2 <= 57)) {
b2 -= 48;
}
iaddr += (b1 * 16 + b2);
}
return address(iaddr);
}
function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) {
minLength = b.length;
}
for (uint i = 0; i < minLength; i ++) {
if (a[i] < b[i]) {
return -1;
} else if (a[i] > b[i]) {
return 1;
}
}
if (a.length < b.length) {
return -1;
} else if (a.length > b.length) {
return 1;
} else {
return 0;
}
}
function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if (h.length < 1 || n.length < 1 || (n.length > h.length)) {
return -1;
} else if (h.length > (2 ** 128 - 1)) {
return -1;
} else {
uint subindex = 0;
for (uint i = 0; i < h.length; i++) {
if (h[i] == n[0]) {
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) {
subindex++;
}
if (subindex == n.length) {
return int(i);
}
}
}
return -1;
}
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
for (i = 0; i < _bd.length; i++) {
babcde[k++] = _bd[i];
}
for (i = 0; i < _be.length; i++) {
babcde[k++] = _be[i];
}
return string(babcde);
}
function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) {
return safeParseInt(_a, 0);
}
function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
require(!decimals, 'More than one decimal encountered in string!');
decimals = true;
} else {
revert("Non-numeral character encountered in string!");
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function parseInt(string memory _a) internal pure returns (uint _parsedInt) {
return parseInt(_a, 0);
}
function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) {
break;
} else {
_b--;
}
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
decimals = true;
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeString(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeBytes(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function provable_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) {
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10; // Convert from seconds to ledger timer ticks
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(uint8(_nbytes));
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = provable_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
/*
The following variables can be relaxed.
Check the relaxed random contract at https://github.com/oraclize/ethereum-examples
for an idea on how to override and replace commit hash variables.
*/
mstore(add(unonce, 0x20), xor(blockhash(sub(number(), 1)), xor(coinbase(), timestamp())))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = provable_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
provable_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function provable_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal {
provable_randomDS_args[_queryId] = _commitment;
}
function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) {
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20);
sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs);
if (address(uint160(uint256(keccak256(_pubkey)))) == signer) {
return true;
} else {
(sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs);
return (address(uint160(uint256(keccak256(_pubkey)))) == signer);
}
}
function provable_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) {
bool sigok;
// Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2);
copyBytes(_proof, _sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1 + 65 + 32);
tosign2[0] = byte(uint8(1)); //role
copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (!sigok) {
return false;
}
// Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1 + 65);
tosign3[0] = 0xFE;
copyBytes(_proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2);
copyBytes(_proof, 3 + 65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
function provable_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) {
// Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) {
return 1;
}
bool proofVerified = provable_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), provable_getNetworkName());
if (!proofVerified) {
return 2;
}
return 0;
}
function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) {
bool match_ = true;
require(_prefix.length == _nRandomBytes);
for (uint256 i = 0; i< _nRandomBytes; i++) {
if (_content[i] != _prefix[i]) {
match_ = false;
}
}
return match_;
}
function provable_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) {
// Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId)
uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32;
bytes memory keyhash = new bytes(32);
copyBytes(_proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) {
return false;
}
bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2);
copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0);
// Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) {
return false;
}
// Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);
copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65;
copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (provable_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match
delete provable_randomDS_args[_queryId];
} else return false;
// Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32 + 8 + 1 + 32);
copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) {
return false;
}
// Verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (!provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) {
provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = provable_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset);
}
return provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
*/
function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) {
uint minLength = _length + _toOffset;
require(_to.length >= minLength); // Buffer too small. Should be a better way?
uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint j = 32 + _toOffset;
while (i < (32 + _fromOffset + _length)) {
assembly {
let tmp := mload(add(_from, i))
mstore(add(_to, j), tmp)
}
i += 32;
j += 32;
}
return _to;
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
Duplicate Solidity's ecrecover, but catching the CALL return value
*/
function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) {
/*
We do our own memory management here. Solidity uses memory offset
0x40 to store the current end of memory. We write past it (as
writes are memory extensions), but don't update the offset so
Solidity will reuse it. The memory used here is only needed for
this context.
FIXME: inline assembly can't access return values
*/
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, _hash)
mstore(add(size, 32), _v)
mstore(add(size, 64), _r)
mstore(add(size, 96), _s)
ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code.
addr := mload(size)
}
return (ret, addr);
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
*/
function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
return (false, address(0));
}
/*
The signature format is a compact form of:
{bytes32 r}{bytes32 s}{uint8 v}
Compact means, uint8 is not padded to 32 bytes.
*/
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
/*
Here we are loading the last 32 bytes. We exploit the fact that
'mload' will pad with zeroes if we overread.
There is no 'mload8' to do this, but that would be nicer.
*/
v := byte(0, mload(add(_sig, 96)))
/*
Alternative solution:
'byte' is not working due to the Solidity parser, so lets
use the second best option, 'and'
v := and(mload(add(_sig, 65)), 255)
*/
}
/*
albeit non-transactional signatures are not specified by the YP, one would expect it
to match the YP range of [27, 28]
geth uses [0, 1] and some clients have followed. This might change, see:
https://github.com/ethereum/go-ethereum/issues/2053
*/
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (false, address(0));
}
return safer_ecrecover(_hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
/*assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize(), sub(msize(), fmem))
}*/
}
}
interface IUniswapPair is IERC20
{
// Addresses of the first and second pool-kens.
function token0() external view returns (address);
function token1() external view returns (address);
// Get the pair's token pool reserves.
function getReserves()
external view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
contract UniLotteryPool is ERC20, CoreUniLotterySettings
{
// =================== Structs & Enums =================== //
/* Lottery running mode (Auto-Lottery, manual lottery).
*
* If Auto-Lottery feature is enabled, the new lotteries will start
* automatically after the previous one finished, and will use
* the default, agreed-upon config, which is set by voting.
*
* If Manual Lottery is enabled, the new lotteries are started
* manually, by submitting and voting for a specific config.
*
* Both modes can have AVERAGE_CONFIG feature, when final lottery
* config is not set by voting for one of several user-submitted
* configs, but final config is computed by averaging all the voted
* configs, where each vote proposes a config.
*/
enum LotteryRunMode {
MANUAL,
AUTO,
MANUAL_AVERAGE_CONFIG,
AUTO_AVERAGE_CONFIG
}
// =================== Events =================== //
// Periodic stats event.
event PoolStats(
uint32 indexed lotteriesPerformed,
uint indexed totalPoolFunds,
uint indexed currentPoolBalance
);
// New poolholder joins and complete withdraws of a poolholder.
event NewPoolholderJoin(
address indexed poolholder,
uint256 initialAmount
);
event PoolholderWithdraw(
address indexed poolholder
);
// Current poolholder liquidity adds/removes.
event AddedLiquidity(
address indexed poolholder,
uint256 indexed amount
);
event RemovedLiquidity(
address indexed poolholder,
uint256 indexed amount
);
// Lottery Run Mode change (for example, from Manual to Auto lottery).
event LotteryRunModeChanged(
LotteryRunMode previousMode,
LotteryRunMode newMode
);
// Lottery configs proposed. In other words, it's a new lottery start
// initiation. If no config specified, then the default config for
// that lottery is used.
event NewConfigProposed(
address indexed initiator,
Lottery.LotteryConfig cfg,
uint configIndex
);
// Lottery started.
event LotteryStarted(
address indexed lottery,
uint256 indexed fundsUsed,
uint256 indexed poolPercentageUsed,
Lottery.LotteryConfig config
);
// Lottery finished.
event LotteryFinished(
address indexed lottery,
uint256 indexed totalReturn,
uint256 indexed profitAmount
);
// Ether transfered into the fallback receive function.
event EtherReceived(
address indexed sender,
uint256 indexed value
);
// ========= Constants ========= //
// The Core Constants (OWNER_ADDRESS, Owner's max profit amount),
// and also the percentage calculation-related constants,
// are defined in the CoreUniLotterySettings contract, which this
// contract inherits from.
// ERC-20 token's public constants.
string constant public name = "UniLottery Main Pool";
string constant public symbol = "ULPT";
uint256 constant public decimals = 18;
// ========= State variables ========= //
// --------- Slot --------- //
// The debt to the Randomness Provider.
// Incurred when we allow the Randomness Provider to execute
// requests with higher price than we have given it funds for.
// (of course, executed only when the Provider has enough balance
// to execute it).
// Paid back on next Randomness Provider request.
uint80 randomnessProviderDebt;
// Auto-Mode lottery parameters:
uint32 public autoMode_nextLotteryDelay = 1 days;
uint16 public autoMode_maxNumberOfRuns = 50;
// When the last Auto-Mode lottery was started.
uint32 public autoMode_lastLotteryStarted;
// When the last Auto-Mode lottery has finished.
// Used to compute the time until the next lottery.
uint32 public autoMode_lastLotteryFinished;
// Auto-Mode callback scheduled time.
uint32 public autoMode_timeCallbackScheduled;
// Iterations of current Auto-Lottery cycle.
uint16 autoMode_currentCycleIterations = 0;
// Is an Auto-Mode lottery currently ongoing?
bool public autoMode_isLotteryCurrentlyOngoing = false;
// Re-Entrancy Lock for Liquidity Provide/Remove functions.
bool reEntrancyLock_Locked;
// --------- Slot --------- //
// The initial funds of all currently active lotteries.
uint currentLotteryFunds;
// --------- Slot --------- //
// Most recently launched lottery.
Lottery public mostRecentLottery;
// Current lottery run-mode (Enum, so 1 byte).
LotteryRunMode public lotteryRunMode = LotteryRunMode.MANUAL;
// Last time when funds were manually sent to the Randomness Provider.
uint32 lastTimeRandomFundsSend;
// --------- Slot --------- //
// The address of the Gas Oracle (our own service which calls our
// gas price update function periodically).
address gasOracleAddress;
// --------- Slot --------- //
// Stores all lotteries that have been performed
// (including currently ongoing ones ).
Lottery[] public allLotteriesPerformed;
// --------- Slot --------- //
// Currently ongoing lotteries - a list, and a mapping.
mapping( address => bool ) ongoingLotteries;
// --------- Slot --------- //
// Owner-approved addresses, which can call functions, marked with
// modifier "ownerApprovedAddressOnly", on behalf of the Owner,
// to initiate Owner-Only operations, such as setting next lottery
// config, or moving specified part of Owner's liquidity pool share to
// Owner's wallet address.
// Note that this is equivalent of as if Owner had called the
// removeLiquidity() function from OWNER_ADDRESS.
//
// These owner-approved addresses, able to call owner-only functions,
// are used by Owner, to minimize risk of a hack in these ways:
// - OWNER_ADDRESS wallet, which might hold significant ETH amounts,
// is used minimally, to have as little log-on risk in Metamask,
// as possible.
// - The approved addresses can have very little Ether, so little
// risk of using them from Metamask.
// - Periodic liquidity removes from the Pool can help to reduce
// losses, if Pool contract was hacked (which most likely
// wouldn't ever happen given our security measures, but
// better be safe than sorry).
//
mapping( address => bool ) public ownerApprovedAddresses;
// --------- Slot --------- //
// The config to use for the next lottery that will be started.
Lottery.LotteryConfig internal nextLotteryConfig;
// --------- Slot --------- //
// Randomness Provider address.
UniLotteryRandomnessProvider immutable public randomnessProvider;
// --------- Slot --------- //
// The Lottery Factory that we're using to deploy NEW lotteries.
UniLotteryLotteryFactory immutable public lotteryFactory;
// --------- Slot --------- //
// The Lottery Storage factory that we're using to deploy
// new lottery storages. Used inside a Lottery Factory.
address immutable public storageFactory;
// ========= FUNCTIONS - METHODS ========= //
// ========= Private Functions ========= //
// Owner-Only modifier (standard).
modifier ownerOnly
{
require( msg.sender == OWNER_ADDRESS/*, "Function is Owner-Only!" */);
_;
}
// Owner, or Owner-Approved address only.
modifier ownerApprovedAddressOnly
{
require( ownerApprovedAddresses[ msg.sender ]/*,
"Function can be called only by Owner-Approved addresses!"*/);
_;
}
// Owner Approved addresses, and the Gas Oracle address.
// Used when updating RandProv's gas price.
modifier gasOracleAndOwnerApproved
{
require( ownerApprovedAddresses[ msg.sender ] ||
msg.sender == gasOracleAddress/*,
"Function can only be called by Owner-Approved addrs, "
"and by the Gas Oracle!" */);
_;
}
// Randomness Provider-Only modifier.
modifier randomnessProviderOnly
{
require( msg.sender == address( randomnessProvider )/*,
"Function can be called only by the Randomness Provider!" */);
_;
}
/**
* Modifier for checking if a caller is a currently ongoing
* lottery - that is, if msg.sender is one of addresses in
* ongoingLotteryList array, and present in ongoingLotteries.
*/
modifier calledByOngoingLotteryOnly
{
require( ongoingLotteries[ msg.sender ]/*,
"Function can be called only by ongoing lotteries!"*/);
_;
}
/**
* Lock the function to protect from re-entrancy, using
* a Re-Entrancy Mutex Lock.
*/
modifier mutexLOCKED
{
require( ! reEntrancyLock_Locked/*, "Re-Entrant Call Detected!" */);
reEntrancyLock_Locked = true;
_;
reEntrancyLock_Locked = false;
}
// Emits a statistical event, summarizing current pool state.
function emitPoolStats()
private
{
(uint32 a, uint b, uint c) = getPoolStats();
emit PoolStats( a, b, c );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Launch a new UniLottery Lottery, from specified Lottery Config.
* Perform all initialization procedures, including initial fund
* transfer, and random provider registration.
*
* @return newlyLaunchedLottery - the Contract instance (address) of
* the newly deployed and initialized lottery.
*/
function launchLottery(
Lottery.LotteryConfig memory cfg )
private
mutexLOCKED
returns( Lottery newlyLaunchedLottery )
{
// Check config fund requirement.
// Lottery will need funds equal to:
// initial funds + gas required for randomness prov. callback.
// Now, get the price of the random datasource query with
// the above amount of callback gas, from randomness provider.
uint callbackPrice = randomnessProvider
.getPriceForRandomnessCallback( LOTTERY_RAND_CALLBACK_GAS );
// Also take into account the debt that we might owe to the
// Randomness Provider, if it previously executed requests
// with price being higher than we have gave it funds for.
//
// This situation can occur because we transfer lottery callback
// price funds before lottery starts, and when that lottery
// finishes (which can happen after several weeks), then
// the gas price might be higher than we have estimated
// and given funds for on lottery start.
// In this scenario, Randomness Provider would execute the
// request nonetheless, provided that it has enough funds in
// it's balance, to execute it.
//
// However, the Randomness Provider would notify us, that a
// debt of X ethers have been incurred, so we would have
// to transfer that debt's amount with next request's funds
// to Randomness Provider - and that's precisely what we
// are doing here, block.timestamp:
// Compute total cost of this lottery - initial funds,
// Randomness Provider callback cost, and debt from previous
// callback executions.
uint totalCost = cfg.initialFunds + callbackPrice +
randomnessProviderDebt;
// Check if our balance is enough to pay the cost.
// TODO: Implement more robust checks on minimum and maximum
// allowed fund restrictions.
require( totalCost <= address( this ).balance/*,
"Insufficient funds for this lottery start!" */);
// Deploy the new lottery contract using Factory.
Lottery lottery = Lottery( lotteryFactory.createNewLottery(
cfg, address( randomnessProvider ) ) );
// Check if the lottery's pool address and owner address
// are valid (same as ours).
require( lottery.poolAddress() == address( this ) &&
lottery.OWNER_ADDRESS() == OWNER_ADDRESS/*,
"Lottery's pool or owner addresses are invalid!" */);
// Transfer the Gas required for lottery end callback, and the
// debt (if some exists), into the Randomness Provider.
address( randomnessProvider ).transfer(
callbackPrice + randomnessProviderDebt );
// Clear the debt (if some existed) - it has been paid.
randomnessProviderDebt = 0;
// Notify the Randomness Provider about how much gas will be
// needed to run this lottery's ending callback, and how much
// funds we have given for it.
randomnessProvider.setLotteryCallbackGas(
address( lottery ),
LOTTERY_RAND_CALLBACK_GAS,
uint160( callbackPrice )
);
// Initialize the lottery - start the active lottery stage!
// Send initial funds to the lottery too.
lottery.initialize{ value: cfg.initialFunds }();
// Lottery was successfully initialized!
// Now, add it to tracking arrays, and emit events.
ongoingLotteries[ address(lottery) ] = true;
allLotteriesPerformed.push( lottery );
// Set is as the Most Recently Launched Lottery.
mostRecentLottery = lottery;
// Update current lottery funds.
currentLotteryFunds += cfg.initialFunds;
// Emit the apppproppppriate evenc.
emit LotteryStarted(
address( lottery ),
cfg.initialFunds,
( (_100PERCENT) * totalCost ) / totalPoolFunds(),
cfg
);
// Return the newly-successfully-started lottery.
return lottery;
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* When AUTO run-mode is set, this function schedules a new lottery
* to be started after the last Auto-Mode lottery has ended, after
* a specific time delay (by default, 1 day delay).
*
* Also, it's used to bootstrap the Auto-Mode loop - because
* it schedules a callback to get called.
*
* This function is called in 2 occasions:
*
* 1. When lotteryFinish() detects an AUTO run-mode, and so, a
* new Auto-Mode iteration needs to be performed.
*
* 2. When external actor bootstraps a new Auto-Mode cycle.
*
* Notice, that this function doesn't use require()'s - that's
* because it's getting called from lotteryFinish() too, and
* we don't want that function to fail just because some user
* set run mode to other value than AUTO during the time before.
* The only require() is when we check for re-entrancy.
*
* How Auto-Mode works?
* Everything is based on the Randomness Provider scheduled callback
* functionality, which is in turn based on Provable services.
* Basically, here we just schedule a scheduledCallback() to
* get called after a specified amount of time, and the
* scheduledCallback() performs the new lottery launch from the
* current next-lottery config.
*
* * What's payable?
* - We send funds to Randomness Provider, required to launch
* our callback later.
*/
function scheduleAutoModeCallback()
private
mutexLOCKED
returns( bool success )
{
// Firstly, check if mode is AUTO.
if( lotteryRunMode != LotteryRunMode.AUTO ) {
autoMode_currentCycleIterations = 0;
return false;
}
// Start a scheduled callback using the Randomness Provider
// service! But first, we gotta transfer the needed funds
// to the Provider.
// Get the price.
uint callbackPrice = randomnessProvider
.getPriceForScheduledCallback( AUTO_MODE_SCHEDULED_CALLBACK_GAS );
// Add the debt, if exists.
uint totalPrice = callbackPrice + randomnessProviderDebt;
if( totalPrice > address(this).balance ) {
return false;
}
// Send the required funds to the Rand.Provider.
// Use the send() function, because it returns false upon failure,
// and doesn't revert this transaction.
if( ! address( randomnessProvider ).send( totalPrice ) ) {
return false;
}
// Now, we've just paid the debt (if some existed).
randomnessProviderDebt = 0;
// Now, call the scheduling function of the Randomness Provider!
randomnessProvider.schedulePoolCallback(
autoMode_nextLotteryDelay,
AUTO_MODE_SCHEDULED_CALLBACK_GAS,
callbackPrice
);
// Set the time the callback was scheduled.
autoMode_timeCallbackScheduled = uint32( block.timestamp );
return true;
}
// ========= Public Functions ========= //
/**
* Constructor.
* - Here, we deploy the ULPT token contract.
* - Also, we deploy the Provable-powered Randomness Provider
* contract, which lotteries will use to get random seed.
* - We assign our Lottery Factory contract address to the passed
* parameter - the Lottery Factory contract which was deployed
* before, but not yet initialize()'d.
*
* Notice, that the msg.sender (the address who deployed the pool
* contract), doesn't play any special role in this nor any related
* contracts.
*/
constructor( address _lotteryFactoryAddr,
address _storageFactoryAddr,
address payable _randProvAddr )
{
// Initialize the randomness provider.
UniLotteryRandomnessProvider( _randProvAddr ).initialize();
randomnessProvider = UniLotteryRandomnessProvider( _randProvAddr );
// Set the Lottery Factory contract address, and initialize it!
UniLotteryLotteryFactory _lotteryFactory =
UniLotteryLotteryFactory( _lotteryFactoryAddr );
// Initialize the lottery factory, setting it to use the
// specified Storage Factory.
// After this point, factory states become immutable.
_lotteryFactory.initialize( _storageFactoryAddr );
// Assign the Storage Factory address.
// Set the immutable variables to their temporary placeholders.
storageFactory = _storageFactoryAddr;
lotteryFactory = _lotteryFactory;
// Set the first Owner-Approved address as the OWNER_ADDRESS
// itself.
ownerApprovedAddresses[ OWNER_ADDRESS ] = true;
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* The "Receive Ether" function.
* Used to receive Ether from Lotteries, and from the
* Randomness Provider, when retrieving funds.
*/
receive() external payable
{
emit EtherReceived( msg.sender, msg.value );
}
/**
* Get total funds of the pool -- the pool balance, and all the
* initial funds of every currently-ongoing lottery.
*/
function totalPoolFunds() public view
returns( uint256 )
{
// Get All Active Lotteries initial funds.
/*uint lotteryBalances = 0;
for( uint i = 0; i < ongoingLotteryList.length; i++ ) {
lotteryBalances +=
ongoingLotteryList[ i ].getActiveInitialFunds();
}*/
return address(this).balance + currentLotteryFunds;
}
/**
* Get current pool stats - number of poolholders,
* number of voters, etc.
*/
function getPoolStats()
public view
returns(
uint32 _numberOfLotteriesPerformed,
uint _totalPoolFunds,
uint _currentPoolBalance )
{
_numberOfLotteriesPerformed = uint32( allLotteriesPerformed.length );
_totalPoolFunds = totalPoolFunds();
_currentPoolBalance = address( this ).balance;
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Provide liquidity into the pool, and become a pool shareholder.
* - Function accepts Ether payments (No minimum deposit),
* and mints a proportionate number of ULPT tokens for the
* sender.
*/
function provideLiquidity()
external
payable
ownerApprovedAddressOnly
mutexLOCKED
{
// Check for minimum deposit.
//require( msg.value > MIN_DEPOSIT/*, "Deposit amount too low!" */);
// Compute the pool share that the user should obtain with
// the amount he paid in this message -- that is, compute
// percentage of the total pool funds (with new liquidity
// added), relative to the ether transferred in this msg.
// TotalFunds can't be zero, because currently transfered
// msg.value is already added to totalFunds.
//
// Also/*, "percentage" */can't exceed 100%, because condition
// "totalPoolFunds() >= msg.value" is ALWAYS true, because
// msg.value is already added to totalPoolFunds before
// execution of this function's body - transfers to
// "payable" functions are executed before the function's
// body executes (Solidity docs).
//
uint percentage = ( (_100PERCENT) * msg.value ) /
( totalPoolFunds() );
// Now, compute the amount of new ULPT tokens (x) to mint
// for this new liquidity provided, according to formula,
// whose explanation is provided below.
//
// Here, we assume variables:
//
// uintFormatPercentage: the "percentage" Solidity variable,
// defined above, in (uint percentage = ...) statement.
//
// x: the amount of ULPT tokens to mint for this liquidity
// provider, to maintain "percentage" ratio with the
// ULPT's totalSupply after minting (newTotalSupply).
//
// totalSupply: ULPT token's current total supply
// (as returned from totalSupply() function).
//
// Let's start the formula:
//
// ratio = uintFormatPercentage / (_100PERCENT)
// newTotalSupply = totalSupply + x
//
// x / newTotalSupply = ratio
// x / (totalSupply + x) = ratio
// x = ratio * (totalSupply + x)
// x = (ratio * totalSupply) + (ratio * x)
// x - (ratio * x) = (ratio * totalSupply)
// (1 * x) - (ratio * x) = (ratio * totalSupply)
// ( 1 - ratio ) * x = (ratio * totalSupply)
// x = (ratio * totalSupply) / ( 1 - ratio )
//
// ratio * totalSupply
// x = ------------------------------------------------
// 1 - ( uintFormatPercentage / (_100PERCENT) )
//
//
// ratio * totalSupply * (_100PERCENT)
// x = ---------------------------------------------------------------
// ( 1 - (uintFormatPercentage / (_100PERCENT)) )*(_100PERCENT)
//
// Let's abbreviate "_100PERCENT" to "100%".
//
// ratio * totalSupply * 100%
// x = ---------------------------------------------------------
// ( 1 * 100% ) - ( uintFormatPercentage / (100%) ) * (100%)
//
// ratio * totalSupply * 100%
// x = -------------------------------------
// 100% - uintFormatPercentage
//
// (uintFormatPercentage / (100%)) * totalSupply * 100%
// x = -------------------------------------------------------
// 100% - uintFormatPercentage
//
// (uintFormatPercentage / (100%)) * 100% * totalSupply
// x = -------------------------------------------------------
// 100% - uintFormatPercentage
//
// uintFormatPercentage * totalSupply
// x = ------------------------------------
// 100% - uintFormatPercentage
//
// So, with our Solidity variables, that would be:
// ==================================================== //
// //
// percentage * totalSupply //
// amountToMint = ------------------------------ //
// (_100PERCENT) - percentage //
// //
// ==================================================== //
//
// We know that "percentage" is ALWAYS <= 100%, because
// msg.value is already added to address(this).balance before
// the payable function's body executes.
//
// However, notice that when "percentage" approaches 100%,
// the denominator approaches 0, and that's not good.
//
// So, we must ensure that uint256 precision is enough to
// handle such situations, and assign a "default" value for
// amountToMint if such situation occurs.
//
// The most prominent case when this situation occurs, is on
// the first-ever liquidity provide, when ULPT total supply is
// zero, and the "percentage" value is 100%, because pool's
// balance was 0 before the operation.
//
// In such situation, we mint the 100 initial ULPT, which
// represent the pool share of the first ever pool liquidity
// provider, and that's 100% of the pool.
//
// Also, we do the same thing (mint 100 ULPT tokens), on all
// on all other situations when "percentage" is too close to 100%,
// such as when there's a very tiny amount of liquidity left in
// the pool.
//
// We check for those conditions based on precision of uint256
// number type.
// We know, that 256-bit uint can store up to roughly 10^74
// base-10 values.
//
// Also, in our formula:
// "totalSupply" can go to max. 10^30 (in extreme cases).
// "percentage" up to 10^12 (with more-than-enough precision).
//
// When multiplied, that's still only 10^(30+12) = 10^42 ,
// and that's still a long way to go to 10^74.
//
// So, the denominator "(_100PERCENT) - percentage" can go down
// to 1 safely, we must only ensure that it's not zero -
// and the uint256 type will take care of all precision needed.
//
if( balanceOf( msg.sender ) == 0 )
emit NewPoolholderJoin( msg.sender, msg.value );
// If percentage is below 100%, and totalSupply is NOT ZERO,
// work with the above formula.
if( percentage < (_100PERCENT) &&
totalSupply() != 0 )
{
// Compute the formula!
uint256 amountToMint =
( percentage * totalSupply() ) /
( (_100PERCENT) - percentage );
// Mint the computed amount.
_mint( msg.sender, amountToMint );
}
// Else, if the newly-added liquidity percentage is 100%
// (pool's balance was Zero before this liquidity provide), then
// just mint the initial 100 pool tokens.
else
{
_mint( msg.sender, ( 100 * (uint( 10 ) ** decimals) ) );
}
// Emit corresponding event, that liquidity has been added.
emit AddedLiquidity( msg.sender, msg.value );
emitPoolStats();
}
/**
* Get the current pool share (percentage) of a specified
* address. Return the percentage, compute from ULPT data.
*/
function getPoolSharePercentage( address holder )
public view
returns ( uint percentage )
{
return ( (_100PERCENT) * balanceOf( holder ) )
/ totalSupply();
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Remove msg.sender's pool liquidity share, and transfer it
* back to msg.sender's wallet.
* Burn the ULPT tokens that represented msg.sender's share
* of the pool.
* Notice that no activelyManaged modifier is present, which
* means that users are able to withdraw their money anytime.
*
* However, there's a caveat - if some lotteries are currently
* ongoing, the pool's current reserve balance might not be
* enough to meet every withdrawer's needs.
*
* In such scenario, withdrawers have either have to (OR'd):
* - Wait for ongoing lotteries to finish and return their
* funds back to the pool,
* - TODO: Vote for forceful termination of lotteries
* (vote can be done whether pool is active or not).
* - TODO: Wait for OWNER to forcefully terminate lotteries.
*
* Notice that last 2 options aren't going to be implemented
* in this version, because, as the OWNER is going to be the
* only pool shareholder in the begginning, lottery participants
* might see the forceful termination feature as an exit-scam
* threat, and this would damage project's reputation.
*
* The feature is going to be implemented in later versions,
* after security audits pass, pool is open to public,
* and a significant amount of wallets join a pool.
*/
function removeLiquidity(
uint256 ulptAmount )
external
ownerApprovedAddressOnly
mutexLOCKED
{
// Find out the real liquidity owner of this call -
// Check if the msg.sender is an approved-address, which can
// call this function on behalf of the true liquidity owner.
// Currently, this feature is only supported for OWNER_ADDRESS.
address payable liquidityOwner = OWNER_ADDRESS;
// Condition "balanceOf( liquidityOwner ) > 1" automatically
// checks if totalSupply() of ULPT is not zero, so we don't have
// to check it separately.
require( balanceOf( liquidityOwner ) > 1 &&
ulptAmount != 0 &&
ulptAmount <= balanceOf( liquidityOwner )/*,
"Specified ULPT token amount is invalid!" */);
// Now, compute share percentage, and send the appropriate
// amount of Ether from pool's balance to liquidityOwner.
uint256 percentage = ( (_100PERCENT) * ulptAmount ) /
totalSupply();
uint256 shareAmount = ( totalPoolFunds() * percentage ) /
(_100PERCENT);
require( shareAmount <= address( this ).balance/*,
"Insufficient pool contract balance!" */);
// Burn the specified amount of ULPT, thus removing the
// holder's pool share.
_burn( liquidityOwner, ulptAmount );
// Transfer holder's fund share as ether to holder's wallet.
liquidityOwner.transfer( shareAmount );
// Emit appropriate events.
if( balanceOf( liquidityOwner ) == 0 )
emit PoolholderWithdraw( liquidityOwner );
emit RemovedLiquidity( liquidityOwner, shareAmount );
emitPoolStats();
}
// ======== Lottery Management Section ======== //
// Check if lottery is currently ongoing.
function isLotteryOngoing( address lotAddr )
external view
returns( bool ) {
return ongoingLotteries[ lotAddr ];
}
// Get length of all lotteries performed.
function allLotteriesPerformed_length()
external view
returns( uint )
{
return allLotteriesPerformed.length;
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Ongoing (not-yet-completed) lottery finalization function.
* - This function is called by a currently ongoing lottery, to
* notify the pool about it's finishing.
* - After lottery calls this function, lottery is removed from
* ongoing lottery tracking list, and set to inactive.
*
* * Ether is transfered into our contract:
* Lottery transfers the pool profit share and initial funds
* back to the pool when calling this function, so the
*/
function lotteryFinish(
uint totalReturn,
uint profitAmount )
external
payable
calledByOngoingLotteryOnly
{
// "De-activate" this lottery.
//ongoingLotteries[ msg.sender ] = false;
delete ongoingLotteries[ msg.sender ]; // implies "false"
// We assume that totalReturn and profitAmount are valid,
// because this function can be called only by Lottery, which
// was deployed by us before.
// Update current lottery funds - this one is no longer active,
// so it's funds block.timestamp have been transfered to us.
uint lotFunds = Lottery( msg.sender ).getInitialFunds();
if( lotFunds < currentLotteryFunds )
currentLotteryFunds -= lotFunds;
else
currentLotteryFunds = 0;
// Emit approppriate events.
emit LotteryFinished( msg.sender, totalReturn, profitAmount );
// If AUTO-MODE is currently set, schedule a next lottery
// start using the current AUTO-MODE parameters!
// Ignore the return value, because AUTO-MODE params might be
// invalid, and we don't want our finish function to fail
// just because of that.
if( lotteryRunMode == LotteryRunMode.AUTO )
{
autoMode_isLotteryCurrentlyOngoing = false;
autoMode_lastLotteryFinished = uint32( block.timestamp );
scheduleAutoModeCallback();
}
}
/**
* The Callback function which Randomness Provider will call
* when executing the Scheduled Callback requests.
*
* We use this callback for scheduling Auto-Mode lotteries -
* when one lottery finishes, another one is scheduled to run
* after specified amount of time.
*
* In this callback, we start the scheduled Auto-Mode lottery.
*/
function scheduledCallback( uint256 /*requestID*/ )
public
{
// At first, check if mode is AUTO (not changed).
if( lotteryRunMode != LotteryRunMode.AUTO )
return;
// Check if we're not X-Ceeding the number of auto-iterations.
if( autoMode_currentCycleIterations >= autoMode_maxNumberOfRuns )
{
autoMode_currentCycleIterations = 0;
return;
}
// Launch an auto-lottery using the currently set next
// lottery config!
// When this lottery finishes, and the mode is still AUTO,
// one more lottery will be started.
launchLottery( nextLotteryConfig );
// Set the time started, and increment iterations.
autoMode_isLotteryCurrentlyOngoing = true;
autoMode_lastLotteryStarted = uint32( block.timestamp );
autoMode_currentCycleIterations++;
}
/**
* The Randomness Provider-callable function, which is used to
* ask pool for permission to execute lottery ending callback
* request with higher price than the pool-given funds for that
* specific lottery's ending request, when lottery was created.
*
* The function notifies the pool about the new and
* before-expected price, so the pool could compute a debt to
* be paid to the Randomnes Provider in next request.
*
* Here, we update our debt variable, which is the difference
* between current and expected-before request price,
* and we'll transfer the debt to Randomness Provider on next
* request to Randomness Provider.
*
* Notice, that we'll permit the execution of the lottery
* ending callback only if the new price is not more than
* 1.5x higher than before-expected price.
*
* This is designed so, because the Randomness Provider will
* call this function only if it has enough funds to execute the
* callback request, and just that the funds that we have transfered
* for this specific lottery's ending callback before, are lower
* than the current price of execution.
*
* Why is this the issue?
* Lottery can last for several weeks, and we give the callback
* execution funds for that specific lottery to Randomness Provider
* only on that lottery's initialization.
* So, after a few weeks, the Provable services might change the
* gas & fee prices, so the callback execution request price
* might change.
*/
function onLotteryCallbackPriceExceedingGivenFunds(
address /*lottery*/,
uint currentRequestPrice,
uint poolGivenExpectedRequestPrice )
external
randomnessProviderOnly
returns( bool callbackExecutionPermitted )
{
require( currentRequestPrice > poolGivenExpectedRequestPrice );
uint difference = currentRequestPrice - poolGivenExpectedRequestPrice;
// Check if the price difference is not bigger than the half
// of the before-expected pool-given price.
// Also, make sure that whole debt doesn't exceed 0.5 ETH.
if( difference <= ( poolGivenExpectedRequestPrice / 2 ) &&
( randomnessProviderDebt + difference ) < ( (1 ether) / 2 ) )
{
// Update our debt, to pay back the difference later,
// when we transfer funds for the next request.
randomnessProviderDebt += uint80( difference );
// Return true - the callback request execution is permitted.
return true;
}
// The price difference is higher - deny the execution.
return false;
}
// Below are the Owner-Callable voting-skipping functions, to set
// the next lottery config, lottery run mode, and other settings.
//
// When the final version is released, these functions will
// be removed, and every governance operation will be done
// through voting.
/**
* Set the LotteryConfig to be used by the next lottery.
* Owner-only callable.
*/
function setNextLotteryConfig(
Lottery.LotteryConfig memory cfg )
public
ownerApprovedAddressOnly
{
nextLotteryConfig = cfg;
emit NewConfigProposed( msg.sender, cfg, 0 );
// emitPoolStats();
}
/**
* Set the Lottery Run Mode to be used for further lotteries.
* It can be AUTO, or MANUAL (more about it on their descriptions).
*/
function setRunMode(
LotteryRunMode runMode )
external
ownerApprovedAddressOnly
{
// Check if it's one of allowed run modes.
require( runMode == LotteryRunMode.AUTO ||
runMode == LotteryRunMode.MANUAL/*,
"This Run Mode is not allowed in current state!" */);
// Emit a change event, with old value and new value.
emit LotteryRunModeChanged( lotteryRunMode, runMode );
// Set the new run mode!
lotteryRunMode = runMode;
// emitPoolStats();
}
/**
* Start a manual mode lottery from the previously set up
* next lottery config!
*/
function startManualModeLottery()
external
ownerApprovedAddressOnly
{
// Check if config is set - just check if initial funds
// are a valid value.
require( nextLotteryConfig.initialFunds != 0/*,
"Currently set next-lottery-config is invalid!" */);
// Launch a lottery using our private launcher function!
launchLottery( nextLotteryConfig );
emitPoolStats();
}
/**
* Set an Auto-Mode lottery run mode parameters.
* The auto-mode is implemented using Randomness Provider
* scheduled callback functionality, to schedule a lottery start
* on specific intervals.
*
* @param nextLotteryDelay - amount of time, in seconds, to wait
* when last lottery finishes, to start the next lottery.
*
* @param maxNumberOfRuns - max number of lottery runs in this
* Auto-Mode cycle. When it's reached, mode will switch to
* MANUAL automatically.
*/
function setAutoModeParameters(
uint32 nextLotteryDelay,
uint16 maxNumberOfRuns )
external
ownerApprovedAddressOnly
{
// Set params!
autoMode_nextLotteryDelay = nextLotteryDelay;
autoMode_maxNumberOfRuns = maxNumberOfRuns;
// emitPoolStats();
}
/**
* Starts an Auto-Mode lottery running cycle with currently
* specified Auto-Mode parameters.
* Notice that we must be on Auto run-mode currently.
*/
function startAutoModeCycle()
external
ownerApprovedAddressOnly
{
// Check that we're on the Auto-Mode block.timestamp.
require( lotteryRunMode == LotteryRunMode.AUTO/*,
"Current Run Mode is not AUTO!" */);
// Check if valid AutoMode params were specified.
require( autoMode_maxNumberOfRuns != 0/*,
"Invalid Auto-Mode params set!" */);
// Reset the cycle iteration counter.
autoMode_currentCycleIterations = 0;
// Start the Auto-Mode cycle using a scheduled callback!
scheduledCallback( 0 );
// emitPoolStats();
}
/**
* Set or Remove Owner-approved addresses.
* These addresses are used to call ownerOnly functions on behalf
* of the OWNER_ADDRESS (more detailed description above).
*/
function owner_setOwnerApprovedAddress( address addr )
external
ownerOnly
{
ownerApprovedAddresses[ addr ] = true;
}
function owner_removeOwnerApprovedAddress( address addr )
external
ownerOnly
{
delete ownerApprovedAddresses[ addr ];
}
/**
* ABIEncoderV2 - compatible getter for the nextLotteryConfig,
* which will be retuned as byte array internally, then internally
* de-serialized on receive.
*/
function getNextLotteryConfig()
external
view
returns( Lottery.LotteryConfig memory )
{
return nextLotteryConfig;
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Retrieve the UnClaimed Prizes of a completed lottery, if
* that lottery's prize claim deadline has already passed.
*
* - What's payable? This function causes a specific Lottery to
* transfer Ether from it's contract balance, to our contract.
*/
function retrieveUnclaimedLotteryPrizes(
address payable lottery )
external
ownerApprovedAddressOnly
mutexLOCKED
{
// Just call that function - if the deadline hasn't passed yet,
// that function will revert.
Lottery( lottery ).getUnclaimedPrizes();
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Retrieve the specified amount of funds from the Randomness
* Provider.
*
* WARNING: Future scheduled operations on randomness provider
* might FAIL if randomness provider won't have enough
* funds to execute that operation on that time!
*
* - What's payable? This function causes the Randomness Provider to
* transfer Ether from it's contract balance, to our contract.
*/
function retrieveRandomnessProviderFunds(
uint etherAmount )
external
ownerApprovedAddressOnly
mutexLOCKED
{
randomnessProvider.sendFundsToPool( etherAmount );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Send specific amount of funds to Randomness Provider, from
* our contract's balance.
* This is useful in cases when gas prices change, and current
* funds inside randomness provider are not enough to execute
* operations on the new gas cost.
*
* This operation is limited to 6 ethers once in 12 hours.
*
* - What's payable? We send Ether to the randomness provider.
*/
function provideRandomnessProviderFunds(
uint etherAmount )
external
ownerApprovedAddressOnly
mutexLOCKED
{
// Check if conditions apply!
require( ( etherAmount <= 6 ether ) &&
( block.timestamp - lastTimeRandomFundsSend > 12 hours )/*,
"Random Fund Provide Conditions are not satisfied!" */);
// Set the last-time-funds-sent timestamp to block.timestamp.
lastTimeRandomFundsSend = uint32( block.timestamp );
// Transfer the funds.
address( randomnessProvider ).transfer( etherAmount );
}
/**
* Set the Gas Price to use in the Randomness Provider.
* Used when very volatile gas prices are present during network
* congestions, when default is not enough.
*/
function setGasPriceOfRandomnessProvider(
uint gasPrice )
external
gasOracleAndOwnerApproved
{
randomnessProvider.setGasPrice( gasPrice );
}
/**
* Set the address of the so-called Gas Oracle, which is an
* automated script running on our server, and fetching gas prices.
*
* The address used by this script should be able to call
* ONLY the "setGasPriceOfRandomnessProvider" function (above).
*
* Here, we set that address.
*/
function setGasOracleAddress( address addr )
external
ownerApprovedAddressOnly
{
gasOracleAddress = addr;
}
}
contract Lottery is ERC20, CoreUniLotterySettings
{
// ===================== Events ===================== //
// After initialize() function finishes.
event LotteryInitialized();
// Emitted when lottery active stage ends (Mining Stage starts),
// on Mining Stage Step 1, after transferring profits to their
// respective owners (pool and OWNER_ADDRESS).
event LotteryEnd(
uint128 totalReturn,
uint128 profitAmount
);
// Emitted when on final finish, we call Randomness Provider
// to callback us with random value.
event RandomnessProviderCalled();
// Requirements for finishing stage start have been reached -
// finishing stage has started.
event FinishingStageStarted();
// We were currently on the finishing stage, but some requirement
// is no longer met. We must stop the finishing stage.
event FinishingStageStopped();
// New Referral ID has been generated.
event ReferralIDGenerated(
address referrer,
uint256 id
);
// New referral has been registered with a valid referral ID.
event ReferralRegistered(
address referree,
address referrer,
uint256 id
);
// Fallback funds received.
event FallbackEtherReceiver(
address sender,
uint value
);
// ====================== Structs & Enums ====================== //
// Lottery Stages.
// Described in more detail above, on contract's main doc.
enum STAGE
{
// Initial stage - before the initialize() function is called.
INITIAL,
// Active Stage: On this stage, all token trading occurs.
ACTIVE,
// Finishing stage:
// This is when all finishing criteria are met, and for every
// transfer, we're rolling a pseudo-random number to determine
// if we should end the lottery (move to Ending stage).
FINISHING,
// Ending - Mining Stage:
// This stage starts after we lottery is no longer active,
// finishing stage ends. On this stage, Miners perform the
// Ending Algorithm and other operations.
ENDING_MINING,
// Lottery is completed - this is set after the Mining Stage ends.
// In this stage, Lottery Winners can claim their prizes.
COMPLETION,
// DISABLED stage. Used when we want a lottery contract to be
// absolutely disabled - so no state-modifying functions could
// be called.
// This is used in DelegateCall scenarios, where state-contract
// delegate-calls code contract, to save on deployment costs.
DISABLED
}
// Ending algorithm types enum.
enum EndingAlgoType
{
// 1. Mined Winner Selection Algorithm.
// This algorithm is executed by a Lottery Miner in a single
// transaction, on Mining Step 2.
//
// On that single transaction, all ending scores for all
// holders are computed, and a sorted winner array is formed,
// which is written onto the LotteryStorage state.
// Thus, it's gas expensive, and suitable only for small
// holder numbers (up to 300).
//
// Pros:
// + Guaranteed deterministically specifiable winner prize
// distribution - for example, if we specify that there
// must be 2 winners, of which first gets 60% of prize funds,
// and second gets 40% of prize funds, then it's
// guarateed that prize funds will be distributed just
// like that.
//
// + Low gas cost of prize claims - only ~ 40,000 gas for
// claiming a prize.
//
// Cons:
// - Not scaleable - as the Winner Selection Algorithm is
// executed in a single transaction, it's limited by
// block gas limit - 12,500,000 on the MainNet.
// Thus, the lottery is limited to ~300 holders, and
// max. ~200 winners of those holders.
// So, it's suitable for only express-lotteries, where
// a lottery runs only until ~300 holders are reached.
//
// - High mining costs - if lottery has 300 holders,
// mining transaction takes up whole block gas limit.
//
MinedWinnerSelection,
// 2. Winner Self-Validation Algorithm.
//
// This algorithm does no operations during the Mining Stage
// (except for setting up a Random Seed in Lottery Storage) -
// the winner selection (obtaining a winner rank) is done by
// the winners themselves, when calling the prize claim
// functions.
//
// This algorithm relies on a fact that by the time that
// random seed is obtained, all data needed for winner selection
// is already there - the holder scores of the Active Stage
// (ether contributed, time factors, token balance), and
// the Random Data (random seed + nonce (holder's address)),
// so, there is no need to compute and sort the scores for the
// whole holder array.
//
// It's done like this: the holder checks if he's a winner, using
// a view-function off-chain, and if so, he calls the
// claimWinnerPrize() function, which obtains his winner rank
// on O(n) time, and does no writing to contract states,
// except for prize transfer-related operations.
//
// When computing the winner's rank on LotteryStorage,
// O(n) time is needed, as we loop through the holders array,
// computing ending scores for each holder, using already-known
// data.
// However that means that for every prize claim, all scores of
// all holders must be re-computed.
// Computing a score for a single holder takes roughly 1500 gas
// (400 for 3 slots SLOAD, and ~300 for arithmetic operations).
//
// So, this algorithm makes prize claims more expensive for
// every lottery holder.
// If there's 1000 holders, prize claim takes up 1,500,000 gas,
// so, this algorithm is not suitable for small prizes,
// because gas fee would be higher than the prize amount won.
//
// Pros:
// + Guaranteed deterministically specifiable winner prize
// distribution (same as for algorithm 1).
//
// + No mining costs for winner selection algorithm.
//
// + More scalable than algorithm 1.
//
// Cons:
// - High gas costs of prize claiming, rising with the number
// of lottery holders - 1500 for every lottery holder.
// Thus, suitable for only large prize amounts.
//
WinnerSelfValidation,
// 3. Rolled-Randomness algorithm.
//
// This algorithm is the most cheapest in terms of gas, but
// the winner prize distribution is non-deterministic.
//
// This algorithm doesn't employ miners (no mining costs),
// and doesn't require to compute scores for every holder
// prior to getting a winner's rank, thus is the most scalable.
//
// It works like this: a holder checks his winner status by
// computing only his own randomized score (rolling a random
// number from the random seed, and multiplying it by holder's
// Active Stage score), and computing this randomized-score's
// ratio relative to maximum available randomized score.
// The higher the ratio, the higher the winner rank is.
//
// However, many players can roll very high or low scores, and
// get the same prizes, so it's difficult to make a fair and
// efficient deterministic prize distribution mechanism, so
// we have to fallback to specific heuristic workarounds.
//
// Pros:
// + Scalable: O(1) complexity for computing a winner rank,
// so there can be an unlimited amount of lottery holders,
// and gas costs for winner selection and prize claim would
// still be constant & low.
//
// + Gas-efficient: gas costs for all winner-related operations
// are constant and low, because only single holder's score
// is computed.
//
// + Doesn't require mining - even more gas savings.
//
// Cons:
// + Hard to make a deterministic and fair prize distribution
// mechanism, because of un-known environment - as only
// single holder's score is compared to max-available
// random score, not taking into account other holder
// scores.
//
RolledRandomness
}
/**
* Gas-efficient, minimal config, which specifies only basic,
* most-important and most-used settings.
*/
struct LotteryConfig
{
// ================ Misc Settings =============== //
// --------- Slot --------- //
// Initial lottery funds (initial market cap).
// Specified by pool, and is used to check if initial funds
// transferred to fallback are correct - equal to this value.
uint initialFunds;
// --------- Slot --------- //
// The minimum ETH value of lottery funds, that, once
// reached on an exchange liquidity pool (Uniswap, or our
// contract), must be guaranteed to not shrink below this value.
//
// This is accomplished in _transfer() function, by denying
// all sells that would drop the ETH amount in liquidity pool
// below this value.
//
// But on initial lottery stage, before this minimum requirement
// is reached for the first time, all sells are allowed.
//
// This value is expressed in ETH - total amount of ETH funds
// that we own in Uniswap liquidity pair.
//
// So, if initial funds were 10 ETH, and this is set to 100 ETH,
// after liquidity pool's ETH value reaches 100 ETH, all further
// sells which could drop the liquidity amount below 100 ETH,
// would be denied by require'ing in _transfer() function
// (transactions would be reverted).
//
uint128 fundRequirement_denySells;
// ETH value of our funds that we own in Uniswap Liquidity Pair,
// that's needed to start the Finishing Stage.
uint128 finishCriteria_minFunds;
// --------- Slot --------- //
// Maximum lifetime of a lottery - maximum amount of time
// allowed for lottery to stay active.
// By default, it's two weeks.
// If lottery is still active (hasn't returned funds) after this
// time, lottery will stop on the next token transfer.
uint32 maxLifetime;
// Maximum prize claiming time - for how long the winners
// may be able to claim their prizes after lottery ending.
uint32 prizeClaimTime;
// Token transfer burn rates for buyers, and a default rate for
// sells and non-buy-sell transfers.
uint32 burn_buyerRate;
uint32 burn_defaultRate;
// Maximum amount of tokens (in percentage of initial supply)
// to be allowed to own by a single wallet.
uint32 maxAmountForWallet_percentageOfSupply;
// The required amount of time that must pass after
// the request to Randomness Provider has been made, for
// external actors to be able to initiate alternative
// seed generation algorithm.
uint32 REQUIRED_TIME_WAITING_FOR_RANDOM_SEED;
// ================ Profit Shares =============== //
// "Mined Uniswap Lottery" ending Ether funds, which were obtained
// by removing token liquidity from Uniswap, are transfered to
// these recipient categories:
//
// 1. The Main Pool: Initial funds, plus Pool's profit share.
// 2. The Owner: Owner's profit share.
//
// 3. The Miners: Miner rewards for executing the winner
// selection algorithm stages.
// The more holders there are, the more stages the
// winner selection algorithm must undergo.
// Each Miner, who successfully completed an algorithm
// stage, will get ETH reward equal to:
// (minerProfitShare / totalAlgorithmStages).
//
// 4. The Lottery Winners: All remaining funds are given to
// Lottery Winners, which were determined by executing
// the Winner Selection Algorithm at the end of the lottery
// (Miners executed it).
// The Winners can claim their prizes by calling a
// dedicated function in our contract.
//
// The profit shares of #1 and #2 have controlled value ranges
// specified in CoreUniLotterySettings.
//
// All these shares are expressed as percentages of the
// lottery profit amount (totalReturn - initialFunds).
// Percentages are expressed using the PERCENT constant,
// defined in CoreUniLotterySettings.
//
// Here we specify profit shares of Pool, Owner, and the Miners.
// Winner Prize Fund is all that's left (must be more than 50%
// of all profits).
//
uint32 poolProfitShare;
uint32 ownerProfitShare;
// --------- Slot --------- //
uint32 minerProfitShare;
// =========== Lottery Finish criteria =========== //
// Lottery finish by design is a whole soft stage, that
// starts when criteria for holders and fund gains are met.
// During this stage, for every token transfer, a pseudo-random
// number will be rolled for lottery finish, with increasing
// probability.
//
// There are 2 ways that this probability increase is
// implemented:
// 1. Increasing on every new holder.
// 2. Increasing on every transaction after finish stage
// was initiated.
//
// On every new holder, probability increases more than on
// new transactions.
//
// However, if during this stage some criteria become
// no-longer-met, the finish stage is cancelled.
// This cancel can be implemented by setting finish probability
// to zero, or leaving it as it was, but pausing the finishing
// stage.
// This is controlled by finish_resetProbabilityOnStop flag -
// if not set, probability stays the same, when the finishing
// stage is discontinued.
// ETH value of our funds that we own in Uniswap Liquidity Pair,
// that's needed to start the Finishing Stage.
//
// LOOK ABOVE - arranged for tight-packing.
// Minimum number of token holders required to start the
// finishing stage.
uint32 finishCriteria_minNumberOfHolders;
// Minimum amount of time that lottery must be active.
uint32 finishCriteria_minTimeActive;
// Initial finish probability, when finishing stage was
// just initiated.
uint32 finish_initialProbability;
// Finishing probability increase steps, for every new
// transaction and every new holder.
// If holder number decreases, probability decreases.
uint32 finish_probabilityIncreaseStep_transaction;
uint32 finish_probabilityIncreaseStep_holder;
// =========== Winner selection config =========== //
// Winner selection algorithm settings.
//
// Algorithm is based on score, which is calculated for
// every holder on lottery finish, and is comprised of
// the following parts.
// Each part is normalized to range ( 0 - scorePoints ),
// from smallest to largest value of each holder;
//
// After scores are computed, they are multiplied by
// holder count factor (holderCount / holderCountDivisor),
// and finally, multiplied by safely-generated random values,
// to get end winning scores.
// The top scorers win prizes.
//
// By default setting, max score is 40 points, and it's
// comprised of the following parts:
//
// 1. Ether contributed (when buying from Uniswap or contract).
// Gets added when buying, and subtracted when selling.
// Default: 10 points.
//
// 2. Amount of lottery tokens holder has on finish.
// Default: 5 points.
//
// 3. Ether contributed, multiplied by the relative factor
// of time - that is/*, "block.timestamp" */minus "lotteryStartTime".
// This way, late buyers can get more points even if
// they get little tokens and don't spend much ether.
// Default: 5 points.
//
// 4. Refferrer bonus. For every player that joined with
// your referral ID, you get (that player's score) / 10
// points! This goes up to specified max score.
// Also, every player who provides a valid referral ID,
// gets 2 points for free!
// Default max bonus: 20 points.
//
int16 maxPlayerScore_etherContributed;
int16 maxPlayerScore_tokenHoldingAmount;
int16 maxPlayerScore_timeFactor;
int16 maxPlayerScore_refferalBonus;
// --------- Slot --------- //
// Score-To-Random ration data (as a rational ratio number).
// For example if 1:5, then scorePart = 1, and randPart = 5.
uint16 randRatio_scorePart;
uint16 randRatio_randPart;
// Time factor divisor - interval of time, in seconds, after
// which time factor is increased by one.
uint16 timeFactorDivisor;
// Bonus score a player should get when registering a valid
// referral code obtained from a referrer.
int16 playerScore_referralRegisteringBonus;
// Are we resetting finish probability when finishing stage
// stops, if some criteria are no longer met?
bool finish_resetProbabilityOnStop;
// =========== Winner Prize Fund Settings =========== //
// There are 2 available modes that we can use to distribute
// winnings: a computable sequence (geometrical progression),
// or an array of winner prize fund share percentages.
// More gas efficient is to use a computable sequence,
// where each winner gets a share equal to (factor * fundsLeft).
// Factor is in range [0.01 - 1.00] - simulated as [1% - 100%].
//
// For example:
// Winner prize fund is 100 ethers, Factor is 1/4 (25%), and
// there are 5 winners total (winnerCount), and sequenced winner
// count is 2 (sequencedWinnerCount).
//
// So, we pre-compute the upper shares, till we arrive to the
// sequenced winner count, in a loop:
// - Winner 1: 0.25 * 100 = 25 eth; 100 - 25 = 75 eth left.
// - Winner 2: 0.25 * 75 ~= 19 eth; 75 - 19 = 56 eth left.
//
// Now, we compute the left-over winner shares, which are
// winners that get their prizes from the funds left after the
// sequence winners.
//
// So, we just divide the leftover funds (56 eth), by 3,
// because winnerCount - sequencedWinnerCount = 3.
// - Winner 3 = 56 / 3 = 18 eth;
// - Winner 4 = 56 / 3 = 18 eth;
// - Winner 5 = 56 / 3 = 18 eth;
//
// If this value is 0, then we'll assume that array-mode is
// to be used.
uint32 prizeSequenceFactor;
// Maximum number of winners that the prize sequence can yield,
// plus the leftover winners, which will get equal shares of
// the remainder from the first-prize sequence.
uint16 prizeSequence_winnerCount;
// How many winners would get sequence-computed prizes.
// The left-over winners
// This is needed because prizes in sequence tend to zero, so
// we need to limit the sequence to avoid very small prizes,
// and to avoid the remainder.
uint16 prizeSequence_sequencedWinnerCount;
// Initial token supply (without decimals).
uint48 initialTokenSupply;
// Ending Algorithm type.
// More about the 3 algorithm types above.
uint8 endingAlgoType;
// --------- Slot --------- //
// Array mode: The winner profit share percentages array.
// For example, lottery profits can be distributed this way:
//
// Winner profit shares (8 winners):
// [ 20%, 15%, 10%, 5%, 4%, 3%, 2%, 1% ] = 60% of profits.
// Owner profits: 10%
// Pool profits: 30%
//
// Pool profit share is not defined explicitly in the config, so
// when we internally validate specified profit shares, we
// assume the pool share to be the left amount until 100% ,
// but we also make sure that this amount is at least equal to
// MIN_POOL_PROFITS, defined in CoreSettings.
//
uint32[] winnerProfitShares;
}
// ========================= Constants ========================= //
// The Miner Profits - max/min values.
// These aren't defined in Core Settings, because Miner Profits
// are only specific to this lottery type.
uint32 constant MIN_MINER_PROFITS = 1 * PERCENT;
uint32 constant MAX_MINER_PROFITS = 10 * PERCENT;
// Uniswap Router V2 contract instance.
// Address is the same for MainNet, and all public testnets.
IUniswapRouter constant uniswapRouter = IUniswapRouter(
address( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ) );
// Public-accessible ERC20 token specific constants.
string constant public name = "UniLottery Token";
string constant public symbol = "ULT";
uint256 constant public decimals = 18;
// =================== State Variables =================== //
// ------- Initial Slots ------- //
// The config which is passed to constructor.
LotteryConfig internal cfg;
// ------- Slot ------- //
// The Lottery Storage contract, which stores all holder data,
// such as scores, referral tree data, etc.
LotteryStorage public lotStorage;
// ------- Slot ------- //
// Pool address. Set on constructor from msg.sender.
address payable public poolAddress;
// ------- Slot ------- //
// Randomness Provider address.
address public randomnessProvider;
// ------- Slot ------- //
// Exchange address. In Uniswap mode, it's the Uniswap liquidity
// pair's address, where trades execute.
address public exchangeAddress;
// Start date.
uint32 public startDate;
// Completion (Mining Phase End) date.
uint32 public completionDate;
// The date when Randomness Provider was called, requesting a
// random seed for the lottery finish.
// Also, when this variable becomes Non-Zero, it indicates that we're
// on Ending Stage Part One: waiting for the random seed.
uint32 finish_timeRandomSeedRequested;
// ------- Slot ------- //
// WETH address. Set by calling Router's getter, on constructor.
address WETHaddress;
// Is the WETH first or second token in our Uniswap Pair?
bool uniswap_ethFirst;
// If we are, or were before, on finishing stage, this is the
// probability of lottery going to Ending Stage on this transaction.
uint32 finishProbablity;
// Re-Entrancy Lock (Mutex).
// We protect for reentrancy in the Fund Transfer functions.
bool reEntrancyMutexLocked;
// On which stage we are currently.
uint8 public lotteryStage;
// Indicator for whether the lottery fund gains have passed a
// minimum fund gain requirement.
// After that time point (when this bool is set), the token sells
// which could drop the fund value below the requirement, would
// be denied.
bool fundGainRequirementReached;
// The current step of the Mining Stage.
uint16 miningStep;
// If we're currently on Special Transfer Mode - that is, we allow
// direct transfers between parties even in NON-ACTIVE state.
bool specialTransferModeEnabled;
// ------- Slot ------- //
// Per-Transaction Pseudo-Random hash value (transferHashValue).
// This value is computed on every token transfer, by keccak'ing
// the last (current) transferHashValue, msg.sender, block.timestamp, and
// transaction count.
//
// This is used on Finishing Stage, as a pseudo-random number,
// which is used to check if we should end the lottery (move to
// Ending Stage).
uint256 transferHashValue;
// ------- Slot ------- //
// On lottery end, get & store the lottery total ETH return
// (including initial funds), and profit amount.
uint128 public ending_totalReturn;
uint128 public ending_profitAmount;
// ------- Slot ------- //
// The mapping that contains TRUE for addresses that already claimed
// their lottery winner prizes.
// Used only in COMPLETION, on claimWinnerPrize(), to check if
// msg.sender has already claimed his prize.
mapping( address => bool ) public prizeClaimersAddresses;
// ============= Private/internal functions ============= //
// Pool Only modifier.
modifier poolOnly {
require( msg.sender == poolAddress/*,
"Function can be called only by the pool!" */);
_;
}
// Only randomness provider allowed modifier.
modifier randomnessProviderOnly {
require( msg.sender == randomnessProvider/*,
"Function can be called only by the UniLottery"
" Randomness Provider!" */);
_;
}
// Execute function only on specific lottery stage.
modifier onlyOnStage( STAGE _stage )
{
require( lotteryStage == uint8( _stage )/*,
"Function cannot be called on current stage!" */);
_;
}
// Modifier for protecting the function from re-entrant calls,
// by using a locked Re-Entrancy Lock (Mutex).
modifier mutexLOCKED
{
require( ! reEntrancyMutexLocked/*,
"Re-Entrant Calls are NOT ALLOWED!" */);
reEntrancyMutexLocked = true;
_;
reEntrancyMutexLocked = false;
}
// Check if we're currently on a specific stage.
function onStage( STAGE _stage )
internal view
returns( bool )
{
return ( lotteryStage == uint8( _stage ) );
}
/**
* Check if token transfer to specific wallet won't exceed
* maximum token amount allowed to own by a single wallet.
*
* @return true, if holder's balance with "amount" added,
* would exceed the max allowed single holder's balance
* (by default, that is 5% of total supply).
*/
function transferExceedsMaxBalance(
address holder, uint amount )
internal view
returns( bool )
{
uint maxAllowedBalance =
( totalSupply() * cfg.maxAmountForWallet_percentageOfSupply ) /
( _100PERCENT );
return ( ( balanceOf( holder ) + amount ) > maxAllowedBalance );
}
/**
* Update holder data.
* This function is called by _transfer() function, just before
* transfering final amount of tokens directly from sender to
* receiver.
* At this point, all burns/mints have been done, and we're sure
* that this transfer is valid and must be successful.
*
* In all modes, this function is used to update the holder array.
*
* However, on external exchange modes (e.g. on Uniswap mode),
* it is also used to track buy/sell ether value, to update holder
* scores, when token buys/sells cannot be tracked directly.
*
* If, however, we use Standalone mode, we are the exchange,
* so on _transfer() we already know the ether value, which is
* set to currentBuySellEtherValue variable.
*
* @param amountSent - the token amount that is deducted from
* sender's balance. This includes burn, and owner fee.
*
* @param amountReceived - the token amount that receiver
* actually receives, after burns and fees.
*
* @return holderCountChanged - indicates whether holder count
* changes during this transfer - new holder joins or leaves
* (true), or no change occurs (false).
*/
function updateHolderData_preTransfer(
address sender,
address receiver,
uint256 amountSent,
uint256 amountReceived )
internal
returns( bool holderCountChanged )
{
// Update holder array, if new token holder joined, or if
// a holder transfered his whole balance.
holderCountChanged = false;
// Sender transferred his whole balance - no longer a holder.
if( balanceOf( sender ) == amountSent )
{
lotStorage.removeHolder( sender );
holderCountChanged = true;
}
// Receiver didn't have any tokens before - add it to holders.
if( balanceOf( receiver ) == 0 && amountReceived > 0 )
{
lotStorage.addHolder( receiver );
holderCountChanged = true;
}
// Update holder score factors: if buy/sell occured, update
// etherContributed and timeFactors scores,
// and also propagate the scores through the referral chain
// to the parent referrers (this is done in Storage contract).
// This lottery operates only on external exchange (Uniswap)
// mode, so we have to find out the buy/sell Ether value by
// calling the external exchange (Uniswap pair) contract.
// Temporary variable to store current transfer's buy/sell
// value in Ethers.
int buySellValue;
// Sender is an exchange - buy detected.
if( sender == exchangeAddress && receiver != exchangeAddress )
{
// Use the Router's functionality.
// Set the exchange path to WETH -> ULT
// (ULT is Lottery Token, and it's address is our address).
address[] memory path = new address[]( 2 );
path[ 0 ] = WETHaddress;
path[ 1 ] = address(this);
uint[] memory ethAmountIn = uniswapRouter.getAmountsIn(
amountSent, // uint amountOut,
path // address[] path
);
buySellValue = int( ethAmountIn[ 0 ] );
// Compute time factor value for the current ether value.
// buySellValue is POSITIVE.
// When computing Time Factors, leave only 2 ether decimals.
int timeFactorValue = ( buySellValue / (1 ether / 100) ) *
int( (block.timestamp - startDate) / cfg.timeFactorDivisor );
if( timeFactorValue == 0 )
timeFactorValue = 1;
// Update and propagate the buyer (receiver) scores.
lotStorage.updateAndPropagateScoreChanges(
receiver,
int80( buySellValue ),
int80( timeFactorValue ),
int80( amountReceived ) );
}
// Receiver is an exchange - sell detected.
else if( sender != exchangeAddress && receiver == exchangeAddress )
{
// Use the Router's functionality.
// Set the exchange path to ULT -> WETH
// (ULT is Lottery Token, and it's address is our address).
address[] memory path = new address[]( 2 );
path[ 0 ] = address(this);
path[ 1 ] = WETHaddress;
uint[] memory ethAmountOut = uniswapRouter.getAmountsOut(
amountReceived, // uint amountIn
path // address[] path
);
// It's a sell (ULT -> WETH), so set value to NEGATIVE.
buySellValue = int( -1 ) * int( ethAmountOut[ 1 ] );
// Compute time factor value for the current ether value.
// buySellValue is NEGATIVE.
int timeFactorValue = ( buySellValue / (1 ether / 100) ) *
int( (block.timestamp - startDate) / cfg.timeFactorDivisor );
if( timeFactorValue == 0 )
timeFactorValue = -1;
// Update and propagate the seller (sender) scores.
lotStorage.updateAndPropagateScoreChanges(
sender,
int80( buySellValue ),
int80( timeFactorValue ),
-1 * int80( amountSent ) );
}
// Neither Sender nor Receiver are exchanges - default transfer.
// Tokens just got transfered between wallets, without
// exchanging for ETH - so etherContributed_change = 0.
// On this case, update both sender's & receiver's scores.
//
else {
buySellValue = 0;
lotStorage.updateAndPropagateScoreChanges( sender, 0, 0,
-1 * int80( amountSent ) );
lotStorage.updateAndPropagateScoreChanges( receiver, 0, 0,
int80( amountReceived ) );
}
// Check if lottery liquidity pool funds have already
// reached a minimum required ETH value.
uint ethFunds = getCurrentEthFunds();
if( !fundGainRequirementReached &&
ethFunds >= cfg.fundRequirement_denySells )
{
fundGainRequirementReached = true;
}
// Check whether this token transfer is allowed if it's a sell
// (if buySellValue is negative):
//
// If we've already reached the minimum fund gain requirement,
// and this sell would shrink lottery liquidity pool's ETH funds
// below this requirement, then deny this sell, causing this
// transaction to fail.
if( fundGainRequirementReached &&
buySellValue < 0 &&
( uint( -1 * buySellValue ) >= ethFunds ||
ethFunds - uint( -1 * buySellValue ) <
cfg.fundRequirement_denySells ) )
{
require( false/*, "This sell would drop the lottery ETH funds"
"below the minimum requirement threshold!" */);
}
}
/**
* Check for finishing stage start conditions.
* - If some conditions are met, start finishing stage!
* Do it by setting "onFinishingStage" bool.
* - If we're currently on finishing stage, and some condition
* is no longer met, then stop the finishing stage.
*/
function checkFinishingStageConditions()
internal
{
// Firstly, check if lottery hasn't exceeded it's maximum lifetime.
// If so, don't check anymore, just set finishing stage, and
// end the lottery on further call of checkForEnding().
if( (block.timestamp - startDate) > cfg.maxLifetime )
{
lotteryStage = uint8( STAGE.FINISHING );
return;
}
// Compute & check the finishing criteria.
// Notice that we adjust the config-specified fund gain
// percentage increase to uint-mode, by adding 100 percents,
// because we don't deal with negative percentages, and here
// we represent loss as a percentage below 100%, and gains
// as percentage above 100%.
// So, if in regular gains notation, it's said 10% gain,
// in uint mode, it's said 110% relative increase.
//
// (Also, remember that losses are impossible in our lottery
// working scheme).
if( lotStorage.getHolderCount() >= cfg.finishCriteria_minNumberOfHolders
&&
getCurrentEthFunds() >= cfg.finishCriteria_minFunds
&&
(block.timestamp - startDate) >= cfg.finishCriteria_minTimeActive )
{
if( onStage( STAGE.ACTIVE ) )
{
// All conditions are met - start the finishing stage.
lotteryStage = uint8( STAGE.FINISHING );
emit FinishingStageStarted();
}
}
else if( onStage( STAGE.FINISHING ) )
{
// However, what if some condition was not met, but we're
// already on the finishing stage?
// If so, we must stop the finishing stage.
// But what to do with the finishing probability?
// Config specifies if it should be reset or maintain it's
// value until the next time finishing stage is started.
lotteryStage = uint8( STAGE.ACTIVE );
if( cfg.finish_resetProbabilityOnStop )
finishProbablity = cfg.finish_initialProbability;
emit FinishingStageStopped();
}
}
/**
* We're currently on finishing stage - so let's check if
* we should end the lottery block.timestamp!
*
* This function is called from _transfer(), only if we're sure
* that we're currently on finishing stage (onFinishingStage
* variable is set).
*
* Here, we compute the pseudo-random number from hash of
* current message's sender, block.timestamp, and other values,
* and modulo it to the current finish probability.
* If it's equal to 1, then we end the lottery!
*
* Also, here we update the finish probability according to
* probability update criteria - holder count, and tx count.
*
* @param holderCountChanged - indicates whether Holder Count
* has changed during this transfer (new holder joined, or
* a holder sold all his tokens).
*/
function checkForEnding( bool holderCountChanged )
internal
{
// At first, check if lottery max lifetime is exceeded.
// If so, start ending procedures right block.timestamp.
if( (block.timestamp - startDate) > cfg.maxLifetime )
{
startEndingStage();
return;
}
// Now, we know that lottery lifetime is still OK, and we're
// currently on Finishing Stage (because this function is
// called only when onFinishingStage is set).
//
// Now, check if we should End the lottery, by computing
// a modulo on a pseudo-random number, which is a transfer
// hash, computed for every transfer on _transfer() function.
//
// Get the modulo amount according to current finish
// probability.
// We use precision of 0.01% - notice the "10000 *" before
// 100 PERCENT.
// Later, when modulo'ing, we'll check if value is below 10000.
//
uint prec = 10000;
uint modAmount = (prec * _100PERCENT) / finishProbablity;
if( ( transferHashValue % modAmount ) <= prec )
{
// Finish probability is met! Commence lottery end -
// start Ending Stage.
startEndingStage();
return;
}
// Finish probability wasn't met.
// Update the finish probability, by increasing it!
// Transaction count criteria.
// As we know that this function is called on every new
// transfer (transaction), we don't check if transactionCount
// increased or not - we just perform probability update.
finishProbablity += cfg.finish_probabilityIncreaseStep_transaction;
// Now, perform holder count criteria update.
// Finish probability increases, no matter if holder count
// increases or decreases.
if( holderCountChanged )
finishProbablity += cfg.finish_probabilityIncreaseStep_holder;
}
/**
* Start the Ending Stage, by De-Activating the lottery,
* to deny all further token transfers (excluding the one when
* removing liquidity from Uniswap), and transition into the
* Mining Phase - set the lotteryStage to MINING.
*/
function startEndingStage()
internal
{
lotteryStage = uint8( STAGE.ENDING_MINING );
}
/**
* Execute the first step of the Mining Stage - request a
* Random Seed from the Randomness Provider.
*
* Here, we call the Randomness Provider, asking for a true random seed
* to be passed to us into our callback, named
* "finish_randomnessProviderCallback()".
*
* When that callback will be called, our storage's random seed will
* be set, and we'll be able to start the Ending Algorithm on
* further mining steps.
*
* Notice that Randomness Provider must already be funded, to
* have enough Ether for Provable fee and the gas costs of our
* callback function, which are quite high, because of winner
* selection algorithm, which is computationally expensive.
*
* The Randomness Provider is always funded by the Pool,
* right before the Pool deploys and starts a new lottery, so
* as every lottery calls the Randomness Provider only once,
* the one-call-fund method for every lottery is sufficient.
*
* Also notice, that Randomness Provider might fail to call
* our callback due to some unknown reasons!
* Then, the lottery profits could stay locked in this
* lottery contract forever ?!!
*
* No! We've thought about that - we've implemented the
* Alternative Ending mechanism, where, if specific time passes
* after we've made a request to Randomness Provider, and
* callback hasn't been called yet, we allow external actor to
* execute the Alternative ending, which basically does the
* same things as the default ending, just that the Random Seed
* will be computed locally in our contract, using the
* Pseudo-Random mechanism, which could compute a reasonably
* fair and safe value using data from holder array, and other
* values, described in more detail on corresponding function's
* description.
*/
function mine_requestRandomSeed()
internal
{
// We're sure that the Randomness Provider has enough funds.
// Execute the random request, and get ready for Ending Algorithm.
IRandomnessProvider( randomnessProvider )
.requestRandomSeedForLotteryFinish();
// Store the time when random seed has been requested, to
// be able to alternatively handle the lottery finish, if
// randomness provider doesn't call our callback for some
// reason.
finish_timeRandomSeedRequested = uint32( block.timestamp );
// Emit appropriate events.
emit RandomnessProviderCalled();
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Transfer the Owner & Pool profit shares, when lottery ends.
* This function is the first one that's executed on the Mining
* Stage.
* This is the first step of Mining. So, the Miner who executes this
* function gets the mining reward.
*
* This function's job is to Gather the Profits & Initial Funds,
* and Transfer them to Profiters - that is, to The Pool, and
* to The Owner.
*
* The Miners' profit share and Winner Prize Fund stay in this
* contract.
*
* On this function, we (in this order):
*
* 1. Remove all liquidity from Uniswap (if using Uniswap Mode),
* pulling it to our contract's wallet.
*
* 2. Transfer the Owner and the Pool ETH profit shares to
* Owner and Pool addresses.
*
* * This function transfers Ether out of our contract:
* - We transfer the Profits to Pool and Owner addresses.
*/
function mine_removeUniswapLiquidityAndTransferProfits()
internal
mutexLOCKED
{
// We've already approved our token allowance to Router.
// Now, approve Uniswap liquidity token's Router allowance.
ERC20( exchangeAddress ).approve( address(uniswapRouter), uint(-1) );
// Enable the SPECIAL-TRANSFER mode, to allow Uniswap to transfer
// the tokens from Pair to Router, and then from Router to us.
specialTransferModeEnabled = true;
// Remove liquidity!
uint amountETH = uniswapRouter
.removeLiquidityETHSupportingFeeOnTransferTokens(
address(this), // address token,
ERC20( exchangeAddress ).balanceOf( address(this) ),
0, // uint amountTokenMin,
0, // uint amountETHMin,
address(this), // address to,
(block.timestamp + 10000000) // uint deadline
);
// Tokens are transfered. Disable the special transfer mode.
specialTransferModeEnabled = false;
// Check that we've got a correct amount of ETH.
require( address(this).balance >= amountETH &&
address(this).balance >= cfg.initialFunds/*,
"Incorrect amount of ETH received from Uniswap!" */);
// Compute the Profit Amount (current balance - initial funds).
ending_totalReturn = uint128( address(this).balance );
ending_profitAmount = ending_totalReturn - uint128( cfg.initialFunds );
// Compute, and Transfer Owner's profit share and
// Pool's profit share to their respective addresses.
uint poolShare = ( ending_profitAmount * cfg.poolProfitShare ) /
( _100PERCENT );
uint ownerShare = ( ending_profitAmount * cfg.ownerProfitShare ) /
( _100PERCENT );
// To pool, transfer it's profit share plus initial funds.
IUniLotteryPool( poolAddress ).lotteryFinish
{ value: poolShare + cfg.initialFunds }
( ending_totalReturn, ending_profitAmount );
// Transfer Owner's profit share.
OWNER_ADDRESS.transfer( ownerShare );
// Emit ending event.
emit LotteryEnd( ending_totalReturn, ending_profitAmount );
}
/**
* Executes a single step of the Winner Selection Algorithm
* (the Ending Algorithm).
* The algorithm itself is being executed in the Storage contract.
*
* On current design, whole algorithm is executed in a single step.
*
* This function is executed only in the Mining stage, and
* accounts for most of the gas spent during mining.
*/
function mine_executeEndingAlgorithmStep()
internal
{
// Launch the winner algorithm, to execute the next step.
lotStorage.executeWinnerSelectionAlgorithm();
}
// =============== Public functions =============== //
/**
* Constructor of this delegate code contract.
* Here, we set OUR STORAGE's lotteryStage to DISABLED, because
* we don't want anybody to call this contract directly.
*/
constructor()
{
lotteryStage = uint8( STAGE.DISABLED );
}
/**
* Construct the lottery contract which is delegating it's
* call to us.
*
* @param config - LotteryConfig structure to use in this lottery.
*
* Future approach: ABI-encoded Lottery Config
* (different implementations might use different config
* structures, which are ABI-decoded inside the implementation).
*
* Also, this "config" includes the ABI-encoded temporary values,
* which are not part of persisted LotteryConfig, but should
* be used only in constructor - for example, values to be
* assigned to storage variables, such as ERC20 token's
* name, symbol, and decimals.
*
* @param _poolAddress - Address of the Main UniLottery Pool, which
* provides initial funds, and receives it's profit share.
*
* @param _randomProviderAddress - Address of a Randomness Provider,
* to use for obtaining random seeds.
*
* @param _storageAddress - Address of a Lottery Storage.
* Storage contract is a separate contract which holds all
* lottery token holder data, such as intermediate scores.
*
*/
function construct(
LotteryConfig memory config,
address payable _poolAddress,
address _randomProviderAddress,
address _storageAddress )
external
{
// Check if contract wasn't already constructed!
require( poolAddress == address( 0 )/*,
"Contract is already constructed!" */);
// Set the Pool's Address - notice that it's not the
// msg.sender, because lotteries aren't created directly
// by the Pool, but by the Lottery Factory!
poolAddress = _poolAddress;
// Set the Randomness Provider address.
randomnessProvider = _randomProviderAddress;
// Check the minimum & maximum requirements for config
// profit & lifetime parameters.
require( config.maxLifetime <= MAX_LOTTERY_LIFETIME/*,
"Lottery maximum lifetime is too high!" */);
require( config.poolProfitShare >= MIN_POOL_PROFITS &&
config.poolProfitShare <= MAX_POOL_PROFITS/*,
"Pool profit share is invalid!" */);
require( config.ownerProfitShare >= MIN_OWNER_PROFITS &&
config.ownerProfitShare <= MAX_OWNER_PROFITS/*,
"Owner profit share is invalid!" */);
require( config.minerProfitShare >= MIN_MINER_PROFITS &&
config.minerProfitShare <= MAX_MINER_PROFITS/*,
"Miner profit share is invalid!" */);
// Check if time factor divisor is higher than 2 minutes.
// That's because int40 wouldn't be able to handle precisions
// of smaller time factor divisors.
require( config.timeFactorDivisor >= 2 minutes /*,
"Time factor divisor is lower than 2 minutes!"*/ );
// Check if winner profit share is good.
uint32 totalWinnerShare =
(_100PERCENT) - config.poolProfitShare
- config.ownerProfitShare
- config.minerProfitShare;
require( totalWinnerShare >= MIN_WINNER_PROFIT_SHARE/*,
"Winner profit share is too low!" */);
// Check if ending algorithm params are good.
require( config.randRatio_scorePart != 0 &&
config.randRatio_randPart != 0 &&
( config.randRatio_scorePart +
config.randRatio_randPart ) < 10000/*,
"Random Ratio params are invalid!" */);
require( config.endingAlgoType ==
uint8( EndingAlgoType.MinedWinnerSelection ) ||
config.endingAlgoType ==
uint8( EndingAlgoType.WinnerSelfValidation ) ||
config.endingAlgoType ==
uint8( EndingAlgoType.RolledRandomness )/*,
"Wrong Ending Algorithm Type!" */);
// Set the number of winners (winner count).
// If using Computed Sequence winner prize shares, set that
// value, and if it's zero, then we're using the Array-Mode
// prize share specification.
if( config.prizeSequence_winnerCount == 0 &&
config.winnerProfitShares.length != 0 )
config.prizeSequence_winnerCount =
uint16( config.winnerProfitShares.length );
// Setup our Lottery Storage - initialize, and set the
// Algorithm Config.
LotteryStorage _lotStorage = LotteryStorage( _storageAddress );
// Setup a Winner Score Config for the winner selection algo,
// to be used in the Lottery Storage.
LotteryStorage.WinnerAlgorithmConfig memory winnerConfig;
// Algorithm type.
winnerConfig.endingAlgoType = config.endingAlgoType;
// Individual player max score parts.
winnerConfig.maxPlayerScore_etherContributed =
config.maxPlayerScore_etherContributed;
winnerConfig.maxPlayerScore_tokenHoldingAmount =
config.maxPlayerScore_tokenHoldingAmount;
winnerConfig.maxPlayerScore_timeFactor =
config.maxPlayerScore_timeFactor;
winnerConfig.maxPlayerScore_refferalBonus =
config.maxPlayerScore_refferalBonus;
// Score-To-Random ratio parts.
winnerConfig.randRatio_scorePart = config.randRatio_scorePart;
winnerConfig.randRatio_randPart = config.randRatio_randPart;
// Set winner count (no.of winners).
winnerConfig.winnerCount = config.prizeSequence_winnerCount;
// Initialize the storage (bind it to our contract).
_lotStorage.initialize( winnerConfig );
// Set our immutable variable.
lotStorage = _lotStorage;
// Now, set our config to the passed config.
cfg = config;
// Might be un-needed (can be replaced by Constant on the MainNet):
WETHaddress = uniswapRouter.WETH();
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Fallback Receive Ether function.
* Used to receive ETH funds back from Uniswap, on lottery's end,
* when removing liquidity.
*/
receive() external payable
{
emit FallbackEtherReceiver( msg.sender, msg.value );
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<
* PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Initialization function.
* Here, the most important startup operations are made -
* such as minting initial token supply and transfering it to
* the Uniswap liquidity pair, in exchange for UNI-v2 tokens.
*
* This function is called by the pool, when transfering
* initial funds to this contract.
*
* What's payable?
* - Pool transfers initial funds to our contract.
* - We transfer that initial fund Ether to Uniswap liquidity pair
* when creating/providing it.
*/
function initialize()
external
payable
poolOnly
mutexLOCKED
onlyOnStage( STAGE.INITIAL )
{
// Check if pool transfered correct amount of funds.
require( address( this ).balance == cfg.initialFunds/*,
"Invalid amount of funds transfered!" */);
// Set start date.
startDate = uint32( block.timestamp );
// Set the initial transfer hash value.
transferHashValue = uint( keccak256(
abi.encodePacked( msg.sender, block.timestamp ) ) );
// Set initial finish probability, to be used when finishing
// stage starts.
finishProbablity = cfg.finish_initialProbability;
// ===== Active operations - mint & distribute! ===== //
// Mint full initial supply of tokens to our contract address!
_mint( address(this),
uint( cfg.initialTokenSupply ) * (10 ** decimals) );
// Now - prepare to create a new Uniswap Liquidity Pair,
// with whole our total token supply and initial funds ETH
// as the two liquidity reserves.
// Approve Uniswap Router to allow it to spend our tokens.
// Set maximum amount available.
_approve( address(this), address( uniswapRouter ), uint(-1) );
// Provide liquidity - the Router will automatically
// create a new Pair.
uniswapRouter.addLiquidityETH
{ value: address(this).balance }
(
address(this), // address token,
totalSupply(), // uint amountTokenDesired,
totalSupply(), // uint amountTokenMin,
address(this).balance, // uint amountETHMin,
address(this), // address to,
(block.timestamp + 1000) // uint deadline
);
// Get the Pair address - that will be the exchange address.
exchangeAddress = IUniswapFactory( uniswapRouter.factory() )
.getPair( WETHaddress, address(this) );
// We assume that the token reserves of the pair are good,
// and that we own the full amount of liquidity tokens.
// Find out which of the pair tokens is WETH - is it the
// first or second one. Use it later, when getting our share.
if( IUniswapPair( exchangeAddress ).token0() == WETHaddress )
uniswap_ethFirst = true;
else
uniswap_ethFirst = false;
// Move to ACTIVE lottery stage.
// Now, all token transfers will be allowed.
lotteryStage = uint8( STAGE.ACTIVE );
// Lottery is initialized. We're ready to emit event.
emit LotteryInitialized();
}
// Return this lottery's initial funds, as were specified in the config.
//
function getInitialFunds() external view
returns( uint )
{
return cfg.initialFunds;
}
// Return active (still not returned to pool) initial fund value.
// If no-longer-active, return 0 (default) - because funds were
// already returned back to the pool.
//
function getActiveInitialFunds() external view
returns( uint )
{
if( onStage( STAGE.ACTIVE ) )
return cfg.initialFunds;
return 0;
}
/**
* Get current Exchange's Token and ETH reserves.
* We're on Uniswap mode, so get reserves from Uniswap.
*/
function getReserves()
external view
returns( uint _ethReserve, uint _tokenReserve )
{
// Use data from Uniswap pair contract.
( uint112 res0, uint112 res1, ) =
IUniswapPair( exchangeAddress ).getReserves();
if( uniswap_ethFirst )
return ( res0, res1 );
else
return ( res1, res0 );
}
/**
* Get our share (ETH amount) of the Uniswap Pair ETH reserve,
* of our Lottery tokens ULT-WETH liquidity pair.
*/
function getCurrentEthFunds()
public view
returns( uint ethAmount )
{
IUniswapPair pair = IUniswapPair( exchangeAddress );
( uint112 res0, uint112 res1, ) = pair.getReserves();
uint resEth = uint( uniswap_ethFirst ? res0 : res1 );
// Compute our amount of the ETH reserve, based on our
// percentage of our liquidity token balance to total supply.
uint liqTokenPercentage =
( pair.balanceOf( address(this) ) * (_100PERCENT) ) /
( pair.totalSupply() );
// Compute and return the ETH reserve.
return ( resEth * liqTokenPercentage ) / (_100PERCENT);
}
/**
* Get current finish probability.
* If it's ACTIVE stage, return 0 automatically.
*/
function getFinishProbability()
external view
returns( uint32 )
{
if( onStage( STAGE.FINISHING ) )
return finishProbablity;
return 0;
}
/**
* Generate a referral ID for msg.sender, who must be a token holder.
* Referral ID is used to refer other wallets into playing our
* lottery.
* - Referrer gets bonus points for every wallet that bought
* lottery tokens and specified his referral ID.
* - Referrees (wallets who got referred by registering a valid
* referral ID, corresponding to some referrer), get some
* bonus points for specifying (registering) a referral ID.
*
* Referral ID is a uint256 number, which is generated by
* keccak256'ing the holder's address, holder's current
* token ballance, and current time.
*/
function generateReferralID()
external
onlyOnStage( STAGE.ACTIVE )
{
uint256 refID = lotStorage.generateReferralID( msg.sender );
// Emit approppriate events.
emit ReferralIDGenerated( msg.sender, refID );
}
/**
* Register a referral for a msg.sender (must be token holder),
* using a valid referral ID got from a referrer.
* This function is called by a referree, who obtained a
* valid referral ID from some referrer, who previously
* generated it using generateReferralID().
*
* You can only register a referral once!
* When you do so, you get bonus referral points!
*/
function registerReferral(
uint256 referralID )
external
onlyOnStage( STAGE.ACTIVE )
{
address referrer = lotStorage.registerReferral(
msg.sender,
cfg.playerScore_referralRegisteringBonus,
referralID );
// Emit approppriate events.
emit ReferralRegistered( msg.sender, referrer, referralID );
}
/**
* The most important function of this contract - Transfer Function.
*
* Here, all token burning, intermediate score tracking, and
* finish condition checking is performed, according to the
* properties specified in config.
*/
function _transfer( address sender,
address receiver,
uint256 amount )
internal
override
{
// Check if transfers are allowed in current state.
// On Non-Active stage, transfers are allowed only from/to
// our contract.
// As we don't have Standalone Mode on this lottery variation,
// that means that tokens to/from our contract are travelling
// only when we transfer them to Uniswap Pair, and when
// Uniswap transfers them back to us, on liquidity remove.
//
// On this state, we also don't perform any burns nor
// holding trackings - just transfer and return.
if( !onStage( STAGE.ACTIVE ) &&
!onStage( STAGE.FINISHING ) &&
( sender == address(this) || receiver == address(this) ||
specialTransferModeEnabled ) )
{
super._transfer( sender, receiver, amount );
return;
}
// Now, we know that we're NOT on special mode.
// Perform standard checks & brecks.
require( ( onStage( STAGE.ACTIVE ) ||
onStage( STAGE.FINISHING ) )/*,
"Token transfers are only allowed on ACTIVE stage!" */);
// Can't transfer zero tokens, or use address(0) as sender.
require( amount != 0 && sender != address(0)/*,
"Amount is zero, or transfering from zero address." */);
// Compute the Burn Amount - if buying tokens from an exchange,
// we use a lower burn rate - to incentivize buying!
// Otherwise (if selling or just transfering between wallets),
// we use a higher burn rate.
uint burnAmount;
// It's a buy - sender is an exchange.
if( sender == exchangeAddress )
burnAmount = ( amount * cfg.burn_buyerRate ) / (_100PERCENT);
else
burnAmount = ( amount * cfg.burn_defaultRate ) / (_100PERCENT);
// Now, compute the final amount to be gotten by the receiver.
uint finalAmount = amount - burnAmount;
// Check if receiver's balance won't exceed the max-allowed!
// Receiver must not be an exchange.
if( receiver != exchangeAddress )
{
require( !transferExceedsMaxBalance( receiver, finalAmount )/*,
"Receiver's balance would exceed maximum after transfer!"*/);
}
// Now, update holder data array accordingly.
bool holderCountChanged = updateHolderData_preTransfer(
sender,
receiver,
amount, // Amount Sent (Pre-Fees)
finalAmount // Amount Received (Post-Fees).
);
// All is ok - perform the burn and token transfers block.timestamp.
// Burn token amount from sender's balance.
super._burn( sender, burnAmount );
// Finally, transfer the final amount from sender to receiver.
super._transfer( sender, receiver, finalAmount );
// Compute new Pseudo-Random transfer hash, which must be
// computed for every transfer, and is used in the
// Finishing Stage as a pseudo-random unique value for
// every transfer, by which we determine whether lottery
// should end on this transfer.
//
// Compute it like this: keccak the last (current)
// transferHashValue, msg.sender, sender, receiver, amount.
transferHashValue = uint( keccak256( abi.encodePacked(
transferHashValue, msg.sender, sender, receiver, amount ) ) );
// Check if we should be starting a finishing stage block.timestamp.
checkFinishingStageConditions();
// If we're on finishing stage, check for ending conditions.
// If ending check is satisfied, the checkForEnding() function
// starts ending operations.
if( onStage( STAGE.FINISHING ) )
checkForEnding( holderCountChanged );
}
/**
* Callback function, which is called from Randomness Provider,
* after it obtains a random seed to be passed to us, after
* we have initiated The Ending Stage, on which random seed
* is used to generate random factors for Winner Selection
* algorithm.
*/
function finish_randomnessProviderCallback(
uint256 randomSeed,
uint256 /*callID*/ )
external
randomnessProviderOnly
{
// Set the random seed in the Storage Contract.
lotStorage.setRandomSeed( randomSeed );
// If algo-type is not Mined Winner Selection, then by block.timestamp
// we assume lottery as COMPL3T3D.
if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) )
{
lotteryStage = uint8( STAGE.COMPLETION );
completionDate = uint32( block.timestamp );
}
}
/**
* Function checks if we can initiate Alternative Seed generation.
*
* Alternative approach to Lottery Random Seed is used only when
* Randomness Provider doesn't work, and doesn't call the
* above callback.
*
* This alternative approach can be initiated by Miners, when
* these conditions are met:
* - Lottery is on Ending (Mining) stage.
* - Request to Randomness Provider was made at least X time ago,
* and our callback hasn't been called yet.
*
* If these conditions are met, we can initiate the Alternative
* Random Seed generation, which generates a seed based on our
* state.
*/
function alternativeSeedGenerationPossible()
internal view
returns( bool )
{
return ( onStage( STAGE.ENDING_MINING ) &&
( (block.timestamp - finish_timeRandomSeedRequested) >
cfg.REQUIRED_TIME_WAITING_FOR_RANDOM_SEED ) );
}
/**
* Return this lottery's config, using ABIEncoderV2.
*/
/*function getLotteryConfig()
external view
returns( LotteryConfig memory ourConfig )
{
return cfg;
}*/
/**
* Checks if Mining is currently available.
*/
function isMiningAvailable()
external view
returns( bool )
{
return onStage( STAGE.ENDING_MINING ) &&
( miningStep == 0 ||
( miningStep == 1 &&
( lotStorage.getRandomSeed() != 0 ||
alternativeSeedGenerationPossible() )
) );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Mining function, to be executed on Ending (Mining) stage.
*
* "Mining" approach is used in this lottery, to use external
* actors for executing the gas-expensive Ending Algorithm,
* and other ending operations, such as profit transfers.
*
* "Miners" can be any external actors who call this function.
* When Miner successfully completes a Mining Step, he gets
* a Mining Reward, which is a certain portion of lottery's profit
* share, dedicated to Miners.
*
* NOT-IMPLEMENTED APPROACH:
*
* All these operations are divided into "mining steps", which are
* smaller components, which fit into reasonable gas limits.
* All "steps" are designed to take up similar amount of gas.
*
* For example, if total lottery profits (total ETH got from
* pulling liquidity out of Uniswap, minus initial funds),
* is 100 ETH, Miner Profit Share is 10%, and there are 5 mining
* steps total, then for a singe step executed, miner will get:
*
* (100 * 0.1) / 5 = 2 ETH.
*
* ---------------------------------
*
* CURRENTLY IMPLEMENTED APPROACH:
*
* As the above-defined approach would consume very much gas for
* inter-step intermediate state storage, we have thought that
* for block.timestamp, it's better to have only 2 mining steps, the second of
* which performs the whole Winner Selection Algorithm.
*
* This is because performing the whole algorithm at once would save
* us up to 10x more gas in total, than executing it in steps.
*
* However, this solution is not scalable, because algorithm has
* to fit into block gas limit (10,000,000 gas), so we are limited
* to a certain safe maximum number of token holders, which is
* empirically determined during testing, and defined in the
* MAX_SAFE_NUMBER_OF_HOLDERS constant, which is checked against the
* config value "finishCriteria_minNumberOfHolders" in constructor.
*
* So, in this approach, there are only 2 mining steps:
*
* 1. Remove liquidity from Uniswap, transfer profit shares to
* the Pool and the Owner Address, and request Random Seed
* from the Randomness Provider.
* Reward: 25% of total Mining Rewards.
*
* 2. Perform the whole Winner Selection Algorithm inside the
* Lottery Storage contract.
* Reward: 75% of total Mining Rewards.
*
* * Function transfers Ether out of our contract:
* - Transfers the current miner's reward to msg.sender.
*/
function mine()
external
onlyOnStage( STAGE.ENDING_MINING )
{
uint currentStepReward;
// Perform different operations on different mining steps.
// Step 0: Remove liquidity from Uniswap, transfer profits to
// Pool and Owner addresses. Also, request a Random Seed
// from the Randomness Provider.
if( miningStep == 0 )
{
mine_requestRandomSeed();
mine_removeUniswapLiquidityAndTransferProfits();
// Compute total miner reward amount, then compute this
// step's reward later.
uint totalMinerRewards =
( ending_profitAmount * cfg.minerProfitShare ) /
( _100PERCENT );
// Step 0 reward is 10% for Algo type 1.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
currentStepReward = ( totalMinerRewards * (10 * PERCENT) ) /
( _100PERCENT );
}
// If other algo-types, second step is not normally needed,
// so here we take 80% of miner rewards.
// If Randomness Provider won't give us a seed after
// specific amount of time, we'll initiate a second step,
// with remaining 20% of miner rewords.
else
{
currentStepReward = ( totalMinerRewards * (80 * PERCENT) ) /
( _100PERCENT );
}
require( currentStepReward <= totalMinerRewards/*, "BUG 1694" */);
}
// Step 1:
// If we use MinedWinnerSelection algo-type, then execute the
// winner selection algorithm.
// Otherwise, check if Random Provider hasn't given us a
// random seed long enough, so that we have to generate a
// seed locally.
else
{
// Check if we can go into this step when using specific
// ending algorithm types.
if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) )
{
require( lotStorage.getRandomSeed() == 0 &&
alternativeSeedGenerationPossible()/*,
"Second Mining Step is not available for "
"current Algo-Type on these conditions!" */);
}
// Compute total miner reward amount, then compute this
// step's reward later.
uint totalMinerRewards =
( ending_profitAmount * cfg.minerProfitShare ) /
( _100PERCENT );
// Firstly, check if random seed is already obtained.
// If not, check if we should generate it locally.
if( lotStorage.getRandomSeed() == 0 )
{
if( alternativeSeedGenerationPossible() )
{
// Set random seed inside the Storage Contract,
// but using our contract's transferHashValue as the
// random seed.
// We believe that this hash has enough randomness
// to be considered a fairly good random seed,
// because it has beed chain-computed for every
// token transfer that has occured in ACTIVE stage.
//
lotStorage.setRandomSeed( transferHashValue );
// If using Non-Mined algorithm types, reward for this
// step is 20% of miner funds.
if( cfg.endingAlgoType !=
uint8(EndingAlgoType.MinedWinnerSelection) )
{
currentStepReward =
( totalMinerRewards * (20 * PERCENT) ) /
( _100PERCENT );
}
}
else
{
// If alternative seed generation is not yet possible
// (not enough time passed since the rand.provider
// request was made), then mining is not available
// currently.
require( false/*, "Mining not yet available!" */);
}
}
// Now, we know that Random Seed is obtained.
// If we use this algo-type, perform the actual
// winner selection algorithm.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
mine_executeEndingAlgorithmStep();
// Set the prize amount to SECOND STEP prize amount (90%).
currentStepReward = ( totalMinerRewards * (90 * PERCENT) ) /
( _100PERCENT );
}
// Now we've completed both Mining Steps, it means MINING stage
// is finally completed!
// Transition to COMPLETION stage, and set lottery completion
// time to NOW.
lotteryStage = uint8( STAGE.COMPLETION );
completionDate = uint32( block.timestamp );
require( currentStepReward <= totalMinerRewards/*, "BUG 2007" */);
}
// Now, transfer the reward to miner!
// Check for bugs too - if the computed amount doesn't exceed.
// Increment the mining step - move to next step (if there is one).
miningStep++;
// Check & Lock the Re-Entrancy Lock for transfers.
require( ! reEntrancyMutexLocked/*, "Re-Entrant call detected!" */);
reEntrancyMutexLocked = true;
// Finally, transfer the reward to message sender!
msg.sender.transfer( currentStepReward );
// UnLock ReEntrancy Lock.
reEntrancyMutexLocked = false;
}
/**
* Function computes winner prize amount for winner at rank #N.
* Prerequisites: Must be called only on STAGE.COMPLETION stage,
* because we use the final profits amount here, and that value
* (ending_profitAmount) is known only on COMPLETION stage.
*
* @param rankingPosition - ranking position of a winner.
* @return finalPrizeAmount - prize amount, in Wei, of this winner.
*/
function getWinnerPrizeAmount(
uint rankingPosition )
public view
returns( uint finalPrizeAmount )
{
// Calculate total winner prize fund profit percentage & amount.
uint winnerProfitPercentage =
(_100PERCENT) - cfg.poolProfitShare -
cfg.ownerProfitShare - cfg.minerProfitShare;
uint totalPrizeAmount =
( ending_profitAmount * winnerProfitPercentage ) /
( _100PERCENT );
// We compute the prize amounts differently for the algo-type
// RolledRandomness, because distribution of these prizes is
// non-deterministic - multiple holders could fall onto the
// same ranking position, due to randomness of rolled score.
//
if( cfg.endingAlgoType == uint8(EndingAlgoType.RolledRandomness) )
{
// Here, we'll use Prize Sequence Factor approach differently.
// We'll use the prizeSequenceFactor value not to compute
// a geometric progression, but to compute an arithmetic
// progression, where each ranking position will get a
// prize equal to
// "totalPrizeAmount - rankingPosition * singleWinnerShare"
//
// singleWinnerShare is computed as a value corresponding
// to single-winner's share of total prize amount.
//
// Using such an approach, winner at rank 0 would get a
// prize equal to whole totalPrizeAmount, but, as the
// scores are rolled using random factor, it's very unlikely
// to get a such high score, so most likely such prize
// won't ever be claimed, but it is a possibility.
//
// Most of the winners in this approach are likely to
// roll scores in the middle, so would get prizes equal to
// 1-10% of total prize funds.
uint singleWinnerShare = totalPrizeAmount /
cfg.prizeSequence_winnerCount;
return totalPrizeAmount - rankingPosition * singleWinnerShare;
}
// Now, we know that ending algorithm is normal (deterministic).
// So, compute the prizes in a standard way.
// If using Computed Sequence: loop for "rankingPosition"
// iterations, while computing the prize shares.
// If "rankingPosition" is larger than sequencedWinnerCount,
// then compute the prize from sequence-leftover amount.
if( cfg.prizeSequenceFactor != 0 )
{
require( rankingPosition < cfg.prizeSequence_winnerCount/*,
"Invalid ranking position!" */);
// Leftover: If prizeSequenceFactor is 25%, it's 75%.
uint leftoverPercentage =
(_100PERCENT) - cfg.prizeSequenceFactor;
// Loop until the needed iteration.
uint loopCount = (
rankingPosition >= cfg.prizeSequence_sequencedWinnerCount ?
cfg.prizeSequence_sequencedWinnerCount :
rankingPosition
);
for( uint i = 0; i < loopCount; i++ )
{
totalPrizeAmount =
( totalPrizeAmount * leftoverPercentage ) /
( _100PERCENT );
}
// Get end prize amount - sequenced, or leftover.
// Leftover-mode.
if( loopCount == cfg.prizeSequence_sequencedWinnerCount &&
cfg.prizeSequence_winnerCount >
cfg.prizeSequence_sequencedWinnerCount )
{
// Now, totalPrizeAmount equals all leftover-group winner
// prize funds.
// So, just divide it by number of leftover winners.
finalPrizeAmount =
( totalPrizeAmount ) /
( cfg.prizeSequence_winnerCount -
cfg.prizeSequence_sequencedWinnerCount );
}
// Sequenced-mode
else
{
finalPrizeAmount =
( totalPrizeAmount * cfg.prizeSequenceFactor ) /
( _100PERCENT );
}
}
// Else, if we're using Pre-Specified Array of winner profit
// shares, just get the share at the corresponding index.
else
{
require( rankingPosition < cfg.winnerProfitShares.length );
finalPrizeAmount =
( totalPrizeAmount *
cfg.winnerProfitShares[ rankingPosition ] ) /
( _100PERCENT );
}
}
/**
* After lottery has completed, this function returns if msg.sender
* is one of lottery winners, and the position in winner rankings.
*
* Function must be used to obtain the ranking position before
* calling claimWinnerPrize().
*
* @param addr - address whose status to check.
*/
function getWinnerStatus( address addr )
external view
returns( bool isWinner, uint32 rankingPosition,
uint prizeAmount )
{
if( !onStage( STAGE.COMPLETION ) || balanceOf( addr ) == 0 )
return (false , 0, 0);
( isWinner, rankingPosition ) =
lotStorage.getWinnerStatus( addr );
if( isWinner )
{
prizeAmount = getWinnerPrizeAmount( rankingPosition );
if( prizeAmount > address(this).balance )
prizeAmount = address(this).balance;
}
}
/**
* Compute the intermediate Active Stage player score.
* This score is Player Score, not randomized.
* @param addr - address to check.
*/
function getPlayerIntermediateScore( address addr )
external view
returns( uint )
{
return lotStorage.getPlayerActiveStageScore( addr );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Claim the winner prize of msg.sender, if he is one of the winners.
*
* This function must be provided a ranking position of msg.sender,
* which must be obtained using the function above.
*
* The Lottery Storage then just checks if holder address in the
* winner array element at position rankingPosition is the same
* as msg.sender's.
*
* If so, then claim request is valid, and we can give the appropriate
* prize to that winner.
* Prize can be determined by a computed factor-based sequence, or
* from the pre-specified winner array.
*
* * This function transfers Ether out of our contract:
* - Sends the corresponding winner prize to the msg.sender.
*
* @param rankingPosition - the position of Winner Array, that
* msg.sender says he is in (obtained using getWinnerStatus).
*/
function claimWinnerPrize(
uint32 rankingPosition )
external
onlyOnStage( STAGE.COMPLETION )
mutexLOCKED
{
// Check if msg.sender hasn't already claimed his prize.
require( ! prizeClaimersAddresses[ msg.sender ]/*,
"msg.sender has already claimed his prize!" */);
// msg.sender must have at least some of UniLottery Tokens.
require( balanceOf( msg.sender ) != 0/*,
"msg.sender's token balance can't be zero!" */);
// Check if there are any prize funds left yet.
require( address(this).balance != 0/*,
"All prize funds have already been claimed!" */);
// If using Mined Selection Algo, check if msg.sender is
// really on that ranking position - algo was already executed.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
require( lotStorage.minedSelection_isAddressOnWinnerPosition(
msg.sender, rankingPosition )/*,
"msg.sender is not on specified winner position!" */);
}
// For other algorithms, get ranking position by executing
// a specific algorithm of that algo-type.
else
{
bool isWinner;
( isWinner, rankingPosition ) =
lotStorage.getWinnerStatus( msg.sender );
require( isWinner/*, "msg.sender is not a winner!" */);
}
// Compute the prize amount, using our internal function.
uint finalPrizeAmount = getWinnerPrizeAmount( rankingPosition );
// If prize is small and computation precision errors occured,
// leading it to be larger than our balance, fix it.
if( finalPrizeAmount > address(this).balance )
finalPrizeAmount = address(this).balance;
// Transfer the Winning Prize to msg.sender!
msg.sender.transfer( finalPrizeAmount );
// Mark msg.sender as already claimed his prize.
prizeClaimersAddresses[ msg.sender ] = true;
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Transfer the leftover Winner Prize Funds of this contract to the
* Main UniLottery Pool, if prize claim deadline has been exceeded.
*
* Function can only be called from the Main Pool, and if some
* winners haven't managed to claim their prizes on time, their
* prizes will go back to UniLottery Pool.
*
* * Function transfers Ether out of our contract:
* - Transfer the leftover funds to the Pool (msg.sender).
*/
function getUnclaimedPrizes()
external
poolOnly
onlyOnStage( STAGE.COMPLETION )
mutexLOCKED
{
// Check if prize claim deadline has passed.
require( completionDate != 0 &&
( block.timestamp - completionDate ) > cfg.prizeClaimTime/*,
"Prize claim deadline not reached yet!" */);
// Just transfer it all to the Pool.
poolAddress.transfer( address(this).balance );
}
}
contract UniLotteryRandomnessProvider is usingProvable
{
// =============== E-Vent Section =============== //
// New Lottery Random Seed Request made.
event LotteryRandomSeedRequested(
uint id,
address lotteryAddress,
uint gasLimit,
uint totalEtherGiven
);
// Random seed obtained, and callback successfully completed.
event LotteryRandomSeedCallbackCompleted(
uint id
);
// UniLottery Pool scheduled a call.
event PoolCallbackScheduled(
uint id,
address poolAddress,
uint timeout,
uint gasLimit,
uint totalEtherGiven
);
// Pool scheduled callback successfully completed.
event PoolCallbackCompleted(
uint id
);
// Ether transfered into fallback.
event EtherTransfered(
address sender,
uint value
);
// =============== Structs & Enums =============== //
// Enum - type of the request.
enum RequestType {
LOTTERY_RANDOM_SEED,
POOL_SCHEDULED_CALLBACK
}
// Call Request Structure.
struct CallRequestData
{
// -------- Slot -------- //
// The ID of the request.
uint256 requestID;
// -------- Slot -------- //
// Requester address. Can be pool, or an ongoing lottery.
address requesterAddress;
// The Type of request (Random Seed or Pool Scheduled Callback).
RequestType reqType;
}
// Lottery request config - specifies gas limits that must
// be used for that specific lottery's callback.
// Must be set separately from CallRequest, because gas required
// is specified and funds are transfered by The Pool, before starting
// a lottery, and when that lottery ends, it just calls us, expecting
// it's gas cost funds to be already sent to us.
struct LotteryGasConfig
{
// -------- Slot -------- //
// The total ether funds that the pool has transfered to
// our contract for execution of this lottery's callback.
uint160 etherFundsTransferedForGas;
// The gas limit provided for that callback.
uint64 gasLimit;
}
// =============== State Variables =============== //
// -------- Slot -------- //
// Mapping of all currently pending or on-process requests
// from their Query IDs.
mapping( uint256 => CallRequestData ) pendingRequests;
// -------- Slot -------- //
// A mapping of Pool-specified-before-their-start lottery addresses,
// to their corresponding Gas Configs, which will be used for
// their end callbacks.
mapping( address => LotteryGasConfig ) lotteryGasConfigs;
// -------- Slot -------- //
// The Pool's address. We receive funds from it, and use it
// to check whether the requests are coming from ongoing lotteries.
address payable poolAddress;
// ============ Private/Internal Functions ============ //
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress/*,
"Function can only be called by the Main Pool!" */);
_;
}
// Ongoing Lottery Only modifier.
// Data must be fetch'd from the Pool.
modifier ongoingLotteryOnly
{
require( IMainUniLotteryPool( poolAddress )
.isLotteryOngoing( msg.sender )/*,
"Function can be called only by ongoing lotteries!" */);
_;
}
// ================= Public Functions ================= //
/**
* Constructor.
* Here, we specify the Provable proof type, to use for
* Random Datasource queries.
*/
constructor()
{
// Set the Provable proof type for Random Queries - Ledger.
provable_setProof( proofType_Ledger );
}
/**
* Initialization function.
* Called by the Pool, on Pool's constructor, to initialize this
* randomness provider.
*/
function initialize() external
{
// Check if we were'nt initialized yet (pool address not set yet).
require( poolAddress == address( 0 )/*,
"Contract is already initialized!" */);
poolAddress = msg.sender;
}
/**
* The Payable Fallback function.
* This function is used by the Pool, to transfer the required
* funds to us, to be able to pay for Provable gas & fees.
*/
receive () external payable
{
emit EtherTransfered( msg.sender, msg.value );
}
/**
* Get the total Ether price for a request to specific
* datasource with specific gas limit.
* It just calls the Provable's internal getPrice function.
*/
// Random datasource.
function getPriceForRandomnessCallback( uint gasLimit )
external
returns( uint totalEtherPrice )
{
return provable_getPrice( "random", gasLimit );
}
// URL datasource (for callback scheduling).
function getPriceForScheduledCallback( uint gasLimit )
external
returns( uint totalEtherPrice )
{
return provable_getPrice( "URL", gasLimit );
}
/**
* Set the gas limit which should be used by the lottery deployed
* on address "lotteryAddr", when that lottery finishes and
* requests us to call it's ending callback with random seed
* provided.
* Also, specify the amount of Ether that the pool has transfered
* to us for the execution of this lottery's callback.
*/
function setLotteryCallbackGas(
address lotteryAddr,
uint64 callbackGasLimit,
uint160 totalEtherTransferedForThisOne )
external
poolOnly
{
LotteryGasConfig memory gasConfig;
gasConfig.gasLimit = callbackGasLimit;
gasConfig.etherFundsTransferedForGas = totalEtherTransferedForThisOne;
// Set the mapping entry for this lottery address.
lotteryGasConfigs[ lotteryAddr ] = gasConfig;
}
/**
* The Provable Callback, which will get called from Off-Chain
* Provable service, when it completes execution of our request,
* made before previously with provable_query variant.
*
* Here, we can perform 2 different tasks, based on request type
* (we get the CallRequestData from the ID passed by Provable).
*
* The different tasks are:
* 1. Pass Random Seed to Lottery Ending Callback.
* 2. Call a Pool's Scheduled Callback.
*/
function __callback(
bytes32 _queryId,
string memory _result,
bytes memory _proof )
public
override
{
// Check that the sender is Provable Services.
require( msg.sender == provable_cbAddress() );
// Get the Request Data storage pointer, and check if it's Set.
CallRequestData storage reqData =
pendingRequests[ uint256( _queryId ) ];
require( reqData.requestID != 0/*,
"Invalid Request Data structure (Response is Invalid)!" */);
// Check the Request Type - if it's a lottery asking for a
// random seed, or a Pool asking to call it's scheduled callback.
if( reqData.reqType == RequestType.LOTTERY_RANDOM_SEED )
{
// It's a lottery asking for a random seed.
// Check if Proof is valid, using the Base Contract's built-in
// checking functionality.
require( provable_randomDS_proofVerify__returnCode(
_queryId, _result, _proof ) == 0/*,
"Random Datasource Proof Verification has FAILED!" */);
// Get the Random Number by keccak'ing the random bytes passed.
uint256 randomNumber = uint256(
keccak256( abi.encodePacked( _result ) ) );
// Pass this Random Number as a Seed to the requesting lottery!
ILottery( reqData.requesterAddress )
.finish_randomnessProviderCallback(
randomNumber, uint( _queryId ) );
// Emit appropriate events.
emit LotteryRandomSeedCallbackCompleted( uint( _queryId ) );
}
// It's a pool, asking to call it's callback, that it scheduled
// to get called in some time before.
else if( reqData.reqType == RequestType.POOL_SCHEDULED_CALLBACK )
{
IMainUniLotteryPool( poolAddress )
.scheduledCallback( uint( _queryId ) );
// Emit appropriate events.
emit PoolCallbackCompleted( uint( _queryId ) );
}
// We're finished! Remove the request data from the pending
// requests mapping.
delete pendingRequests[ uint256( _queryId ) ];
}
/**
* This is the function through which the Lottery requests a
* Random Seed for it's ending callback.
* The gas funds needed for that callback's execution were already
* transfered to us from The Pool, at the moment the Pool created
* and deployed that lottery.
* The gas specifications are set in the LotteryGasConfig of that
* specific lottery.
* TODO: Also set the custom gas price.
*/
function requestRandomSeedForLotteryFinish()
external
ongoingLotteryOnly
returns( uint256 requestId )
{
// Check if gas limit (amount of gas) for this lottery was set.
require( lotteryGasConfigs[ msg.sender ].gasLimit != 0/*,
"Gas limit for this lottery was not set!" */);
// Check if the currently estimated price for this request
// is not higher than the one that the pool transfered funds for.
uint transactionPrice = provable_getPrice( "random",
lotteryGasConfigs[ msg.sender ].gasLimit );
if( transactionPrice >
lotteryGasConfigs[ msg.sender ].etherFundsTransferedForGas )
{
// If our balance is enough to execute the transaction, then
// ask pool if it agrees that we execute this transaction
// with higher price than pool has given funds to us for.
if( address(this).balance >= transactionPrice )
{
bool response = IMainUniLotteryPool( poolAddress )
.onLotteryCallbackPriceExceedingGivenFunds(
msg.sender,
transactionPrice,
lotteryGasConfigs[msg.sender].etherFundsTransferedForGas
);
require( response/*, "Pool has denied the request!" */);
}
// If price absolutely exceeds our contract's balance:
else {
require( false/*, "Request price exceeds contract's balance!" */);
}
}
// Set the Provable Query parameters.
// Execute the query as soon as possible.
uint256 QUERY_EXECUTION_DELAY = 0;
// Set the gas amount to the previously specified gas limit.
uint256 GAS_FOR_CALLBACK = lotteryGasConfigs[ msg.sender ].gasLimit;
// Request 8 random bytes (that's enough randomness with keccak).
uint256 NUM_RANDOM_BYTES_REQUESTED = 8;
// Execute the Provable Query!
uint256 queryId = uint256( provable_newRandomDSQuery(
QUERY_EXECUTION_DELAY,
NUM_RANDOM_BYTES_REQUESTED,
GAS_FOR_CALLBACK
) );
// Populate & Add the pending requests mapping entry.
CallRequestData memory requestData;
requestData.requestID = queryId;
requestData.reqType = RequestType.LOTTERY_RANDOM_SEED;
requestData.requesterAddress = msg.sender;
pendingRequests[ queryId ] = requestData;
// Emit an event - lottery just requested a random seed.
emit LotteryRandomSeedRequested(
queryId, msg.sender,
lotteryGasConfigs[ msg.sender ].gasLimit,
lotteryGasConfigs[ msg.sender ].etherFundsTransferedForGas
);
// Remove the just-used Lottery Gas Configs mapping entry.
delete lotteryGasConfigs[ msg.sender ];
// Return the ID of the query.
return queryId;
}
/**
* Schedule a call for the pool, using specified amount of gas,
* and executing after specified amount of time.
* Accomplished using an empty URL query, and setting execution
* delay to the specified timeout.
* On execution, __callback() calls the Pool's scheduledCallback()
* function.
*
* @param timeout - how much time to delay the execution of callback.
* @param gasLimit - gas limit to use for the callback's execution.
* @param etherFundsTransferedForGas - how much Ether has the Pool
* transfered to our contract before calling this function,
* to be used only for this operation.
*/
function schedulePoolCallback(
uint timeout,
uint gasLimit,
uint etherFundsTransferedForGas )
external
poolOnly
returns( uint256 requestId )
{
// Price exceeding transfered funds doesn't need to be checked
// here, because pool transfers required funds just before
// calling this function, so price can't change between transfer
// and this function's call.
// Execute the query on specified timeout, with a
// specified Gas Limit.
uint queryId = uint(
provable_query( timeout, "URL", "", gasLimit )
);
// Populate & Add the pending requests mapping entry.
CallRequestData memory requestData;
requestData.requestID = queryId;
requestData.reqType = RequestType.POOL_SCHEDULED_CALLBACK;
requestData.requesterAddress = msg.sender;
pendingRequests[ queryId ] = requestData;
// Emit an event - lottery just requested a random seed.
emit PoolCallbackScheduled( queryId, poolAddress, timeout, gasLimit,
etherFundsTransferedForGas );
// Return a query ID.
return queryId;
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Sends the specified amount of Ether back to the Pool.
* WARNING: Future Provable requests might fail due to insufficient
* funds! No checks are made to ensure sufficiency.
*/
function sendFundsToPool( uint etherAmount )
external
poolOnly
{
poolAddress.transfer( etherAmount );
}
/**
* Set the gas price to be used for future Provable queries.
* Used to change the default gas in times of congested networks.
*/
function setGasPrice( uint _gasPrice )
external
poolOnly
{
// Limit gas price to 600 GWei.
require( _gasPrice <= 600 * (10 ** 9)/*,
"Specified gas price is higher than 600 GWei !" */);
provable_setCustomGasPrice( _gasPrice );
}
}
| Set the Lottery address (msg.sender can't be zero), and thus, set our contract to initialized! Set the Winner-Algo-Config. NOT-NEEDED: Set initial min-max scores: min is INT_MAX. | function initialize(
WinnerAlgorithmConfig memory _wcfg )
public
{
require( address( lottery ) == address( 0 )/*,
"Storage is already initialized!" */);
lottery = msg.sender;
algConfig = _wcfg;
minMaxScores.holderScore_timeFactors_min = int80( 2 ** 78 );
minMaxScores.holderScore_tokenBalance_min = int80( 2 ** 78 );
| 7,577,605 |
./full_match/80001/0xafB8D3F0d92461d3c860E4F7FA1B28a5BF8a1cF8/sources/MintingNFT.sol | This is a function of ERC721Enumerable interface / | function supportsInterface(bytes4 interfaceId) public view
override(ERC721Enumerable) returns (bool)
{
return super.supportsInterface(interfaceId);
}
| 874,113 |
// contracts/MyContract.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.7.0;
//import "@openzeppelin/contracts/GSN/GSNRecipientERC20Fee.sol";
//import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
//import "@openzeppelin/contracts/access/Roles.sol";
contract HubContract is Initializable {
address private mainContract;
address private admin;
bytes32 private encrypted; //If blank, all will be encryoted
bytes32 private plaintext; //If blank, all will be encrypted
mapping(address => bool) private _admins;
//mapping Admin[] public _admins;
mapping(address => bool) private _providers;
//Providers are marked from their IAM to service contract.
//Provider's KPI are managed here.
event ProviderAdded(address indexed account);
event ProviderRemoved(address indexed account);
event OfferRolled(address indexed account, address offer);
event BidAwarded(address indexed account, address microbid, address account2);
event BidSubmitted(address indexed account, address microbid);
function initialize(address _master) public initializer {
//admin = _admin;//address _admin
mainContract = _master;
admin = msg.sender;
_admins[msg.sender] = true;
_addProvider(msg.sender);
}
/*
function io(uint256 typex,
bytes memory bidrequest, //can contain bid or request
address microbid,
address provider,
bytes32 _salt
) public {
if (typex == 1) {
_offer(_salt, microbid, bidrequest);
}
if (typex == 2) {
_award(microbid, provider);
}
if (typex == 3) {
_bid(microbid, provider, bidrequest);
}
}
*/
fallback() external payable { }
function offer(bytes32 _salt, address microbid, bytes memory bidrequest ) public {
_offer(_salt, microbid, bidrequest);
}
function award(address microbid, address provider) public {
_award(microbid, provider);
}
function bid(address microbid, address provider, bytes memory bidrequest) public {
_bid(microbid, provider, bidrequest);
}
//Admin Public Function
function isAdmin(address adminac) public view returns (bool) {
return _admins[adminac];
}
function renounceAdmin(address account) public {
require(_admins[msg.sender], "You must be admin");
_removeAdmin(account);
}
function addAdmin(address account) public {
require(_admins[msg.sender], "You must be admin");
_addAdmin(account);
}
// Provider Public Functions
function isProvider(address account) public view returns (bool) {
return _providers[account];
}
function renounceProvider(address spoke) public {
require(_admins[msg.sender], "You must be admin");
_removeProvider(spoke);
}
function addProvider(address spoke) public {
require(_admins[msg.sender], "You must be admin");
_addProvider(spoke);
}
//Admin Internal Function
function _addAdmin(address account) internal {
require(_admins[msg.sender], "You must be admin");
require(account != address(0));
//Admin memory admin = Admin(account, true);
_admins[admin] = true;
}
function _removeAdmin (address account) internal {
require(_admins[msg.sender], "You must be admin");
require(account != address(0));
_admins[account] = false;
delete _admins[account];
}
/*
modifier onlyProvider() {
require(isProvider(msg.sender));
_;
}*/
//Provided Internal Function
function _addProvider(address account) internal {
require(_admins[msg.sender], "You must be admin");
require(account != address(0));
//Provider memory provider = Provider(account, true);
_providers[account] = true;
emit ProviderAdded(account);
}
function _removeProvider (address account) internal {
require(_admins[msg.sender], "You must be admin");
require(account != address(0));
_providers[account] = false;
delete _providers[account];
emit ProviderRemoved(account);
}
//Create a Micro-Offer to serve the end customer
function _offer(
bytes32 _salt,
address microbid,
bytes memory request
) internal {
require(_admins[msg.sender], "You must be admin");
new OfferContract{salt: _salt}(mainContract , microbid, request);
emit OfferRolled(mainContract, microbid);
}
//Reward bid
function _award(address microbid, address provider) internal {
require(_admins[msg.sender], "You must be admin");
// require(microbid.call(bytes4(keccak256("setaward(address)")), provider));
OfferContract oc = OfferContract(microbid);
// call method from other contract
oc.setaward(provider);
emit BidAwarded(mainContract, microbid, provider);
}
//Provider Side Function of Bidding
function _bid(address microbid, address provider, bytes memory bid) internal {
require(_providers[msg.sender], "You must be a provider");
require(provider == msg.sender, "You must submit your own bids");
//require(microbid.call(bytes4(keccak256("setbid(byte32)")), bid));
OfferContract oc = OfferContract(microbid);
// call method from other contract
oc.setbid(provider, bid);
emit BidSubmitted(mainContract, microbid);
}
}
//Offer Contract for providers to send their bids -> Needs Access info of Admins & Providers from the HubContract
contract OfferContract {
address payable owner;
//address private recipient;
address private mainId;
address private selfId;
//address private pvtIdentity;
bytes private request;//Plaintext or Encrypted with Contract's key, so that only participating parties can read it
//bytes private response;//Encrypted with Hub's Public key, so that only hub can read it
address private winner;//Offchain Offerid
//bytes private offernonce;//Offchain Offer Nonce //Comprissing of user id hash
mapping(address => bytes) public responses;
mapping(address => bool) public acks;
constructor(
address _mainId, //Address of Main Contract
address _selfId, //Address of Sub Contract(This)
bytes memory _request
)public {
owner = msg.sender;
mainId = _mainId;
selfId = _selfId;
request = _request;
//providers = _providers;
//admins = _admins;
//require(success, "Transfer failed.");
}
function ack(address account) public { //Acknowledge
require(mainId == msg.sender, "Call from Contract Only");
acks[account] = true;
}
function end() public {
require(mainId == msg.sender, "Call from Contract Only");
selfdestruct(owner);
}
function setaward(address account) public {
require(mainId == msg.sender, "Call from Contract Only");
winner = account;
}
function setbid(address account, bytes memory bid) public {
require(mainId == msg.sender, "Call from Contract Only");
responses[account] = bid;
}
}
| Provider Side Function of Biddingrequire(microbid.call(bytes4(keccak256("setbid(byte32)")), bid)); call method from other contract | function _bid(address microbid, address provider, bytes memory bid) internal {
require(_providers[msg.sender], "You must be a provider");
require(provider == msg.sender, "You must submit your own bids");
OfferContract oc = OfferContract(microbid);
oc.setbid(provider, bid);
emit BidSubmitted(mainContract, microbid);
}
| 7,241,391 |
./partial_match/1/0xC94081183A25B5fC729Cdf993F7fe83970F9D776/sources/FraxUnifiedFarm_ERC20_KyberSwapElasticV2.sol | Sets multiple variables at once _misc_vars The variables to set: [0]: uint256 _lock_max_multiplier, [1] uint256 _vefxs_max_multiplier, [2] uint256 _vefxs_per_frax_for_max_boost, [3] uint256 _vefxs_boost_scale_factor, [4] uint256 _lock_time_for_max_multiplier, [5] uint256 _lock_time_min [6] uint256 _max_stake_limit (must be at greater or equal to old value) [0]: uint256 _lock_max_multiplier, [1] uint256 _vefxs_max_multiplier, [2] uint256 _vefxs_per_frax_for_max_boost, [3] uint256 _vefxs_boost_scale_factor, [4] uint256 _lock_time_for_max_multiplier, [5] uint256 _lock_time_min | function setMiscVariables(
uint256[6] memory _misc_vars
) external onlyByOwnGov {
require(_misc_vars[0] >= MULTIPLIER_PRECISION, "Must be >= MUL PREC");
require((_misc_vars[1] >= 0) && (_misc_vars[2] >= 0) && (_misc_vars[3] >= 0) && (_misc_vars[5] >= 0), "Must be >= 0");
require((_misc_vars[4] >= 1), "Must be >= 1");
lock_max_multiplier = _misc_vars[0];
vefxs_max_multiplier = _misc_vars[1];
vefxs_per_frax_for_max_boost = _misc_vars[2];
vefxs_boost_scale_factor = _misc_vars[3];
lock_time_for_max_multiplier = _misc_vars[4];
lock_time_min = _misc_vars[5];
}
| 3,608,784 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.