file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Interfaces
import { IsaLPPricer } from "../IsaLPPricer.sol";
import {
PrizePoolInterface
} from "../../shared/interfaces/pooltogether/PrizePoolInterface.sol";
import {
IControlledToken
} from "../../shared/interfaces/pooltogether/IControlledToken.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract PoolTogetherPricer is IsaLPPricer {
// TODO: not currently being used
/**
* @notice It returns the exchange rate of the aToken to the underlying asset.
* @dev The exchange ratio for Aave tokens is always 1:1, however the token balance is compounded silently
* using an index at the time of their last deposit. See {AavePricer.getBalanceOfUnderlying}
* @param saLPToken address of the single asset liquidity provider token.
* @return Exchange rate for 1 saLP token in the underlying asset.
*/
function getRateFor(address saLPToken)
public
view
override
returns (uint256)
{
return 0;
}
// TODO: not currently being used
/**
* @notice It calculates the value of the protocol token amount into the underlying asset.
* @dev The value of an Aave token is always the same as the underlying asset amount. See {AavePricer.getRateFor}
* @param saLPToken address of the single asset liquidity provider token
* @param amount Amount of the token to convert into the underlying asset.
* @return Value of the saLP token in the underlying asset.
*/
function getValueOf(address saLPToken, uint256 amount)
external
view
override
returns (uint256)
{
return 0;
}
/**
* @notice It calculates the balance of the underlying asset for {account}.
* @param saLPToken Address of the single asset liquidity provider token.
* @param account Address of the account to get the balance of.
* @return Balance of the underlying asset.
*/
function getBalanceOfUnderlying(address saLPToken, address account)
external
override
returns (uint256)
{
return _getPrizePool(saLPToken).balanceOfCredit(account, saLPToken);
}
/**
* @notice Gets the underlying asset address for the Compound token.
* @dev cETH is the only Compound token that does not support the {underlying} function.
* @param saLPToken address of the Compound token.
* @return address of the underlying saLPToken asset.
*/
function getUnderlying(address saLPToken)
public
view
override
returns (address)
{
return _getPrizePool(saLPToken).token();
}
function _getPrizePool(address saLPToken)
private
view
returns (PrizePoolInterface)
{
return IControlledToken(saLPToken).controller();
}
}
|
TODO: not currently being used It calculates the value of the protocol token amount into the underlying asset. The value of an Aave token is always the same as the underlying asset amount. See {AavePricer.getRateFor} saLPToken address of the single asset liquidity provider token amount Amount of the token to convert into the underlying asset. return Value of the saLP token in the underlying asset./
|
function getValueOf(address saLPToken, uint256 amount)
external
view
override
returns (uint256)
{
return 0;
}
| 13,106,817 |
./full_match/1/0x60232134f0A9177e5248BC44fC95c2c5EFEf8E1A/sources/src/experimental/delegate-bid.sol
|
Casts a vote on an external proposal. Tip is awarded to the caller dao The address of the DAO propId The id of the proposal to execute This function ensures that the proposal is within the execution window and that some bid has been offered to cast the vote/ refund gas and calculate an incentive for the executer, distribute the rest to the contract beneficiary
|
function castExternalVote(address dao, uint256 propId) external nonReentrant {
uint256 startGas = gasleft();
require(dao != address(0), "DAO address is not valid");
require(_isActive(dao, propId), "Voting is closed for this proposal");
Bid storage bid = bids[address(dao)][propId];
require(bid.amount > 0 && bid.bidder != address(0), "Bid not offered for this proposal");
require(block.number >= bid.endBlock - castWindow, "Vote can only be cast during the proposal execution window");
require(!bid.executed, "Vote already cast");
require(bid.txBlock < block.number, "Vote cannot be cast in the same block the bid was made");
bid.executed = true;
INounsDAOLogic eDAO = INounsDAOLogic(dao);
eDAO.castVote(propId, bid.support);
emit VoteCast(dao, propId, bid.support, bid.amount, bid.bidder);
unchecked {
uint256 balance = address(this).balance;
if (balance == 0) {
return;
}
uint256 tip = min(baseTip, bid.amount);
uint256 basefee = min(block.basefee, MAX_REFUND_BASE_FEE);
uint256 gasPrice = min(tx.gasprice, basefee + MAX_REFUND_PRIORITY_FEE);
uint256 gasUsed = min(startGas - gasleft() + REFUND_BASE_GAS, MAX_REFUND_GAS_USED);
uint256 refundAmount = min(gasPrice * gasUsed, balance);
uint256 refundIncludingTip = min(refundAmount + tip, bid.amount);
uint256 fee = bid.amount - refundIncludingTip;
emit VoteCastRefundAndDistribute(tx.origin, refundAmount, tip, refundSent, fee, feeSent);
}
}
| 17,035,288 |
./partial_match/1/0x457cD63bee88ac01f3cD4a67D5DCc921D8C0D573/sources/contracts/abstract/JBPayoutRedemptionPaymentTerminal3_1_1.sol
|
Get the fee discount from the fee gauge for the specified project. _projectId The ID of the project to get a fee discount for. _feeType The type of fee the discount is being applied to. return feeDiscount The fee discount, which should be interpreted as a percentage out MAX_FEE_DISCOUNT. Can't take a fee if the protocol project doesn't have a terminal that accepts the token. Get the fee discount. If the guage reverts, keep the discount at 0.
|
) internal view returns (uint256) {
if (
directory.primaryTerminalOf(_FEE_BENEFICIARY_PROJECT_ID, token) ==
IJBPaymentTerminal(address(0))
) return JBConstants.MAX_FEE_DISCOUNT;
if (feeGauge != address(0))
try IJBFeeGauge3_1(feeGauge).currentDiscountFor(_projectId, _feeType) returns (
uint256 discount
function _feeAmount(
uint256 _amount,
uint256 _fee,
uint256 _feeDiscount
}
function _currentFeeDiscount(
uint256 _projectId,
JBFeeType _feeType
) {
if (discount <= JBConstants.MAX_FEE_DISCOUNT) return discount;
return 0;
}
return 0;
} catch {
}
| 4,264,599 |
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import '@openzeppelin/contracts/interfaces/IERC721.sol';
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./AnonymiceLibrary.sol";
import "./OriginalAnonymiceInterface.sol";
//
// ╔═╗┌┐┌┌─┐┌┐┌┬ ┬┌┬┐┬┌─┐┌─┐ ╔═╗┬ ┬┌─┐┌─┐┌─┐┌─┐ ╔═╗┬ ┬ ┬┌┐
// ╠═╣││││ ││││└┬┘│││││ ├┤ ║ ├─┤├┤ ├┤ └─┐├┤ ║ │ │ │├┴┐
// ╩ ╩┘└┘└─┘┘└┘ ┴ ┴ ┴┴└─┘└─┘ ╚═╝┴ ┴└─┘└─┘└─┘└─┘ ╚═╝┴─┘└─┘└─┘
//
// Own Burned Anonymice and create an exclusive Cheese Club!
// Minting dApp on anonymicecheese.club
//
// We know other projects tried to do this before and failed. So we fixed all their issues and
// we're ready to let you own those mice.
// Cheese club will be the heart of those 6,450 burned mice.
//
contract AnonymiceCheeseClub is ERC721Enumerable, Ownable {
using AnonymiceLibrary for uint8;
//Mappings
uint16[6450] internal tokenToOriginalMiceId;
uint256 internal nextOriginalMiceToLoad = 0;
OriginalAnonymiceInterface.Trait[] internal burnedTraitType;
//uint256s
uint256 MAX_SUPPLY = 6450;
uint256 FREE_MINTS = 500;
uint256 PRICE = .02 ether;
//addresses
address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731;
//string arrays
string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
];
//events
event TokenMinted(uint256 supply);
constructor() ERC721("Anonymice Cheese Club", "MICE-CHEESE-CLUB") {
}
// ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗
// ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝
// ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗
// ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║
// ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝
// ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝
/**
* @dev Loads the IDs of burned mices
* @param _howMany The number of mices to load. Starts from the last loaded
*/
function _loadOriginalMices(uint256 _howMany) internal {
require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded");
ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract);
uint start = nextOriginalMiceToLoad;
for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) {
uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i);
tokenToOriginalMiceId[i] = uint16(id);
}
nextOriginalMiceToLoad = start + _howMany;
}
/**
* @dev Mint internal, this is to avoid code duplication.
*/
function mintInternal(uint256 num_tokens, address to) internal {
uint256 _totalSupply = totalSupply();
require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply');
require(!AnonymiceLibrary.isContract(msg.sender));
if ((num_tokens + _totalSupply) > MAX_SUPPLY) {
num_tokens = MAX_SUPPLY - _totalSupply;
}
_loadOriginalMices(num_tokens);
for (uint i=0; i < num_tokens; i++) {
_safeMint(to, _totalSupply);
emit TokenMinted(_totalSupply);
_totalSupply = _totalSupply + 1;
}
}
/**
* @dev Mints new tokens.
*/
function mint(address _to, uint _count) public payable {
uint _totalSupply = totalSupply();
if (_totalSupply > FREE_MINTS) {
require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)');
}
return mintInternal(_count, _to);
}
/**
* @dev Kills the mice again, this time forever.
* @param _tokenId The token to burn.
*/
function killForever(uint256 _tokenId) public {
require(ownerOf(_tokenId) == msg.sender);
//Burn token
_transfer(
msg.sender,
0x000000000000000000000000000000000000dEaD,
_tokenId
);
}
// ██████╗ ███████╗ █████╗ ██████╗
// ██╔══██╗██╔════╝██╔══██╗██╔══██╗
// ██████╔╝█████╗ ███████║██║ ██║
// ██╔══██╗██╔══╝ ██╔══██║██║ ██║
// ██║ ██║███████╗██║ ██║██████╔╝
// ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝
/**
* @dev Helper function to reduce pixel size within contract
*/
function letterToNumber(string memory _inputLetter)
internal
view
returns (uint8)
{
for (uint8 i = 0; i < LETTERS.length; i++) {
if (
keccak256(abi.encodePacked((LETTERS[i]))) ==
keccak256(abi.encodePacked((_inputLetter)))
) return (i + 1);
}
revert();
}
/**
* @dev Hash to SVG function
*/
function hashToSVG(string memory _hash)
public
view
returns (string memory)
{
string memory svgString;
bool[24][24] memory placedPixels;
OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract);
for (uint8 i = 0; i < 9; i++) {
uint8 thisTraitIndex = AnonymiceLibrary.parseInt(
AnonymiceLibrary.substring(_hash, i, i + 1)
);
OriginalAnonymiceInterface.Trait memory trait;
if (i == 0) {
trait = OriginalAnonymiceInterface.Trait(
burnedTraitType[thisTraitIndex].traitName,
burnedTraitType[thisTraitIndex].traitType,
burnedTraitType[thisTraitIndex].pixels,
burnedTraitType[thisTraitIndex].pixelCount
);
} else {
(string memory traitName, string memory traitType, string memory pixels, uint pixelCount) =
originalMiceCollection.traitTypes(i, thisTraitIndex);
trait = OriginalAnonymiceInterface.Trait(
traitName,
traitType,
pixels,
pixelCount
);
}
for (
uint16 j = 0;
j < trait.pixelCount;
j++
) {
string memory thisPixel = AnonymiceLibrary.substring(
trait.pixels,
j * 4,
j * 4 + 4
);
uint8 x = letterToNumber(
AnonymiceLibrary.substring(thisPixel, 0, 1)
);
uint8 y = letterToNumber(
AnonymiceLibrary.substring(thisPixel, 1, 2)
);
if (placedPixels[x][y]) continue;
svgString = string(
abi.encodePacked(
svgString,
"<rect class='c",
AnonymiceLibrary.substring(thisPixel, 2, 4),
"' x='",
x.toString(),
"' y='",
y.toString(),
"'/>"
)
);
placedPixels[x][y] = true;
}
}
svgString = string(
abi.encodePacked(
'<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ',
svgString,
"<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#FFEB3B}.c66{fill:#FFC107}</style></svg>"
)
);
return svgString;
}
/**
* @dev Hash to metadata function
*/
function hashToMetadata(string memory _hash, uint _tokenId)
public
view
returns (string memory)
{
string memory metadataString;
OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract);
for (uint8 i = 0; i < 9; i++) {
uint8 thisTraitIndex = AnonymiceLibrary.parseInt(
AnonymiceLibrary.substring(_hash, i, i + 1)
);
OriginalAnonymiceInterface.Trait memory trait;
if (i == 0) {
trait = OriginalAnonymiceInterface.Trait(
burnedTraitType[thisTraitIndex].traitName,
burnedTraitType[thisTraitIndex].traitType,
burnedTraitType[thisTraitIndex].pixels,
burnedTraitType[thisTraitIndex].pixelCount
);
} else {
(string memory traitName, string memory traitType, string memory pixels, uint pixelCount) =
originalMiceCollection.traitTypes(i, thisTraitIndex);
trait = OriginalAnonymiceInterface.Trait(
traitName,
traitType,
pixels,
pixelCount
);
}
metadataString = string(
abi.encodePacked(
metadataString,
'{"trait_type":"',
trait.traitType,
'","value":"',
trait.traitName,
'"}'
)
);
if (i != 8)
metadataString = string(abi.encodePacked(metadataString, ","));
}
// add the property of original token id number
metadataString = string(
abi.encodePacked(
metadataString,
',{"trait_type":"',
'Original Mice Token Id',
'","value":"',
AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]),
'"}'
)
);
return string(abi.encodePacked("[", metadataString, "]"));
}
/**
* @dev Returns the SVG and metadata for a token Id
* @param _tokenId The tokenId to return the SVG and metadata for.
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId));
string memory tokenHash = _tokenIdToHash(_tokenId);
return
string(
abi.encodePacked(
"data:application/json;base64,",
AnonymiceLibrary.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Anonymice #',
AnonymiceLibrary.toString(_tokenId),
'", "description": "Anonymice Cheese Club is a collection of 6,450 mice burned in the original Anonymice collection. They preserve the same traits of the burned ones, with metadata and images generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain.", "image": "data:image/svg+xml;base64,',
AnonymiceLibrary.encode(
bytes(hashToSVG(tokenHash))
),
'","attributes":',
hashToMetadata(tokenHash, _tokenId),
"}"
)
)
)
)
)
);
}
/**
* @dev Returns a hash for a given tokenId
* @param _tokenId The tokenId to return the hash for.
*/
function _tokenIdToHash(uint256 _tokenId)
public
view
returns (string memory)
{
OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract);
string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId]));
//If this is a burned token, override the previous hash
if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) {
tokenHash = string(
abi.encodePacked(
"1",
AnonymiceLibrary.substring(tokenHash, 1, 9)
)
);
} else {
tokenHash = string(
abi.encodePacked(
"0",
AnonymiceLibrary.substring(tokenHash, 1, 9)
)
);
}
return tokenHash;
}
/**
* @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs.
* @param _wallet The wallet to get the tokens of.
*/
function walletOfOwner(address _wallet)
public
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_wallet);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_wallet, i);
}
return tokensId;
}
// ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗
// ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗
// ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝
// ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗
// ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║
// ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝
/**
* @dev Clears the traits.
*/
function clearBurnedTraits() public onlyOwner {
for (uint256 i = 0; i < burnedTraitType.length; i++) {
delete burnedTraitType[i];
}
}
/**
* @dev Add trait types of burned
* @param traits Array of traits to add
*/
function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits)
public
onlyOwner
{
for (uint256 i = 0; i < traits.length; i++) {
burnedTraitType.push(
OriginalAnonymiceInterface.Trait(
traits[i].traitName,
traits[i].traitType,
traits[i].pixels,
traits[i].pixelCount
)
);
}
return;
}
/**
* @dev Collects the total amount in the contract
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721.sol";
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
library AnonymiceLibrary {
string internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal 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);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function parseInt(string memory _a)
internal
pure
returns (uint8 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint8 mint = 0;
for (uint8 i = 0; i < bresult.length; i++) {
if (
(uint8(uint8(bresult[i])) >= 48) &&
(uint8(uint8(bresult[i])) <= 57)
) {
mint *= 10;
mint += uint8(bresult[i]) - 48;
}
}
return mint;
}
function substring(
string memory str,
uint256 startIndex,
uint256 endIndex
) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
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;
}
}
pragma solidity ^0.8.4;
interface OriginalAnonymiceInterface {
struct Trait {
string traitName;
string traitType;
string pixels;
uint256 pixelCount;
}
function _tokenIdToHash(uint _tokenId) external view returns (string memory);
function traitTypes(uint a, uint b) external view returns (string memory, string memory, string memory, uint);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
|
Hash to metadata function/
|
function hashToMetadata(string memory _hash, uint _tokenId)
public
view
returns (string memory)
{
string memory metadataString;
OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract);
for (uint8 i = 0; i < 9; i++) {
uint8 thisTraitIndex = AnonymiceLibrary.parseInt(
AnonymiceLibrary.substring(_hash, i, i + 1)
);
OriginalAnonymiceInterface.Trait memory trait;
if (i == 0) {
trait = OriginalAnonymiceInterface.Trait(
burnedTraitType[thisTraitIndex].traitName,
burnedTraitType[thisTraitIndex].traitType,
burnedTraitType[thisTraitIndex].pixels,
burnedTraitType[thisTraitIndex].pixelCount
);
(string memory traitName, string memory traitType, string memory pixels, uint pixelCount) =
originalMiceCollection.traitTypes(i, thisTraitIndex);
trait = OriginalAnonymiceInterface.Trait(
traitName,
traitType,
pixels,
pixelCount
);
}
metadataString = string(
abi.encodePacked(
metadataString,
'{"trait_type":"',
trait.traitType,
'","value":"',
trait.traitName,
'"}'
)
);
if (i != 8)
metadataString = string(abi.encodePacked(metadataString, ","));
}
abi.encodePacked(
metadataString,
',{"trait_type":"',
'Original Mice Token Id',
'","value":"',
AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]),
'"}'
)
);
return string(abi.encodePacked("[", metadataString, "]"));
}
| 14,342,348 |
./partial_match/80001/0xbFABf2373eEFf171E4462819ba5E51e1F842e51c/sources/@cryptoalgebra/plugins/contracts/interfaces/IAlgebraVirtualPool.sol
|
The interface for the virtual pool Used to calculate active liquidity in farmings
|
interface IAlgebraVirtualPool {
function crossTo(int24 targetTick, bool zeroToOne) external returns (bool success);
pragma solidity >=0.5.0;
}
| 8,815,121 |
pragma solidity ^0.5.0;
library MerkleTreeVerifier {
function math_log2(
uint x
)
public
pure
returns (uint y)
{
assembly {
let arg := x
x := sub(x,1)
x := or(x, div(x, 0x02))
x := or(x, div(x, 0x04))
x := or(x, div(x, 0x10))
x := or(x, div(x, 0x100))
x := or(x, div(x, 0x10000))
x := or(x, div(x, 0x100000000))
x := or(x, div(x, 0x10000000000000000))
x := or(x, div(x, 0x100000000000000000000000000000000))
x := add(x, 1)
let m := mload(0x40)
mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd)
mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe)
mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616)
mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff)
mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e)
mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707)
mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606)
mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100)
mstore(0x40, add(m, 0x100))
let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff
let shift := 0x100000000000000000000000000000000000000000000000000000000000000
let a := div(mul(x, magic), shift)
y := div(mload(add(m,sub(255,a))), shift)
y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000)))
}
}
function _computeMerkleRoot(
bytes32[] memory items
)
public
pure
returns (bytes32)
{
// extend layer to be a power of 2
// this simplifies logic later
bytes32[] memory layer = _getBalancedLayer(items);
// Hash leaves
for(uint i = 0; i < layer.length; i++) {
layer[i] = _hashLeaf(layer[i]);
}
while(layer.length > 1) {
layer = _computeLayer(layer);
}
return layer[0];
}
function _getBalancedLayer(
bytes32[] memory items
)
public
pure
returns (bytes32[] memory)
{
uint powerOf2Size = 2 ** math_log2(items.length);
if(items.length == 1) {
powerOf2Size = 2;
}
bytes32[] memory layer = new bytes32[](powerOf2Size);
for(uint i = 0; i < layer.length; i++) {
if(i < items.length) {
layer[i] = items[i];
} else {
// The rest of the leaves are empty.
layer[i] = 0x00;
}
}
return layer;
}
function _computeLayer(
bytes32[] memory layer
)
public
pure
returns (bytes32[] memory)
{
// require(
// layer.length == (2 ** math_log2(layer.length)),
// "NOT_PERFECT_POWEROF2"
// );
require(
layer.length > 1,
"Layer too small, redundant call"
);
bytes32[] memory nextLayer = new bytes32[](layer.length / 2);
for(uint i = 0; i < nextLayer.length; i++) {
uint left = i * 2;
uint right = left + 1;
nextLayer[i] = _hashBranch(layer[left], layer[right]);
}
return nextLayer;
}
/**
* @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves
* and each pair of pre-images are sorted.
* @param proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree
* @param root Merkle root
* @param leaf Leaf of Merkle tree
*/
function _verify(
bytes32 leaf,
bytes32 root,
bytes32[] memory proof,
bool[] memory paths
)
public
pure
returns (bool)
{
// Check if the computed hash (root) is equal to the provided root
return _computeRoot(proof, paths, leaf) == root;
}
function _computeRoot(
bytes32[] memory proof,
bool[] memory paths,
bytes32 leaf
)
public
pure
returns (bytes32)
{
bytes32 node = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 pairNode = proof[i];
if (paths[i]) {
// Hash(current element of the proof + current computed hash)
node = _hashBranch(pairNode, node);
} else {
// Hash(current computed hash + current element of the proof)
node = _hashBranch(node, pairNode);
}
}
return node;
}
function _hashLeaf(
bytes32 leaf
)
public
pure
returns (bytes32)
{
bytes1 LEAF_PREFIX = 0x00;
return keccak256(abi.encodePacked(LEAF_PREFIX, leaf));
}
function _hashBranch(
bytes32 left,
bytes32 right
)
public
pure
returns (bytes32)
{
bytes1 BRANCH_PREFIX = 0x01;
return keccak256(abi.encodePacked(BRANCH_PREFIX, left, right));
}
}
|
extend layer to be a power of 2 this simplifies logic later Hash leaves
|
function _computeMerkleRoot(
bytes32[] memory items
)
public
pure
returns (bytes32)
{
bytes32[] memory layer = _getBalancedLayer(items);
for(uint i = 0; i < layer.length; i++) {
layer[i] = _hashLeaf(layer[i]);
}
while(layer.length > 1) {
layer = _computeLayer(layer);
}
return layer[0];
}
| 12,921,503 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
import "./Address.sol";
interface ISwapAndLiquify{
function inSwapAndLiquify() external returns(bool);
function swapAndLiquify(uint256 tokenAmount) external;
}
contract ALDN is IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
mapping(address => bool) private _isExcludedFromMaxTxAmount;
address[] private _excluded;
uint256 private constant MAX = type(uint256).max;
uint256 private _tTotal = 1000000000 * 10**6 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "MagicLamp Governance Token";
string private _symbol = "ALDN";
uint8 private _decimals = 9;
// fee factors
uint256 public taxFee = 5;
uint256 private _previousTaxFee;
uint256 public liquidityFee = 5;
uint256 private _previousLiquidityFee;
bool public swapAndLiquifyEnabled = true;
uint256 public maxTxAmount = 5000000 * 10**6 * 10**9;
uint256 private _numTokensSellToAddToLiquidity = 500000 * 10**6 * 10**9;
ISwapAndLiquify public swapAndLiquify;
// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
// @notice A record of each accounts delegate
mapping (address => address) public delegates;
// @notice A checkpoint for marking number of votes from a given block
struct VotesCheckpoint {
uint32 fromBlock;
uint96 tOwned;
uint256 rOwned;
}
// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => VotesCheckpoint)) public votesCheckpoints;
// @notice The number of votes checkpoints for each account
mapping (address => uint32) public numVotesCheckpoints;
// @notice A checkpoint for marking rate from a given block
struct RateCheckpoint {
uint32 fromBlock;
uint256 rate;
}
// @notice A record of rates, by index
mapping (uint32 => RateCheckpoint) public rateCheckpoints;
// @notice The number of rate checkpoints
uint32 public numRateCheckpoints;
// @notice An event thats emitted when swap and liquidify address is changed
event SwapAndLiquifyAddressChanged(address priviousAddress, address newAddress);
// @notice An event thats emitted when swap and liquidify enable is changed
event SwapAndLiquifyEnabledChanged(bool enabled);
// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousROwned, uint previousTOwned, uint newROwned, uint newTOwned);
// @notice An event thats emitted when reflection rate changes
event RateChanged(uint previousRate, uint newRate);
constructor() {
_rOwned[_msgSender()] = _rTotal;
// excludes
_isExcludedFromFee[owner()] = true;
_isExcludedFromMaxTxAmount[owner()] = true;
_isExcluded[address(this)] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromMaxTxAmount[address(this)] = true;
_isExcluded[0x000000000000000000000000000000000000dEaD] = true;
emit Transfer(address(0), owner(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
uint256 spenderAllowance = _allowances[sender][_msgSender()];
if (sender != _msgSender() && spenderAllowance != type(uint256).max) {
_approve(sender, _msgSender(), spenderAllowance.sub(amount,"ERC20: transfer amount exceeds allowance"));
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue,"ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function _getOwns(address account) private view returns (uint256, uint256) {
uint256 rOwned = _isExcluded[account] ? 0 : _rOwned[account];
uint256 tOwned = _isExcluded[account] ? _tOwned[account] : 0;
return (rOwned, tOwned);
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "ALDN::deliver: excluded addresses cannot call this function");
(uint256 oldROwned, uint256 oldTOwned) = _getOwns(sender);
(uint256 rAmount, , , , , ) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
(uint256 newROwned, uint256 newTOwned) = _getOwns(sender);
_moveDelegates(delegates[sender], delegates[sender], oldROwned, oldTOwned, newROwned, newTOwned);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) {
require(tAmount <= _tTotal, "ALDN::reflectionFromToken: amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function _tokenFromReflection(uint256 rAmount, uint256 rate) private pure returns (uint256) {
return rAmount.div(rate);
}
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, "ALDN::tokenFromReflection: amount must be less than total reflections");
return _tokenFromReflection(rAmount, _getCurrentRate());
}
function excludeFromReward(address account) public onlyOwner {
require(!_isExcluded[account], "ALDN::excludeFromReward: account is already excluded");
(uint256 oldROwned, uint256 oldTOwned) = _getOwns(account);
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
(uint256 newROwned, uint256 newTOwned) = _getOwns(account);
_moveDelegates(delegates[account], delegates[account], oldROwned, oldTOwned, newROwned, newTOwned);
}
function includeInReward(address account) external onlyOwner {
require(_isExcluded[account], "ALDN::includeInReward: account is already included");
(uint256 oldROwned, uint256 oldTOwned) = _getOwns(account);
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
(uint256 newROwned, uint256 newTOwned) = _getOwns(account);
_moveDelegates(delegates[account], delegates[account], oldROwned, oldTOwned, newROwned, newTOwned);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function excludeFromMaxTxAmount(address account) public onlyOwner {
_isExcludedFromMaxTxAmount[account] = true;
}
function includeInMaxTxAmount(address account) public onlyOwner {
_isExcludedFromMaxTxAmount[account] = false;
}
function setTaxFeePercent(uint256 newFee) external onlyOwner {
taxFee = newFee;
}
function setLiquidityFeePercent(uint256 newFee) external onlyOwner {
liquidityFee = newFee;
}
function setMaxTxPercent(uint256 newPercent) external onlyOwner {
maxTxAmount = _tTotal.mul(newPercent).div(10**2);
}
function setSwapAndLiquifyAddress(address newAddress) public onlyOwner {
address priviousAddress = address(swapAndLiquify);
require(priviousAddress != newAddress, "ALDN::setSwapAndLiquifyAddress: same address");
_approve(address(this), address(newAddress), type(uint256).max);
swapAndLiquify = ISwapAndLiquify(newAddress);
emit SwapAndLiquifyAddressChanged(priviousAddress, newAddress);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledChanged(_enabled);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getCurrentRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
/**
* @notice Gets the current rate
* @return The current rate
*/
function _getCurrentRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
/**
* @notice Gets the rate at a block number
* @param blockNumber The block number to get the rate at
* @return The rate at the given block
*/
function _getPriorRate(uint blockNumber) private view returns (uint256) {
if (numRateCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (rateCheckpoints[numRateCheckpoints - 1].fromBlock <= blockNumber) {
return rateCheckpoints[numRateCheckpoints - 1].rate;
}
// Next check implicit zero balance
if (rateCheckpoints[0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = numRateCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
RateCheckpoint memory rcp = rateCheckpoints[center];
if (rcp.fromBlock == blockNumber) {
return rcp.rate;
} else if (rcp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return rateCheckpoints[lower].rate;
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getCurrentRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(taxFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(liquidityFee).div(10**2);
}
function removeAllFee() private {
if (taxFee == 0 && liquidityFee == 0) return;
_previousTaxFee = taxFee;
_previousLiquidityFee = liquidityFee;
taxFee = 0;
liquidityFee = 0;
}
function restoreAllFee() private {
taxFee = _previousTaxFee;
liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function isExcludedFromMaxTxAmount(address account) public view returns (bool) {
return _isExcludedFromMaxTxAmount[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ALDN::_approve: approve from the zero address");
require(spender != address(0), "ALDN::_approve: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ALDN::_transfer: transfer from the zero address");
require(to != address(0), "ALDN::_transfer: transfer to the zero address");
require(amount > 0, "ALDN::_transfer: amount must be greater than zero");
require(_isExcludedFromMaxTxAmount[from] || _isExcludedFromMaxTxAmount[to] || amount <= maxTxAmount, "ALDN::_transfer: transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= maxTxAmount) {
contractTokenBalance = maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numTokensSellToAddToLiquidity;
if (overMinTokenBalance && from != owner() && from != address(swapAndLiquify)
&& !swapAndLiquify.inSwapAndLiquify() && swapAndLiquifyEnabled) {
contractTokenBalance = _numTokensSellToAddToLiquidity;
// add liquidity
swapAndLiquify.swapAndLiquify(contractTokenBalance);
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if (sender == recipient) {
emit Transfer(sender, recipient, amount);
return;
}
(uint256 oldSenderROwned, uint256 oldSenderTOwned) = _getOwns(sender);
(uint256 oldRecipientROwned, uint256 oldRecipientTOwned) = _getOwns(recipient);
{
if (!takeFee) {
removeAllFee();
}
bool isExcludedSender = _isExcluded[sender];
bool isExcludedRecipient = _isExcluded[recipient];
if (isExcludedSender && !isExcludedRecipient) {
_transferFromExcluded(sender, recipient, amount);
} else if (!isExcludedSender && isExcludedRecipient) {
_transferToExcluded(sender, recipient, amount);
} else if (!isExcludedSender && !isExcludedRecipient) {
_transferStandard(sender, recipient, amount);
} else if (isExcludedSender && isExcludedRecipient) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) {
restoreAllFee();
}
}
(uint256 newSenderROwned, uint256 newSenderTOwned) = _getOwns(sender);
(uint256 newRecipientROwned, uint256 newRecipientTOwned) = _getOwns(recipient);
_moveDelegates(delegates[sender], delegates[recipient], oldSenderROwned.sub(newSenderROwned), oldSenderTOwned.sub(newSenderTOwned), newRecipientROwned.sub(oldRecipientROwned), newRecipientTOwned.sub(oldRecipientTOwned));
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function burn(uint256 burnQuantity) external override pure returns (bool) {
burnQuantity;
return false;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(_msgSender(), delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(_name)), _getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "ALDN::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "ALDN::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "ALDN::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the votes balance of `checkpoint` with `rate`
* @param rOwned The reflection value to get votes balance
* @param tOwned The balance value to get votes balance
* @param rate The rate to get votes balance
* @return The number of votes with params
*/
function _getVotes(uint256 rOwned, uint256 tOwned, uint256 rate) private pure returns (uint96) {
uint256 votes = 0;
votes = votes.add(_tokenFromReflection(rOwned, rate));
votes = votes.add(tOwned);
return uint96(votes);
}
/**
* @notice Gets the votes balance of `checkpoint` with `rate`
* @param checkpoint The checkpoint to get votes balance
* @param rate The rate to get votes balance
* @return The number of votes of `checkpoint` with `rate`
*/
function _getVotes(VotesCheckpoint memory checkpoint, uint256 rate) private pure returns (uint96) {
return _getVotes(checkpoint.rOwned, checkpoint.tOwned, rate);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numVotesCheckpoints[account];
return nCheckpoints > 0 ? _getVotes(votesCheckpoints[account][nCheckpoints - 1], _getCurrentRate()) : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "ALDN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numVotesCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
uint256 rate = _getPriorRate(blockNumber);
// First check most recent balance
if (votesCheckpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return _getVotes(votesCheckpoints[account][nCheckpoints - 1], rate);
}
// Next check implicit zero balance
if (votesCheckpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
if (votesCheckpoints[account][center].fromBlock == blockNumber) {
return _getVotes(votesCheckpoints[account][center], rate);
} else if (votesCheckpoints[account][center].fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return _getVotes(votesCheckpoints[account][lower], rate);
}
function _delegate(address delegator, address delegatee) private {
address currentDelegate = delegates[delegator];
(uint256 delegatorROwned, uint256 delegatorTOwned) = _getOwns(delegator);
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorROwned, delegatorTOwned, delegatorROwned, delegatorTOwned);
}
function _moveDelegates(address srcRep, address dstRep, uint256 subROwned, uint256 subTOwned, uint256 addROwned, uint256 addTOwned) private {
if (srcRep != dstRep) {
if (srcRep != address(0)) {
uint32 srcRepNum = numVotesCheckpoints[srcRep];
uint256 srcRepOldR = srcRepNum > 0 ? votesCheckpoints[srcRep][srcRepNum - 1].rOwned : 0;
uint256 srcRepOldT = srcRepNum > 0 ? votesCheckpoints[srcRep][srcRepNum - 1].tOwned : 0;
uint256 srcRepNewR = srcRepOldR.sub(subROwned);
uint256 srcRepNewT = srcRepOldT.sub(subTOwned);
if (srcRepOldR != srcRepNewR || srcRepOldT != srcRepNewT) {
_writeCheckpoint(srcRep, srcRepNum, srcRepOldR, srcRepOldT, srcRepNewR, srcRepNewT);
}
}
if (dstRep != address(0)) {
uint32 dstRepNum = numVotesCheckpoints[dstRep];
uint256 dstRepOldR = dstRepNum > 0 ? votesCheckpoints[dstRep][dstRepNum - 1].rOwned : 0;
uint256 dstRepOldT = dstRepNum > 0 ? votesCheckpoints[dstRep][dstRepNum - 1].tOwned : 0;
uint256 dstRepNewR = dstRepOldR.add(addROwned);
uint256 dstRepNewT = dstRepOldT.add(addTOwned);
if (dstRepOldR != dstRepNewR || dstRepOldT != dstRepNewT) {
_writeCheckpoint(dstRep, dstRepNum, dstRepOldR, dstRepOldT, dstRepNewR, dstRepNewT);
}
}
} else if (dstRep != address(0)) {
uint32 dstRepNum = numVotesCheckpoints[dstRep];
uint256 dstRepOldR = dstRepNum > 0 ? votesCheckpoints[dstRep][dstRepNum - 1].rOwned : 0;
uint256 dstRepOldT = dstRepNum > 0 ? votesCheckpoints[dstRep][dstRepNum - 1].tOwned : 0;
uint256 dstRepNewR = dstRepOldR.add(addROwned).sub(subROwned);
uint256 dstRepNewT = dstRepOldT.add(addTOwned).sub(subTOwned);
if (dstRepOldR != dstRepNewR || dstRepOldT != dstRepNewT) {
_writeCheckpoint(dstRep, dstRepNum, dstRepOldR, dstRepOldT, dstRepNewR, dstRepNewT);
}
}
uint256 rate = _getCurrentRate();
uint256 rateOld = numRateCheckpoints > 0 ? rateCheckpoints[numRateCheckpoints - 1].rate : 0;
if (rate != rateOld) {
_writeRateCheckpoint(numRateCheckpoints, rateOld, rate);
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldROwned, uint256 oldTOwned, uint256 newROwned, uint256 newTOwned) private {
uint32 blockNumber = safe32(block.number, "ALDN::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && votesCheckpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
votesCheckpoints[delegatee][nCheckpoints - 1].tOwned = uint96(newTOwned);
votesCheckpoints[delegatee][nCheckpoints - 1].rOwned = newROwned;
} else {
votesCheckpoints[delegatee][nCheckpoints] = VotesCheckpoint(blockNumber, uint96(newTOwned), newROwned);
numVotesCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldROwned, oldTOwned, newROwned, newTOwned);
}
function _writeRateCheckpoint(uint32 nCheckpoints, uint256 oldRate, uint256 newRate) private {
uint32 blockNumber = safe32(block.number, "ALDN::_writeRateCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && rateCheckpoints[nCheckpoints - 1].fromBlock == blockNumber) {
rateCheckpoints[nCheckpoints - 1].rate = newRate;
} else {
rateCheckpoints[nCheckpoints].fromBlock = blockNumber;
rateCheckpoints[nCheckpoints].rate = newRate;
numRateCheckpoints = nCheckpoints + 1;
}
emit RateChanged(oldRate, newRate);
}
function safe32(uint n, string memory errorMessage) private pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function _getChainId() private view returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// 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 custom add
*/
function burn(uint256 burnQuantity) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Context.sol";
// File: @openzeppelin/contracts/access/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
address private _authorizedNewOwner;
event OwnershipTransferAuthorization(address indexed authorizedAddress);
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 Returns the address of the current authorized new owner.
*/
function authorizedNewOwner() public view virtual returns (address) {
return _authorizedNewOwner;
}
/**
* @notice Authorizes the transfer of ownership from _owner to the provided address.
* NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ).
* This authorization may be removed by another call to this function authorizing
* the null address.
*
* @param authorizedAddress The address authorized to become the new owner.
*/
function authorizeOwnershipTransfer(address authorizedAddress) external onlyOwner {
_authorizedNewOwner = authorizedAddress;
emit OwnershipTransferAuthorization(_authorizedNewOwner);
}
/**
* @notice Transfers ownership of this contract to the _authorizedNewOwner.
*/
function assumeOwnership() external {
require(_msgSender() == _authorizedNewOwner, "Ownable: only the authorized new owner can accept ownership");
emit OwnershipTransferred(_owner, _authorizedNewOwner);
_owner = _authorizedNewOwner;
_authorizedNewOwner = address(0);
}
/**
* @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.
*
* @param confirmAddress The address wants to give up ownership.
*/
function renounceOwnership(address confirmAddress) public virtual onlyOwner {
require(confirmAddress == _owner, "Ownable: confirm address is wrong");
emit OwnershipTransferred(_owner, address(0));
_authorizedNewOwner = address(0);
_owner = address(0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @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;
}
}
|
Gets the votes balance of `checkpoint` with `rate` checkpoint The checkpoint to get votes balance rate The rate to get votes balance return The number of votes of `checkpoint` with `rate`/
|
function _getVotes(VotesCheckpoint memory checkpoint, uint256 rate) private pure returns (uint96) {
return _getVotes(checkpoint.rOwned, checkpoint.tOwned, rate);
}
| 1,414,418 |
./full_match/1/0x418a29D6697dcfc1FB6faD99760639164cf2092B/sources/contracts/adapters/AuctionRebalanceExtension.sol
|
OPERATOR ONLY: Checks that the old components array matches the current components array and then invokes the AuctionRebalanceModuleV1 startRebalance function. Refer to AuctionRebalanceModuleV1 for function specific restrictions. _quoteAsset ERC20 token used as the quote asset in auctions. _oldComponents Addresses of existing components in the SetToken. _newComponents Addresses of new components to be added. _newComponentsAuctionParams AuctionExecutionParams for new components, indexed corresponding to _newComponents. _oldComponentsAuctionParams AuctionExecutionParams for existing components, indexed corresponding to the current component positions. Set to 0 for components being removed. _shouldLockSetToken Indicates if the rebalance should lock the SetToken. _rebalanceDuration Duration of the rebalance in seconds. _positionMultiplier Position multiplier at the time target units were calculated./
|
function startRebalance(
IERC20 _quoteAsset,
address[] memory _oldComponents,
address[] memory _newComponents,
AuctionExecutionParams[] memory _newComponentsAuctionParams,
AuctionExecutionParams[] memory _oldComponentsAuctionParams,
bool _shouldLockSetToken,
uint256 _rebalanceDuration,
uint256 _positionMultiplier
)
external
onlyOperator
{
address[] memory currentComponents = setToken.getComponents();
require(currentComponents.length == _oldComponents.length, "Old components length must match the current components length.");
for (uint256 i = 0; i < _oldComponents.length; i++) {
require(currentComponents[i] == _oldComponents[i], "Input old components array must match the current components array.");
}
bytes memory callData = abi.encodeWithSelector(
IAuctionRebalanceModuleV1.startRebalance.selector,
setToken,
_quoteAsset,
_newComponents,
_newComponentsAuctionParams,
_oldComponentsAuctionParams,
_shouldLockSetToken,
_rebalanceDuration,
_positionMultiplier
);
invokeManager(address(auctionModule), callData);
}
| 4,894,984 |
./full_match/42/0x6D2991198C8688261364BBC1F1740a359eBfc761/sources/browser/WETHParty.sol
|
set member shares and loot to burn shares and loot (obviously sets member shares and loot back to 0)
|
function _ragequit(address memberAddress) internal returns (uint256) {
uint256 initialTotalSharesAndLoot = totalShares.add(totalLoot);
Member storage member = members[memberAddress];
require(canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed");
uint256 sharesToBurn = member.shares;
uint256 lootToBurn = member.loot;
uint256 sharesAndLootToBurn = sharesToBurn.add(lootToBurn);
member.shares = member.shares.sub(sharesToBurn);
member.loot = member.loot.sub(lootToBurn);
totalShares = totalShares.sub(sharesToBurn);
totalLoot = totalLoot.sub(lootToBurn);
uint256 feeEligible = fairShare(userTokenBalances[GUILD][wETH], sharesAndLootToBurn, initialTotalSharesAndLoot).sub(member.iVal);
subFees(GUILD, feeEligible);
}
for (uint256 i = 0; i < approvedTokens.length; i++) {
uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot);
userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit;
userTokenBalances[memberAddress][approvedTokens[i]] += amountToRagequit;
earningsPeg -= amountToRagequit;
if(member.iTW > 0) {
uint256 iAdj = amountToRagequit - member.iTW;
if(iAdj > 0) {
unsafeInternalTransfer(memberAddress, GUILD, address(wETH), iAdj);
}
}
member.iTW = 0;
member.iVal = 0;
}
for (uint256 i = 0; i < approvedTokens.length; i++) {
uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot);
userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit;
userTokenBalances[memberAddress][approvedTokens[i]] += amountToRagequit;
earningsPeg -= amountToRagequit;
if(member.iTW > 0) {
uint256 iAdj = amountToRagequit - member.iTW;
if(iAdj > 0) {
unsafeInternalTransfer(memberAddress, GUILD, address(wETH), iAdj);
}
}
member.iTW = 0;
member.iVal = 0;
}
for (uint256 i = 0; i < approvedTokens.length; i++) {
uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot);
userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit;
userTokenBalances[memberAddress][approvedTokens[i]] += amountToRagequit;
earningsPeg -= amountToRagequit;
if(member.iTW > 0) {
uint256 iAdj = amountToRagequit - member.iTW;
if(iAdj > 0) {
unsafeInternalTransfer(memberAddress, GUILD, address(wETH), iAdj);
}
}
member.iTW = 0;
member.iVal = 0;
}
member.iTB = 0;
}
| 9,582,682 |
./full_match/1/0xb84cecd3e0708C3e38E63Ac001E2a4D892c33a57/sources/meTokens.sol
|
Transfer `amount` tokens from `msg.sender` to `dst` dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/
|
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "ME::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
| 3,048,370 |
pragma solidity 0.6.12;
interface IAdmin {
function isAdmin(address user) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/math/[email protected]
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/interfaces/ISalesFactory.sol
pragma solidity 0.6.12;
interface ISalesFactory {
function setSaleOwnerAndToken(address saleOwner, address saleToken) external;
function isSaleCreatedThroughFactory(address sale) external view returns (bool);
}
// File contracts/interfaces/IAllocationStaking.sol
pragma solidity 0.6.12;
interface IAllocationStaking {
function redistributeFame(uint256 _pid, address _user, uint256 _amountToBurn) external;
function deposited(uint256 _pid, address _user) external view returns (uint256);
function setTokensUnlockTime(uint256 _pid, address _user, uint256 _tokensUnlockTime) external;
}
// File contracts/sales/FantomSale.sol
pragma solidity 0.6.12;
contract FantomSale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Pointer to Allocation staking contract, where burnFameFromUser will be called.
IAllocationStaking public allocationStakingContract;
// Pointer to sales factory contract
ISalesFactory public factory;
// Admin contract
IAdmin public admin;
struct Sale {
// Token being sold
IERC20 token;
// Is sale created
bool isCreated;
// Are earnings withdrawn
bool earningsWithdrawn;
// Is leftover withdrawn
bool leftoverWithdrawn;
// Have tokens been deposited
bool tokensDeposited;
// Address of sale owner
address saleOwner;
// Price of the token quoted in FTM
uint256 tokenPriceInFTM;
// Amount of tokens to sell
uint256 amountOfTokensToSell;
// Total tokens being sold
uint256 totalTokensSold;
// Total FTM Raised
uint256 totalFTMRaised;
// Sale end time
uint256 saleEnd;
// When tokens can be withdrawn
uint256 tokensUnlockTime;
}
// Participation structure
struct Participation {
uint256 amountBought;
uint256 amountFTMPaid;
uint256 timeParticipated;
uint256 roundId;
bool[] isPortionWithdrawn;
}
// Round structure
struct Round {
uint256 startTime;
uint256 maxParticipation;
}
struct Registration {
uint256 registrationTimeStarts;
uint256 registrationTimeEnds;
uint256 numberOfRegistrants;
}
// Sale
Sale public sale;
// Registration
Registration public registration;
// Number of users participated in the sale.
uint256 public numberOfParticipants;
// Array storing IDS of rounds (IDs start from 1, so they can't be mapped as array indexes
uint256[] public roundIds;
// Mapping round Id to round
mapping(uint256 => Round) public roundIdToRound;
// Mapping user to his participation
mapping(address => Participation) public userToParticipation;
// User to round for which he registered
mapping(address => uint256) public addressToRoundRegisteredFor;
// mapping if user is participated or not
mapping(address => bool) public isParticipated;
// wei precision
uint256 public constant one = 10**18;
// Times when portions are getting unlocked
uint256[] public vestingPortionsUnlockTime;
// Percent of the participation user can withdraw
uint256[] public vestingPercentPerPortion;
//Precision for percent for portion vesting
uint256 public portionVestingPrecision;
// Added configurable round ID for staking round
uint256 public stakingRoundId;
// Max vesting time shift
uint256 public maxVestingTimeShift;
// Registration deposit FTM, which will be paid during the registration, and returned back during the participation.
uint256 public registrationDepositFTM;
// Accounting total FTM collected, after sale admin can withdraw this
uint256 public registrationFees;
// Restricting calls only to sale owner
modifier onlySaleOwner() {
require(msg.sender == sale.saleOwner, "OnlySaleOwner:: Restricted");
_;
}
modifier onlyAdmin() {
require(
admin.isAdmin(msg.sender),
"Only admin can call this function."
);
_;
}
// EVENTS
event TokensSold(address user, uint256 amount);
event UserRegistered(address user, uint256 roundId);
event TokenPriceSet(uint256 newPrice);
event MaxParticipationSet(uint256 roundId, uint256 maxParticipation);
event TokensWithdrawn(address user, uint256 amount);
event SaleCreated(
address saleOwner,
uint256 tokenPriceInFTM,
uint256 amountOfTokensToSell,
uint256 saleEnd,
uint256 tokensUnlockTime
);
event RegistrationTimeSet(
uint256 registrationTimeStarts,
uint256 registrationTimeEnds
);
event RoundAdded(
uint256 roundId,
uint256 startTime,
uint256 maxParticipation
);
event RegistrationFTMRefunded(address user, uint256 amountRefunded);
// Constructor, always initialized through SalesFactory
constructor(address _admin, address _allocationStaking) public {
require(_admin != address(0));
require(_allocationStaking != address(0));
admin = IAdmin(_admin);
factory = ISalesFactory(msg.sender);
allocationStakingContract = IAllocationStaking(_allocationStaking);
}
/// @notice Function to set vesting params
function setVestingParams(
uint256[] memory _unlockingTimes,
uint256[] memory _percents,
uint256 _maxVestingTimeShift
) external onlyAdmin {
require(
vestingPercentPerPortion.length == 0 &&
vestingPortionsUnlockTime.length == 0
);
require(_unlockingTimes.length == _percents.length);
require(portionVestingPrecision > 0, "Safeguard for making sure setSaleParams get first called.");
require(_maxVestingTimeShift <= 30 days, "Maximal shift is 30 days.");
// Set max vesting time shift
maxVestingTimeShift = _maxVestingTimeShift;
uint256 sum;
for (uint256 i = 0; i < _unlockingTimes.length; i++) {
vestingPortionsUnlockTime.push(_unlockingTimes[i]);
vestingPercentPerPortion.push(_percents[i]);
sum += _percents[i];
}
require(sum == portionVestingPrecision, "Percent distribution issue.");
}
function shiftVestingUnlockingTimes(uint256 timeToShift)
external
onlyAdmin
{
require(
timeToShift > 0 && timeToShift < maxVestingTimeShift,
"Shift must be nonzero and smaller than maxVestingTimeShift."
);
// Time can be shifted only once.
maxVestingTimeShift = 0;
for (uint256 i = 0; i < vestingPortionsUnlockTime.length; i++) {
vestingPortionsUnlockTime[i] = vestingPortionsUnlockTime[i].add(
timeToShift
);
}
}
/// @notice Admin function to set sale parameters
function setSaleParams(
address _token,
address _saleOwner,
uint256 _tokenPriceInFTM,
uint256 _amountOfTokensToSell,
uint256 _saleEnd,
uint256 _tokensUnlockTime,
uint256 _portionVestingPrecision,
uint256 _stakingRoundId,
uint256 _registrationDepositFTM
) external onlyAdmin {
require(!sale.isCreated, "setSaleParams: Sale is already created.");
require(
_saleOwner != address(0),
"setSaleParams: Sale owner address can not be 0."
);
require(
_tokenPriceInFTM != 0 &&
_amountOfTokensToSell != 0 &&
_saleEnd > block.timestamp &&
_tokensUnlockTime > block.timestamp,
"setSaleParams: Bad input"
);
require(_portionVestingPrecision >= 100, "Should be at least 100");
require(_stakingRoundId > 0, "Staking round ID can not be 0.");
// Set params
sale.token = IERC20(_token);
sale.isCreated = true;
sale.saleOwner = _saleOwner;
sale.tokenPriceInFTM = _tokenPriceInFTM;
sale.amountOfTokensToSell = _amountOfTokensToSell;
sale.saleEnd = _saleEnd;
sale.tokensUnlockTime = _tokensUnlockTime;
// Deposit in FTM, sent during the registration
registrationDepositFTM = _registrationDepositFTM;
// Set portion vesting precision
portionVestingPrecision = _portionVestingPrecision;
// Set staking round id
stakingRoundId = _stakingRoundId;
// Emit event
emit SaleCreated(
sale.saleOwner,
sale.tokenPriceInFTM,
sale.amountOfTokensToSell,
sale.saleEnd,
sale.tokensUnlockTime
);
}
// @notice Function to retroactively set sale token address, can be called only once,
// after initial contract creation has passed. Added as an options for teams which
// are not having token at the moment of sale launch.
function setSaleToken(
address saleToken
)
external
onlyAdmin
{
require(address(sale.token) == address(0));
sale.token = IERC20(saleToken);
}
/// @notice Function to set registration period parameters
function setRegistrationTime(
uint256 _registrationTimeStarts,
uint256 _registrationTimeEnds
) external onlyAdmin {
require(sale.isCreated);
require(registration.registrationTimeStarts == 0);
require(
_registrationTimeStarts >= block.timestamp &&
_registrationTimeEnds > _registrationTimeStarts
);
require(_registrationTimeEnds < sale.saleEnd);
if (roundIds.length > 0) {
require(
_registrationTimeEnds < roundIdToRound[roundIds[0]].startTime
);
}
registration.registrationTimeStarts = _registrationTimeStarts;
registration.registrationTimeEnds = _registrationTimeEnds;
emit RegistrationTimeSet(
registration.registrationTimeStarts,
registration.registrationTimeEnds
);
}
function setRounds(
uint256[] calldata startTimes,
uint256[] calldata maxParticipations
) external onlyAdmin {
require(sale.isCreated);
require(
startTimes.length == maxParticipations.length,
"setRounds: Bad input."
);
require(roundIds.length == 0, "setRounds: Rounds are set already.");
require(startTimes.length > 0);
uint256 lastTimestamp = 0;
for (uint256 i = 0; i < startTimes.length; i++) {
require(startTimes[i] > registration.registrationTimeEnds);
require(startTimes[i] < sale.saleEnd);
require(startTimes[i] >= block.timestamp);
require(maxParticipations[i] > 0);
require(startTimes[i] > lastTimestamp);
lastTimestamp = startTimes[i];
// Compute round Id
uint256 roundId = i + 1;
// Push id to array of ids
roundIds.push(roundId);
// Create round
Round memory round = Round(startTimes[i], maxParticipations[i]);
// Map round id to round
roundIdToRound[roundId] = round;
// Fire event
emit RoundAdded(roundId, round.startTime, round.maxParticipation);
}
}
/// @notice Registration for sale.
/// @param roundId is the round for which user expressed interest to participate
function registerForSale(uint256 roundId)
external
payable
{
require(
msg.value == registrationDepositFTM,
"Registration deposit does not match."
);
require(roundId != 0, "Round ID can not be 0.");
require(roundId <= roundIds.length, "Invalid round id");
require(
block.timestamp >= registration.registrationTimeStarts &&
block.timestamp <= registration.registrationTimeEnds,
"Registration gate is closed."
);
require(
addressToRoundRegisteredFor[msg.sender] == 0,
"User can not register twice."
);
// Rounds are 1,2,3
addressToRoundRegisteredFor[msg.sender] = roundId;
// Special cases for staking round
if (roundId == stakingRoundId) {
// Lock users stake
allocationStakingContract.setTokensUnlockTime(
0,
msg.sender,
sale.saleEnd
);
}
// Increment number of registered users
registration.numberOfRegistrants++;
// Increase earnings from registration fees
registrationFees = registrationFees.add(msg.value);
// Emit Registration event
emit UserRegistered(msg.sender, roundId);
}
/// @notice Admin function, to update token price before sale to match the closest $ desired rate.
/// @dev This will be updated with an oracle during the sale every N minutes, so the users will always
/// pay initialy set $ value of the token. This is to reduce reliance on the FTM volatility.
function updateTokenPriceInFTM(uint256 price) external onlyAdmin {
require(price > 0, "Price can not be 0.");
// Allowing oracle to run and change the sale value
sale.tokenPriceInFTM = price;
emit TokenPriceSet(price);
}
/// @notice Admin function to postpone the sale
function postponeSale(uint256 timeToShift) external onlyAdmin {
require(
block.timestamp < roundIdToRound[roundIds[0]].startTime,
"1st round already started."
);
// Iterate through all registered rounds and postpone them
for (uint256 i = 0; i < roundIds.length; i++) {
Round storage round = roundIdToRound[roundIds[i]];
// Postpone sale
round.startTime = round.startTime.add(timeToShift);
require(
round.startTime + timeToShift < sale.saleEnd,
"Start time can not be greater than end time."
);
}
}
/// @notice Function to extend registration period
function extendRegistrationPeriod(uint256 timeToAdd) external onlyAdmin {
require(
registration.registrationTimeEnds.add(timeToAdd) <
roundIdToRound[roundIds[0]].startTime,
"Registration period overflows sale start."
);
registration.registrationTimeEnds = registration
.registrationTimeEnds
.add(timeToAdd);
}
/// @notice Admin function to set max participation cap per round
function setCapPerRound(uint256[] calldata rounds, uint256[] calldata caps)
external
onlyAdmin
{
require(
block.timestamp < roundIdToRound[roundIds[0]].startTime,
"1st round already started."
);
require(rounds.length == caps.length, "Arrays length is different.");
for (uint256 i = 0; i < rounds.length; i++) {
require(caps[i] > 0, "Can't set max participation to 0");
Round storage round = roundIdToRound[rounds[i]];
round.maxParticipation = caps[i];
emit MaxParticipationSet(rounds[i], round.maxParticipation);
}
}
// Function for owner to deposit tokens, can be called only once.
function depositTokens() external onlySaleOwner {
require(
!sale.tokensDeposited, "Deposit can be done only once"
);
sale.tokensDeposited = true;
sale.token.safeTransferFrom(
msg.sender,
address(this),
sale.amountOfTokensToSell
);
}
// Function to participate in the sales
function participate(
uint256 amount,
uint256 amountFameToBurn,
uint256 roundId
) external payable {
require(roundId != 0, "Round can not be 0.");
require(
amount <= roundIdToRound[roundId].maxParticipation,
"Overflowing maximal participation for this round."
);
// User must have registered for the round in advance
require(
addressToRoundRegisteredFor[msg.sender] == roundId,
"Not registered for this round"
);
// Check user haven't participated before
require(!isParticipated[msg.sender], "User can participate only once.");
// Disallow contract calls.
require(msg.sender == tx.origin, "Only direct contract calls.");
// Get current active round
uint256 currentRound = getCurrentRound();
// Assert that
require(
roundId == currentRound,
"You can not participate in this round."
);
// Compute the amount of tokens user is buying
uint256 amountOfTokensBuying = (msg.value).mul(one).div(
sale.tokenPriceInFTM
);
// Must buy more than 0 tokens
require(amountOfTokensBuying > 0, "Can't buy 0 tokens");
// Check in terms of user allo
require(
amountOfTokensBuying <= amount,
"Trying to buy more than allowed."
);
// Increase amount of sold tokens
sale.totalTokensSold = sale.totalTokensSold.add(amountOfTokensBuying);
// Increase amount of FTM raised
sale.totalFTMRaised = sale.totalFTMRaised.add(msg.value);
bool[] memory _isPortionWithdrawn = new bool[](
vestingPortionsUnlockTime.length
);
// Create participation object
Participation memory p = Participation({
amountBought: amountOfTokensBuying,
amountFTMPaid: msg.value,
timeParticipated: block.timestamp,
roundId: roundId,
isPortionWithdrawn: _isPortionWithdrawn
});
// Staking round only.
if (roundId == stakingRoundId) {
// Burn FAME from this user.
allocationStakingContract.redistributeFame(
0,
msg.sender,
amountFameToBurn
);
}
// Add participation for user.
userToParticipation[msg.sender] = p;
// Mark user is participated
isParticipated[msg.sender] = true;
// Increment number of participants in the Sale.
numberOfParticipants++;
// Decrease of available registration fees
registrationFees = registrationFees.sub(registrationDepositFTM);
// Transfer registration deposit amount in FTM back to the users.
safeTransferFTM(msg.sender, registrationDepositFTM);
emit RegistrationFTMRefunded(msg.sender, registrationDepositFTM);
emit TokensSold(msg.sender, amountOfTokensBuying);
}
/// Users can claim their participation
function withdrawTokens(uint256 portionId) external {
require(
block.timestamp >= sale.tokensUnlockTime,
"Tokens can not be withdrawn yet."
);
require(portionId < vestingPercentPerPortion.length);
Participation storage p = userToParticipation[msg.sender];
if (
!p.isPortionWithdrawn[portionId] &&
vestingPortionsUnlockTime[portionId] <= block.timestamp
) {
p.isPortionWithdrawn[portionId] = true;
uint256 amountWithdrawing = p
.amountBought
.mul(vestingPercentPerPortion[portionId])
.div(portionVestingPrecision);
// Withdraw percent which is unlocked at that portion
if(amountWithdrawing > 0) {
sale.token.safeTransfer(msg.sender, amountWithdrawing);
emit TokensWithdrawn(msg.sender, amountWithdrawing);
}
} else {
revert("Tokens already withdrawn or portion not unlocked yet.");
}
}
// Expose function where user can withdraw multiple unlocked portions at once.
function withdrawMultiplePortions(uint256 [] calldata portionIds) external {
uint256 totalToWithdraw = 0;
Participation storage p = userToParticipation[msg.sender];
for(uint i=0; i < portionIds.length; i++) {
uint256 portionId = portionIds[i];
require(portionId < vestingPercentPerPortion.length);
if (
!p.isPortionWithdrawn[portionId] &&
vestingPortionsUnlockTime[portionId] <= block.timestamp
) {
p.isPortionWithdrawn[portionId] = true;
uint256 amountWithdrawing = p
.amountBought
.mul(vestingPercentPerPortion[portionId])
.div(portionVestingPrecision);
// Withdraw percent which is unlocked at that portion
totalToWithdraw = totalToWithdraw.add(amountWithdrawing);
}
}
if(totalToWithdraw > 0) {
sale.token.safeTransfer(msg.sender, totalToWithdraw);
emit TokensWithdrawn(msg.sender, totalToWithdraw);
}
}
// Internal function to handle safe transfer
function safeTransferFTM(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success);
}
/// Function to withdraw all the earnings and the leftover of the sale contract.
function withdrawEarningsAndLeftover() external onlySaleOwner {
withdrawEarningsInternal();
withdrawLeftoverInternal();
}
// Function to withdraw only earnings
function withdrawEarnings() external onlySaleOwner {
withdrawEarningsInternal();
}
// Function to withdraw only leftover
function withdrawLeftover() external onlySaleOwner {
withdrawLeftoverInternal();
}
// function to withdraw earnings
function withdrawEarningsInternal() internal {
// Make sure sale ended
require(block.timestamp >= sale.saleEnd);
// Make sure owner can't withdraw twice
require(!sale.earningsWithdrawn);
sale.earningsWithdrawn = true;
// Earnings amount of the owner in FTM
uint256 totalProfit = sale.totalFTMRaised;
safeTransferFTM(msg.sender, totalProfit);
}
// Function to withdraw leftover
function withdrawLeftoverInternal() internal {
// Make sure sale ended
require(block.timestamp >= sale.saleEnd);
// Make sure owner can't withdraw twice
require(!sale.leftoverWithdrawn);
sale.leftoverWithdrawn = true;
// Amount of tokens which are not sold
uint256 leftover = sale.amountOfTokensToSell.sub(sale.totalTokensSold);
if (leftover > 0) {
sale.token.safeTransfer(msg.sender, leftover);
}
}
// Function after sale for admin to withdraw registration fees if there are any left.
function withdrawRegistrationFees() external onlyAdmin {
require(block.timestamp >= sale.saleEnd, "Require that sale has ended.");
require(registrationFees > 0, "No earnings from registration fees.");
// Transfer FTM to the admin wallet.
safeTransferFTM(msg.sender, registrationFees);
// Set registration fees to be 0
registrationFees = 0;
}
// Function where admin can withdraw all unused funds.
function withdrawUnusedFunds() external onlyAdmin {
uint256 balanceFTM = address(this).balance;
uint256 totalReservedForRaise = sale.earningsWithdrawn ? 0 : sale.totalFTMRaised;
safeTransferFTM(
msg.sender,
balanceFTM.sub(totalReservedForRaise.add(registrationFees))
);
}
// Function to act as a fallback and handle receiving FTM.
receive() external payable {
}
/// @notice Get current round in progress.
/// If 0 is returned, means sale didn't start or it's ended.
function getCurrentRound() public view returns (uint256) {
uint256 i = 0;
if (block.timestamp < roundIdToRound[roundIds[0]].startTime) {
return 0; // Sale didn't start yet.
}
while (
(i + 1) < roundIds.length &&
block.timestamp > roundIdToRound[roundIds[i + 1]].startTime
) {
i++;
}
if (block.timestamp >= sale.saleEnd) {
return 0; // Means sale is ended
}
return roundIds[i];
}
/// @notice Function to get participation for passed user address
function getParticipation(address _user)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
bool[] memory
)
{
Participation memory p = userToParticipation[_user];
return (
p.amountBought,
p.amountFTMPaid,
p.timeParticipated,
p.roundId,
p.isPortionWithdrawn
);
}
/// @notice Function to get number of registered users for sale
function getNumberOfRegisteredUsers() external view returns (uint256) {
return registration.numberOfRegistrants;
}
/// @notice Function to get all info about vesting.
function getVestingInfo()
external
view
returns (uint256[] memory, uint256[] memory)
{
return (vestingPortionsUnlockTime, vestingPercentPerPortion);
}
}
// File contracts/sales/SalesFactory.sol
pragma solidity 0.6.12;
contract SalesFactory {
IAdmin public admin;
address public allocationStaking;
mapping (address => bool) public isSaleCreatedThroughFactory;
mapping(address => address) public saleOwnerToSale;
mapping(address => address) public tokenToSale;
// Expose so query can be possible only by position as well
address [] public allSales;
event SaleDeployed(address saleContract);
event SaleOwnerAndTokenSetInFactory(address sale, address saleOwner, address saleToken);
modifier onlyAdmin {
require(admin.isAdmin(msg.sender), "Only Admin can deploy sales");
_;
}
constructor (address _adminContract, address _allocationStaking) public {
admin = IAdmin(_adminContract);
allocationStaking = _allocationStaking;
}
// Set allocation staking contract address.
function setAllocationStaking(address _allocationStaking) public onlyAdmin {
require(_allocationStaking != address(0));
allocationStaking = _allocationStaking;
}
function deploySale()
external
onlyAdmin
{
FantomSale sale = new FantomSale(address(admin), allocationStaking);
isSaleCreatedThroughFactory[address(sale)] = true;
allSales.push(address(sale));
emit SaleDeployed(address(sale));
}
// Function to return number of pools deployed
function getNumberOfSalesDeployed() external view returns (uint) {
return allSales.length;
}
// Function
function getLastDeployedSale() external view returns (address) {
//
if(allSales.length > 0) {
return allSales[allSales.length - 1];
}
return address(0);
}
// Function to get all sales
function getAllSales(uint startIndex, uint endIndex) external view returns (address[] memory) {
require(endIndex > startIndex, "Bad input");
address[] memory sales = new address[](endIndex - startIndex);
uint index = 0;
for(uint i = startIndex; i < endIndex; i++) {
sales[index] = allSales[i];
index++;
}
return sales;
}
}
|
Compute round Id Push id to array of ids Create round Map round id to round Fire event
|
function setRounds(
uint256[] calldata startTimes,
uint256[] calldata maxParticipations
) external onlyAdmin {
require(sale.isCreated);
require(
startTimes.length == maxParticipations.length,
"setRounds: Bad input."
);
require(roundIds.length == 0, "setRounds: Rounds are set already.");
require(startTimes.length > 0);
uint256 lastTimestamp = 0;
for (uint256 i = 0; i < startTimes.length; i++) {
require(startTimes[i] > registration.registrationTimeEnds);
require(startTimes[i] < sale.saleEnd);
require(startTimes[i] >= block.timestamp);
require(maxParticipations[i] > 0);
require(startTimes[i] > lastTimestamp);
lastTimestamp = startTimes[i];
uint256 roundId = i + 1;
roundIds.push(roundId);
Round memory round = Round(startTimes[i], maxParticipations[i]);
roundIdToRound[roundId] = round;
emit RoundAdded(roundId, round.startTime, round.maxParticipation);
}
}
| 12,826,352 |
./full_match/1/0xcEAb38B5C88F33Dabe4D31BDD384E08215526632/sources/browser/CompoundSaverFlashProxy.sol
|
Internal method that preforms a sell on 0x/on-chain Usefull for other DFS contract to integrate for exchanging exData Exchange data struct return (address, uint) Address of the wrapper used and destAmount if selling eth, convert to weth Try 0x first and then fallback on specific wrapper fallback to desired wrapper if 0x failed if anything is left in weth, pull it to user as eth
|
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
uint tokensLeft = exData.srcAmount;
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = exData.srcAddr == WETH_ADDRESS ? msg.value - exData.srcAmount : msg.value;
(success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);
if (success) {
wrapper = exData.exchangeAddr;
}
}
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct");
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
| 3,169,906 |
./full_match/1/0x6307be80ABACAEc6305a2b353EeCa338Ba469d39/sources/contracts/QuiddMintables.sol
|
@inheritdoc ERC165/
|
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(QuiddMintablesBase, ERC2981TokenIDMask, AccessControl)
returns (bool)
{
return QuiddMintablesBase.supportsInterface(interfaceId) ||
ERC2981TokenIDMask.supportsInterface(interfaceId) ||
AccessControl.supportsInterface(interfaceId);
}
| 9,798,064 |
./full_match/5/0x2ACde37ab4FFF420eF8C277984E5f869C32B76e4/sources/contracts/Contract.sol
|
Allows a voter to login using their department and matriculation number. _department The department of the voter. _matriculationNumber The matriculation number of the voter./
|
function loginVoter(string memory _department, string memory _matriculationNumber) public {
require(bytes(_department).length > 0, "Invalid department name");
require(isValidMatriculationNumber(_department, _matriculationNumber), "Invalid matriculation number");
voters[msg.sender] = Voter(false, _department);
}
| 7,063,426 |
pragma solidity ^0.4.24;
/**
* @title ERC721 Non-Fungible Token Standard Basic Interface
* @dev Based on openzepplin open source ERC721 examples.
* See (https://github.com/OpenZeppelin/openzeppelin-solidity)
*/
contract ERC721 {
/**
* @dev 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* @dev 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/**
* @dev 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* @dev 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/** @dev A mapping of interface id to whether or not it is supported */
mapping(bytes4 => bool) internal supportedInterfaces;
/** @dev Token events */
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/** @dev Registers ERC-165, ERC-721, ERC-721 Enumerable and ERC-721 Metadata as supported interfaces */
constructor() public
{
registerInterface(InterfaceId_ERC165);
registerInterface(InterfaceId_ERC721);
registerInterface(InterfaceId_ERC721Enumerable);
registerInterface(InterfaceId_ERC721Metadata);
}
/** @dev Internal function for registering an interface */
function registerInterface(bytes4 _interfaceId) internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
/** @dev ERC-165 interface implementation */
function supportsInterface(bytes4 _interfaceId) external view returns(bool)
{
return supportedInterfaces[_interfaceId];
}
/** @dev ERC-721 interface */
function balanceOf(address _owner) public view returns(uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns(address _owner);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns(address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns(bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public;
/** @dev ERC-721 Enumerable interface */
function totalSupply() public view returns(uint256 _total);
function tokenByIndex(uint256 _index) public view returns(uint256 _tokenId);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns(uint256 _tokenId);
/** @dev ERC-721 Metadata interface */
function name() public view returns(string _name);
function symbol() public view returns(string _symbol);
function tokenURI(uint256 _tokenId) public view returns(string);
}
/**
* @title PixelCons Core
* @notice The purpose of this contract is to provide a shared ecosystem of minimal pixel art tokens for everyone to use. All users are treated
* equally with the exception of an admin user who only controls the ERC721 metadata function which points to the app website. No fees are
* required to interact with this contract beyond base gas fees. Here are a few notes on the basic workings of the contract:
* PixelCons [The core ERC721 token of this contract]
* -Each PixelCon is unique with an ID that encodes all its pixel data
* -PixelCons can be identified by both TokenIDs and TokenIndexes (index requires fewer bits to store)
* -A PixelCon can never be destroyed
* -Total number of PixelCons is limited to 18,446,744,073,709,551,616 (2^64)
* -A single account can only hold 4,294,967,296 PixelCons (2^32)
* Collections [Grouping mechanism for associating PixelCons together]
* -Collections are identified by an index (zero is invalid)
* -Collections can only be created by a user who both created and currently owns all its PixelCons
* -Total number of collections is limited to 18,446,744,073,709,551,616 (2^64)
* For more information about PixelCons, please visit (https://pixelcons.io)
* @dev This contract follows the ERC721 token standard with additional functions for creating, grouping, etc.
* See (https://github.com/OpenZeppelin/openzeppelin-solidity)
* @author PixelCons
*/
contract PixelCons is ERC721 {
using AddressUtils for address;
/** @dev Equal to 'bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))' */
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////// Structs ///////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** @dev The main PixelCon struct */
struct PixelCon {
uint256 tokenId;
//// ^256bits ////
address creator;
uint64 collectionIndex;
uint32 dateCreated;
}
/** @dev A struct linking a token owner with its token index */
struct TokenLookup {
address owner;
uint64 tokenIndex;
uint32 ownedIndex;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////// Storage ///////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** @dev The address thats allowed to withdraw volunteered funds sent to this contract */
address internal admin;
/** @dev The URI template for retrieving token metadata */
string internal tokenURITemplate;
////////////////// PixelCon Tokens //////////////////
/** @dev Mapping from token ID to owner/index */
mapping(uint256 => TokenLookup) internal tokenLookup;
/** @dev Mapping from owner to token indexes */
mapping(address => uint64[]) internal ownedTokens;
/** @dev Mapping from creator to token indexes */
mapping(address => uint64[]) internal createdTokens;
/** @dev Mapping from token ID to approved address */
mapping(uint256 => address) internal tokenApprovals;
/** @dev Mapping from owner to operator approvals */
mapping(address => mapping(address => bool)) internal operatorApprovals;
/** @dev An array containing all PixelCons in existence */
PixelCon[] internal pixelcons;
/** @dev An array that mirrors 'pixelcons' in terms of indexing, but stores only name data */
bytes8[] internal pixelconNames;
////////////////// Collections //////////////////
/** @dev Mapping from collection index to token indexes */
mapping(uint64 => uint64[]) internal collectionTokens;
/** @dev An array that mirrors 'collectionTokens' in terms of indexing, but stores only name data */
bytes8[] internal collectionNames;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////// Events ////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** @dev PixelCon token events */
event Create(uint256 indexed _tokenId, address indexed _creator, uint64 _tokenIndex, address _to);
event Rename(uint256 indexed _tokenId, bytes8 _newName);
/** @dev PixelCon collection events */
event CreateCollection(address indexed _creator, uint64 indexed _collectionIndex);
event RenameCollection(uint64 indexed _collectionIndex, bytes8 _newName);
event ClearCollection(uint64 indexed _collectionIndex);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////// Modifiers ///////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** @dev Small validators for quick validation of function parameters */
modifier validIndex(uint64 _index) {
require(_index != uint64(0), "Invalid index");
_;
}
modifier validId(uint256 _id) {
require(_id != uint256(0), "Invalid ID");
_;
}
modifier validAddress(address _address) {
require(_address != address(0), "Invalid address");
_;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////// PixelCons Core ///////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Contract constructor
*/
constructor() public
{
//admin defaults to the contract creator
admin = msg.sender;
//fill zero index pixelcon collection
collectionNames.length++;
}
/**
* @notice Get the current admin
* @return The current admin
*/
function getAdmin() public view returns(address)
{
return admin;
}
/**
* @notice Withdraw all volunteered funds to `(_to)`
* @param _to Address to withdraw the funds to
*/
function adminWithdraw(address _to) public
{
require(msg.sender == admin, "Only the admin can call this function");
_to.transfer(address(this).balance);
}
/**
* @notice Change the admin to `(_to)`
* @param _newAdmin New admin address
*/
function adminChange(address _newAdmin) public
{
require(msg.sender == admin, "Only the admin can call this function");
admin = _newAdmin;
}
/**
* @notice Change the token URI template
* @param _newTokenURITemplate New token URI template
*/
function adminSetTokenURITemplate(string _newTokenURITemplate) public
{
require(msg.sender == admin, "Only the admin can call this function");
tokenURITemplate = _newTokenURITemplate;
}
////////////////// PixelCon Tokens //////////////////
/**
* @notice Create PixelCon `(_tokenId)`
* @dev Throws if the token ID already exists
* @param _to Address that will own the PixelCon
* @param _tokenId ID of the PixelCon to be creates
* @param _name PixelCon name (not required)
* @return The index of the new PixelCon
*/
function create(address _to, uint256 _tokenId, bytes8 _name) public payable validAddress(_to) validId(_tokenId) returns(uint64)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(pixelcons.length < uint256(2 ** 64) - 1, "Max number of PixelCons has been reached");
require(lookupData.owner == address(0), "PixelCon already exists");
//get created timestamp (zero as date indicates null)
uint32 dateCreated = 0;
if (now < uint256(2 ** 32)) dateCreated = uint32(now);
//create PixelCon token and set owner
uint64 index = uint64(pixelcons.length);
lookupData.tokenIndex = index;
pixelcons.length++;
pixelconNames.length++;
PixelCon storage pixelcon = pixelcons[index];
pixelcon.tokenId = _tokenId;
pixelcon.creator = msg.sender;
pixelcon.dateCreated = dateCreated;
pixelconNames[index] = _name;
uint64[] storage createdList = createdTokens[msg.sender];
uint createdListIndex = createdList.length;
createdList.length++;
createdList[createdListIndex] = index;
addTokenTo(_to, _tokenId);
emit Create(_tokenId, msg.sender, index, _to);
emit Transfer(address(0), _to, _tokenId);
return index;
}
/**
* @notice Rename PixelCon `(_tokenId)`
* @dev Throws if the caller is not the owner and creator of the token
* @param _tokenId ID of the PixelCon to rename
* @param _name New name
* @return The index of the PixelCon
*/
function rename(uint256 _tokenId, bytes8 _name) public validId(_tokenId) returns(uint64)
{
require(isCreatorAndOwner(msg.sender, _tokenId), "Sender is not the creator and owner");
//update name
TokenLookup storage lookupData = tokenLookup[_tokenId];
pixelconNames[lookupData.tokenIndex] = _name;
emit Rename(_tokenId, _name);
return lookupData.tokenIndex;
}
/**
* @notice Check if PixelCon `(_tokenId)` exists
* @param _tokenId ID of the PixelCon to query the existence of
* @return True if the PixelCon exists
*/
function exists(uint256 _tokenId) public view validId(_tokenId) returns(bool)
{
address owner = tokenLookup[_tokenId].owner;
return owner != address(0);
}
/**
* @notice Get the creator of PixelCon `(_tokenId)`
* @dev Throws if PixelCon does not exist
* @param _tokenId ID of the PixelCon to query the creator of
* @return Creator address for PixelCon
*/
function creatorOf(uint256 _tokenId) public view validId(_tokenId) returns(address)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner != address(0), "PixelCon does not exist");
return pixelcons[lookupData.tokenIndex].creator;
}
/**
* @notice Get the total number of PixelCons created by `(_creator)`
* @param _creator Address to query the total of
* @return Total number of PixelCons created by given address
*/
function creatorTotal(address _creator) public view validAddress(_creator) returns(uint256)
{
return createdTokens[_creator].length;
}
/**
* @notice Enumerate PixelCon created by `(_creator)`
* @dev Throws if index is out of bounds
* @param _creator Creator address
* @param _index Counter less than `creatorTotal(_creator)`
* @return PixelCon ID for the `(_index)`th PixelCon created by `(_creator)`
*/
function tokenOfCreatorByIndex(address _creator, uint256 _index) public view validAddress(_creator) returns(uint256)
{
require(_index < createdTokens[_creator].length, "Index is out of bounds");
PixelCon storage pixelcon = pixelcons[createdTokens[_creator][_index]];
return pixelcon.tokenId;
}
/**
* @notice Get all details of PixelCon `(_tokenId)`
* @dev Throws if PixelCon does not exist
* @param _tokenId ID of the PixelCon to get details for
* @return PixelCon details
*/
function getTokenData(uint256 _tokenId) public view validId(_tokenId)
returns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner != address(0), "PixelCon does not exist");
PixelCon storage pixelcon = pixelcons[lookupData.tokenIndex];
return (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner,
pixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated);
}
/**
* @notice Get all details of PixelCon #`(_tokenIndex)`
* @dev Throws if PixelCon does not exist
* @param _tokenIndex Index of the PixelCon to get details for
* @return PixelCon details
*/
function getTokenDataByIndex(uint64 _tokenIndex) public view
returns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated)
{
require(_tokenIndex < totalSupply(), "PixelCon index is out of bounds");
PixelCon storage pixelcon = pixelcons[_tokenIndex];
TokenLookup storage lookupData = tokenLookup[pixelcon.tokenId];
return (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner,
pixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated);
}
/**
* @notice Get the index of PixelCon `(_tokenId)`
* @dev Throws if PixelCon does not exist
* @param _tokenId ID of the PixelCon to query the index of
* @return Index of the given PixelCon ID
*/
function getTokenIndex(uint256 _tokenId) validId(_tokenId) public view returns(uint64)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner != address(0), "PixelCon does not exist");
return lookupData.tokenIndex;
}
////////////////// Collections //////////////////
/**
* @notice Create PixelCon collection
* @dev Throws if the message sender is not the owner and creator of the given tokens
* @param _tokenIndexes Token indexes to group together into a collection
* @param _name Name of the collection
* @return Index of the new collection
*/
function createCollection(uint64[] _tokenIndexes, bytes8 _name) public returns(uint64)
{
require(collectionNames.length < uint256(2 ** 64) - 1, "Max number of collections has been reached");
require(_tokenIndexes.length > 1, "Collection must contain more than one PixelCon");
//loop through given indexes to add to collection and check additional requirements
uint64 collectionIndex = uint64(collectionNames.length);
uint64[] storage collection = collectionTokens[collectionIndex];
collection.length = _tokenIndexes.length;
for (uint i = 0; i < _tokenIndexes.length; i++) {
uint64 tokenIndex = _tokenIndexes[i];
require(tokenIndex < totalSupply(), "PixelCon index is out of bounds");
PixelCon storage pixelcon = pixelcons[tokenIndex];
require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons");
require(pixelcon.collectionIndex == uint64(0), "PixelCon is already in a collection");
pixelcon.collectionIndex = collectionIndex;
collection[i] = tokenIndex;
}
collectionNames.length++;
collectionNames[collectionIndex] = _name;
emit CreateCollection(msg.sender, collectionIndex);
return collectionIndex;
}
/**
* @notice Rename collection #`(_collectionIndex)`
* @dev Throws if the message sender is not the owner and creator of all collection tokens
* @param _collectionIndex Index of the collection to rename
* @param _name New name
* @return Index of the collection
*/
function renameCollection(uint64 _collectionIndex, bytes8 _name) validIndex(_collectionIndex) public returns(uint64)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
//loop through the collections token indexes and check additional requirements
uint64[] storage collection = collectionTokens[_collectionIndex];
require(collection.length > 0, "Collection has been cleared");
for (uint i = 0; i < collection.length; i++) {
PixelCon storage pixelcon = pixelcons[collection[i]];
require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons");
}
//update
collectionNames[_collectionIndex] = _name;
emit RenameCollection(_collectionIndex, _name);
return _collectionIndex;
}
/**
* @notice Clear collection #`(_collectionIndex)`
* @dev Throws if the message sender is not the owner and creator of all collection tokens
* @param _collectionIndex Index of the collection to clear out
* @return Index of the collection
*/
function clearCollection(uint64 _collectionIndex) validIndex(_collectionIndex) public returns(uint64)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
//loop through the collections token indexes and check additional requirements while clearing pixelcon collection index
uint64[] storage collection = collectionTokens[_collectionIndex];
require(collection.length > 0, "Collection is already cleared");
for (uint i = 0; i < collection.length; i++) {
PixelCon storage pixelcon = pixelcons[collection[i]];
require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons");
pixelcon.collectionIndex = 0;
}
//clear out collection data
delete collectionNames[_collectionIndex];
delete collectionTokens[_collectionIndex];
emit ClearCollection(_collectionIndex);
return _collectionIndex;
}
/**
* @notice Check if collection #`(_collectionIndex)` exists
* @param _collectionIndex Index of the collection to query the existence of
* @return True if collection exists
*/
function collectionExists(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bool)
{
return _collectionIndex < totalCollections();
}
/**
* @notice Check if collection #`(_collectionIndex)` has been cleared
* @dev Throws if the collection index is out of bounds
* @param _collectionIndex Index of the collection to query the state of
* @return True if collection has been cleared
*/
function collectionCleared(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bool)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
return collectionTokens[_collectionIndex].length == uint256(0);
}
/**
* @notice Get the total number of collections
* @return Total number of collections
*/
function totalCollections() public view returns(uint256)
{
return collectionNames.length;
}
/**
* @notice Get the collection index of PixelCon `(_tokenId)`
* @dev Throws if the PixelCon does not exist
* @param _tokenId ID of the PixelCon to query the collection of
* @return Collection index of given PixelCon
*/
function collectionOf(uint256 _tokenId) public view validId(_tokenId) returns(uint256)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner != address(0), "PixelCon does not exist");
return pixelcons[tokenLookup[_tokenId].tokenIndex].collectionIndex;
}
/**
* @notice Get the total number of PixelCons in collection #`(_collectionIndex)`
* @dev Throws if the collection does not exist
* @param _collectionIndex Collection index to query the total of
* @return Total number of PixelCons in the collection
*/
function collectionTotal(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(uint256)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
return collectionTokens[_collectionIndex].length;
}
/**
* @notice Get the name of collection #`(_collectionIndex)`
* @dev Throws if the collection does not exist
* @param _collectionIndex Collection index to query the name of
* @return Collection name
*/
function getCollectionName(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bytes8)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
return collectionNames[_collectionIndex];
}
/**
* @notice Enumerate PixelCon in collection #`(_collectionIndex)`
* @dev Throws if the collection does not exist or index is out of bounds
* @param _collectionIndex Collection index
* @param _index Counter less than `collectionTotal(_collection)`
* @return PixelCon ID for the `(_index)`th PixelCon in collection #`(_collectionIndex)`
*/
function tokenOfCollectionByIndex(uint64 _collectionIndex, uint256 _index) public view validIndex(_collectionIndex) returns(uint256)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
require(_index < collectionTokens[_collectionIndex].length, "Index is out of bounds");
PixelCon storage pixelcon = pixelcons[collectionTokens[_collectionIndex][_index]];
return pixelcon.tokenId;
}
////////////////// Web3 Only //////////////////
/**
* @notice Get the indexes of all PixelCons owned by `(_owner)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @param _owner Owner address
* @return PixelCon indexes
*/
function getForOwner(address _owner) public view validAddress(_owner) returns(uint64[])
{
return ownedTokens[_owner];
}
/**
* @notice Get the indexes of all PixelCons created by `(_creator)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @param _creator Creator address
* @return PixelCon indexes
*/
function getForCreator(address _creator) public view validAddress(_creator) returns(uint64[])
{
return createdTokens[_creator];
}
/**
* @notice Get the indexes of all PixelCons in collection #`(_collectionIndex)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @param _collectionIndex Collection index
* @return PixelCon indexes
*/
function getForCollection(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(uint64[])
{
return collectionTokens[_collectionIndex];
}
/**
* @notice Get the basic data for the given PixelCon indexes
* @dev This function is for web3 calls only, as it returns a dynamic array
* @param _tokenIndexes List of PixelCon indexes
* @return All PixelCon basic data
*/
function getBasicData(uint64[] _tokenIndexes) public view returns(uint256[], bytes8[], address[], uint64[])
{
uint256[] memory tokenIds = new uint256[](_tokenIndexes.length);
bytes8[] memory names = new bytes8[](_tokenIndexes.length);
address[] memory owners = new address[](_tokenIndexes.length);
uint64[] memory collectionIdxs = new uint64[](_tokenIndexes.length);
for (uint i = 0; i < _tokenIndexes.length; i++) {
uint64 tokenIndex = _tokenIndexes[i];
require(tokenIndex < totalSupply(), "PixelCon index is out of bounds");
tokenIds[i] = pixelcons[tokenIndex].tokenId;
names[i] = pixelconNames[tokenIndex];
owners[i] = tokenLookup[pixelcons[tokenIndex].tokenId].owner;
collectionIdxs[i] = pixelcons[tokenIndex].collectionIndex;
}
return (tokenIds, names, owners, collectionIdxs);
}
/**
* @notice Get the names of all PixelCons
* @dev This function is for web3 calls only, as it returns a dynamic array
* @return The names of all PixelCons in existence
*/
function getAllNames() public view returns(bytes8[])
{
return pixelconNames;
}
/**
* @notice Get the names of all PixelCons from index `(_startIndex)` to `(_endIndex)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @return The names of the PixelCons in the given range
*/
function getNamesInRange(uint64 _startIndex, uint64 _endIndex) public view returns(bytes8[])
{
require(_startIndex <= totalSupply(), "Start index is out of bounds");
require(_endIndex <= totalSupply(), "End index is out of bounds");
require(_startIndex <= _endIndex, "End index is less than the start index");
uint64 length = _endIndex - _startIndex;
bytes8[] memory names = new bytes8[](length);
for (uint i = 0; i < length; i++) {
names[i] = pixelconNames[_startIndex + i];
}
return names;
}
/**
* @notice Get details of collection #`(_collectionIndex)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @param _collectionIndex Index of the collection to get the data of
* @return Collection name and included PixelCon indexes
*/
function getCollectionData(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bytes8, uint64[])
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
return (collectionNames[_collectionIndex], collectionTokens[_collectionIndex]);
}
/**
* @notice Get the names of all collections
* @dev This function is for web3 calls only, as it returns a dynamic array
* @return The names of all PixelCon collections in existence
*/
function getAllCollectionNames() public view returns(bytes8[])
{
return collectionNames;
}
/**
* @notice Get the names of all collections from index `(_startIndex)` to `(_endIndex)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @return The names of the collections in the given range
*/
function getCollectionNamesInRange(uint64 _startIndex, uint64 _endIndex) public view returns(bytes8[])
{
require(_startIndex <= totalCollections(), "Start index is out of bounds");
require(_endIndex <= totalCollections(), "End index is out of bounds");
require(_startIndex <= _endIndex, "End index is less than the start index");
uint64 length = _endIndex - _startIndex;
bytes8[] memory names = new bytes8[](length);
for (uint i = 0; i < length; i++) {
names[i] = collectionNames[_startIndex + i];
}
return names;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////// ERC-721 Implementation ///////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Get the balance of `(_owner)`
* @param _owner Owner address
* @return Owner balance
*/
function balanceOf(address _owner) public view validAddress(_owner) returns(uint256)
{
return ownedTokens[_owner].length;
}
/**
* @notice Get the owner of PixelCon `(_tokenId)`
* @dev Throws if PixelCon does not exist
* @param _tokenId ID of the token
* @return Owner of the given PixelCon
*/
function ownerOf(uint256 _tokenId) public view validId(_tokenId) returns(address)
{
address owner = tokenLookup[_tokenId].owner;
require(owner != address(0), "PixelCon does not exist");
return owner;
}
/**
* @notice Approve `(_to)` to transfer PixelCon `(_tokenId)` (zero indicates no approved address)
* @dev Throws if not called by the owner or an approved operator
* @param _to Address to be approved
* @param _tokenId ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public validId(_tokenId)
{
address owner = tokenLookup[_tokenId].owner;
require(_to != owner, "Cannot approve PixelCon owner");
require(msg.sender == owner || operatorApprovals[owner][msg.sender], "Sender does not have permission to approve address");
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @notice Get the approved address for PixelCon `(_tokenId)`
* @dev Throws if the PixelCon does not exist
* @param _tokenId ID of the token
* @return Address currently approved for the given PixelCon
*/
function getApproved(uint256 _tokenId) public view validId(_tokenId) returns(address)
{
address owner = tokenLookup[_tokenId].owner;
require(owner != address(0), "PixelCon does not exist");
return tokenApprovals[_tokenId];
}
/**
* @notice Set or unset the approval of operator `(_to)`
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to Operator address to set the approval
* @param _approved Flag for setting approval
*/
function setApprovalForAll(address _to, bool _approved) public validAddress(_to)
{
require(_to != msg.sender, "Cannot approve self");
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @notice Get if `(_operator)` is an approved operator for owner `(_owner)`
* @param _owner Owner address
* @param _operator Operator address
* @return True if the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view validAddress(_owner) validAddress(_operator) returns(bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @notice Transfer the ownership of PixelCon `(_tokenId)` to `(_to)` (try to use 'safeTransferFrom' instead)
* @dev Throws if the sender is not the owner, approved, or operator
* @param _from Current owner
* @param _to Address to receive the PixelCon
* @param _tokenId ID of the PixelCon to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public validAddress(_from) validAddress(_to) validId(_tokenId)
{
require(isApprovedOrOwner(msg.sender, _tokenId), "Sender does not have permission to transfer PixelCon");
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @notice Safely transfer the ownership of PixelCon `(_tokenId)` to `(_to)`
* @dev Throws if receiver is a contract that does not respond or the sender is not the owner, approved, or operator
* @param _from Current owner
* @param _to Address to receive the PixelCon
* @param _tokenId ID of the PixelCon to be transferred
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public
{
//requirements are checked in 'transferFrom' function
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @notice Safely transfer the ownership of PixelCon `(_tokenId)` to `(_to)`
* @dev Throws if receiver is a contract that does not respond or the sender is not the owner, approved, or operator
* @param _from Current owner
* @param _to Address to receive the PixelCon
* @param _tokenId ID of the PixelCon to be transferred
* @param _data Data to send along with a safe transfer check
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public
{
//requirements are checked in 'transferFrom' function
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data), "Transfer was not safe");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// ERC-721 Enumeration Implementation /////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Get the total number of PixelCons in existence
* @return Total number of PixelCons in existence
*/
function totalSupply() public view returns(uint256)
{
return pixelcons.length;
}
/**
* @notice Get the ID of PixelCon #`(_tokenIndex)`
* @dev Throws if index is out of bounds
* @param _tokenIndex Counter less than `totalSupply()`
* @return `_tokenIndex`th PixelCon ID
*/
function tokenByIndex(uint256 _tokenIndex) public view returns(uint256)
{
require(_tokenIndex < totalSupply(), "PixelCon index is out of bounds");
return pixelcons[_tokenIndex].tokenId;
}
/**
* @notice Enumerate PixelCon assigned to owner `(_owner)`
* @dev Throws if the index is out of bounds
* @param _owner Owner address
* @param _index Counter less than `balanceOf(_owner)`
* @return PixelCon ID for the `(_index)`th PixelCon in owned by `(_owner)`
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view validAddress(_owner) returns(uint256)
{
require(_index < ownedTokens[_owner].length, "Index is out of bounds");
PixelCon storage pixelcon = pixelcons[ownedTokens[_owner][_index]];
return pixelcon.tokenId;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// ERC-721 Metadata Implementation //////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Get the name of this contract token
* @return Contract token name
*/
function name() public view returns(string)
{
return "PixelCons";
}
/**
* @notice Get the symbol for this contract token
* @return Contract token symbol
*/
function symbol() public view returns(string)
{
return "PXCN";
}
/**
* @notice Get a distinct Uniform Resource Identifier (URI) for PixelCon `(_tokenId)`
* @dev Throws if the given PixelCon does not exist
* @return PixelCon URI
*/
function tokenURI(uint256 _tokenId) public view returns(string)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner != address(0), "PixelCon does not exist");
PixelCon storage pixelcon = pixelcons[lookupData.tokenIndex];
bytes8 pixelconName = pixelconNames[lookupData.tokenIndex];
//Available values: <tokenId>, <tokenIndex>, <name>, <owner>, <creator>, <dateCreated>, <collectionIndex>
//start with the token URI template and replace in the appropriate values
string memory finalTokenURI = tokenURITemplate;
finalTokenURI = StringUtils.replace(finalTokenURI, "<tokenId>", StringUtils.toHexString(_tokenId, 32));
finalTokenURI = StringUtils.replace(finalTokenURI, "<tokenIndex>", StringUtils.toHexString(uint256(lookupData.tokenIndex), 8));
finalTokenURI = StringUtils.replace(finalTokenURI, "<name>", StringUtils.toHexString(uint256(pixelconName), 8));
finalTokenURI = StringUtils.replace(finalTokenURI, "<owner>", StringUtils.toHexString(uint256(lookupData.owner), 20));
finalTokenURI = StringUtils.replace(finalTokenURI, "<creator>", StringUtils.toHexString(uint256(pixelcon.creator), 20));
finalTokenURI = StringUtils.replace(finalTokenURI, "<dateCreated>", StringUtils.toHexString(uint256(pixelcon.dateCreated), 8));
finalTokenURI = StringUtils.replace(finalTokenURI, "<collectionIndex>", StringUtils.toHexString(uint256(pixelcon.collectionIndex), 8));
return finalTokenURI;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////// Utils ////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Check whether the given editor is the current owner and original creator of a given token ID
* @param _address Address to check for
* @param _tokenId ID of the token to be edited
* @return True if the editor is approved for the given token ID, is an operator of the owner, or is the owner of the token
*/
function isCreatorAndOwner(address _address, uint256 _tokenId) internal view returns(bool)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
address owner = lookupData.owner;
address creator = pixelcons[lookupData.tokenIndex].creator;
return (_address == owner && _address == creator);
}
/**
* @notice Check whether the given spender can transfer a given token ID
* @dev Throws if the PixelCon does not exist
* @param _address Address of the spender to query
* @param _tokenId ID of the token to be transferred
* @return True if the spender is approved for the given token ID, is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _address, uint256 _tokenId) internal view returns(bool)
{
address owner = tokenLookup[_tokenId].owner;
require(owner != address(0), "PixelCon does not exist");
return (_address == owner || tokenApprovals[_tokenId] == _address || operatorApprovals[owner][_address]);
}
/**
* @notice Clear current approval of a given token ID
* @dev Throws if the given address is not indeed the owner of the token
* @param _owner Owner of the token
* @param _tokenId ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal
{
require(tokenLookup[_tokenId].owner == _owner, "Incorrect PixelCon owner");
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @notice Add a token ID to the list of a given address
* @dev Throws if the receiver address has hit ownership limit or the PixelCon already has an owner
* @param _to Address representing the new owner of the given token ID
* @param _tokenId ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal
{
uint64[] storage ownedList = ownedTokens[_to];
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(ownedList.length < uint256(2 ** 32) - 1, "Max number of PixelCons per owner has been reached");
require(lookupData.owner == address(0), "PixelCon already has an owner");
lookupData.owner = _to;
//update ownedTokens references
uint ownedListIndex = ownedList.length;
ownedList.length++;
lookupData.ownedIndex = uint32(ownedListIndex);
ownedList[ownedListIndex] = lookupData.tokenIndex;
}
/**
* @notice Remove a token ID from the list of a given address
* @dev Throws if the given address is not indeed the owner of the token
* @param _from Address representing the previous owner of the given token ID
* @param _tokenId ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal
{
uint64[] storage ownedList = ownedTokens[_from];
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner == _from, "From address is incorrect");
lookupData.owner = address(0);
//update ownedTokens references
uint64 replacementTokenIndex = ownedList[ownedList.length - 1];
delete ownedList[ownedList.length - 1];
ownedList.length--;
if (lookupData.ownedIndex < ownedList.length) {
//we just removed the last token index in the array, but if this wasn't the one to remove, then swap it with the one to remove
ownedList[lookupData.ownedIndex] = replacementTokenIndex;
tokenLookup[pixelcons[replacementTokenIndex].tokenId].ownedIndex = lookupData.ownedIndex;
}
lookupData.ownedIndex = 0;
}
/**
* @notice Invoke `onERC721Received` on a target address (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 ID of the token to be transferred
* @param _data Optional data to send along with the call
* @return True if the call correctly returned the expected value
*/
function checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal returns(bool)
{
if (!_to.isContract()) return true;
bytes4 retval = ERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers from ERC721 asset contracts.
* See (https://github.com/OpenZeppelin/openzeppelin-solidity)
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT.
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
/**
* @title AddressUtils Library
* @dev Utility library of inline functions on addresses.
* See (https://github.com/OpenZeppelin/openzeppelin-solidity)
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address _account) internal view returns(bool)
{
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(_account) }
return size > 0;
}
}
/**
* @title StringUtils Library
* @dev Utility library of inline functions on strings.
* These functions are very expensive and are only intended for web3 calls
* @author PixelCons
*/
library StringUtils {
/**
* @dev Replaces the given key with the given value in the given string
* @param _str String to find and replace in
* @param _key Value to search for
* @param _value Value to replace key with
* @return The replaced string
*/
function replace(string _str, string _key, string _value) internal pure returns(string)
{
bytes memory bStr = bytes(_str);
bytes memory bKey = bytes(_key);
bytes memory bValue = bytes(_value);
uint index = indexOf(bStr, bKey);
if (index < bStr.length) {
bytes memory rStr = new bytes((bStr.length + bValue.length) - bKey.length);
uint i;
for (i = 0; i < index; i++) rStr[i] = bStr[i];
for (i = 0; i < bValue.length; i++) rStr[index + i] = bValue[i];
for (i = 0; i < bStr.length - (index + bKey.length); i++) rStr[index + bValue.length + i] = bStr[index + bKey.length + i];
return string(rStr);
}
return string(bStr);
}
/**
* @dev Converts a given number into a string with hex representation
* @param _num Number to convert
* @param _byteSize Size of the number in bytes
* @return The hex representation as string
*/
function toHexString(uint256 _num, uint _byteSize) internal pure returns(string)
{
bytes memory s = new bytes(_byteSize * 2 + 2);
s[0] = 0x30;
s[1] = 0x78;
for (uint i = 0; i < _byteSize; i++) {
byte b = byte(uint8(_num / (2 ** (8 * (_byteSize - 1 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2 + 2 * i] = char(hi);
s[3 + 2 * i] = char(lo);
}
return string(s);
}
/**
* @dev Gets the ascii hex character for the given value (0-15)
* @param _b Byte to get ascii code for
* @return The ascii hex character
*/
function char(byte _b) internal pure returns(byte c)
{
if (_b < 10) return byte(uint8(_b) + 0x30);
else return byte(uint8(_b) + 0x57);
}
/**
* @dev Gets the index of the key string in the given string
* @param _str String to search in
* @param _key Value to search for
* @return The index of the key in the string (string length if not found)
*/
function indexOf(bytes _str, bytes _key) internal pure returns(uint)
{
for (uint i = 0; i < _str.length - (_key.length - 1); i++) {
bool matchFound = true;
for (uint j = 0; j < _key.length; j++) {
if (_str[i + j] != _key[j]) {
matchFound = false;
break;
}
}
if (matchFound) {
return i;
}
}
return _str.length;
}
}
|
Enumerate PixelCon in collection `(_collectionIndex)` Throws if the collection does not exist or index is out of bounds _collectionIndex Collection index _index Counter less than `collectionTotal(_collection)` return PixelCon ID for the `(_index)`th PixelCon in collection `(_collectionIndex)`/
|
function tokenOfCollectionByIndex(uint64 _collectionIndex, uint256 _index) public view validIndex(_collectionIndex) returns(uint256)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
require(_index < collectionTokens[_collectionIndex].length, "Index is out of bounds");
PixelCon storage pixelcon = pixelcons[collectionTokens[_collectionIndex][_index]];
return pixelcon.tokenId;
}
| 1,804,972 |
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;
/**
* @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));
owner = newOwner;
}
}
contract ERC721Interface {
// Required methods
// function totalSupply() public view returns (uint256 total);
// function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
// function approve(address _to, uint256 _tokenId) external;
// function transfer(address _to, uint256 _tokenId) external;
// function transferFrom(address _from, address _to, uint256 _tokenId) external;
}
/**
* @dev Name provider contract
* Allows saving names and descriptons for specified addresses and tokens
*/
contract NameProvider is Ownable {
uint256 public FEE = 1 finney;
//name storage for addresses
mapping(bytes32 => mapping(address => string)) addressNames;
//marks namespaces as already used on first name save to specified namespace
mapping(bytes32 => bool) takenNamespaces;
//name storage for tokens
mapping(address => mapping(uint256 => string)) tokenNames;
//description storage for tokens
mapping(address => mapping(uint256 => string)) tokenDescriptions;
/* EVENTS */
event NameChanged(bytes32 namespace, address account, string name);
event TokenNameChanged(address tokenProvider, uint256 tokenId, string name);
event TokenDescriptionChanged(address tokenProvider, uint256 tokenId, string description);
function NameProvider(address _owner) public {
require(_owner != address(0));
owner = _owner;
}
modifier setTokenText(address _tokenInterface, uint256 _tokenId, string _text){
//check fee
require(msg.value >= FEE);
//no empty strings allowed
require(bytes(_text).length > 0);
ERC721Interface tokenInterface = ERC721Interface(_tokenInterface);
//only token owner can set its name
require(msg.sender == tokenInterface.ownerOf(_tokenId));
_;//set text code
//return excess
if (msg.value > FEE) {
msg.sender.transfer(msg.value - FEE);
}
}
//@dev set name for specified token,
// NB msg.sender must be owner of the specified token.
//@param _tokenInterface ERC721 protocol provider address
//@param _tokenId id of the token, whose name will be set
//@param _name string that will be set as new token name
function setTokenName(address _tokenInterface, uint256 _tokenId, string _name)
setTokenText(_tokenInterface, _tokenId, _name) external payable {
_setTokenName(_tokenInterface, _tokenId, _name);
}
//@dev set description for specified token,
// NB msg.sender must be owner of the specified token.
//@param _tokenInterface ERC721 protocol provider address
//@param _tokenId id of the token, whose description will be set
//@param _description string that will be set as new token description
function setTokenDescription(address _tokenInterface, uint256 _tokenId, string _description)
setTokenText(_tokenInterface, _tokenId, _description) external payable {
_setTokenDescription(_tokenInterface, _tokenId, _description);
}
//@dev get name of specified token,
//@param _tokenInterface ERC721 protocol provider address
//@param _tokenId id of the token, whose name will be returned
function getTokenName(address _tokenInterface, uint256 _tokenId) external view returns(string) {
return tokenNames[_tokenInterface][_tokenId];
}
//@dev get description of specified token,
//@param _tokenInterface ERC721 protocol provider address
//@param _tokenId id of the token, whose description will be returned
function getTokenDescription(address _tokenInterface, uint256 _tokenId) external view returns(string) {
return tokenDescriptions[_tokenInterface][_tokenId];
}
//@dev set global name for msg.sender,
// NB msg.sender must be owner of the specified token.
//@param _name string that will be set as new address name
function setName(string _name) external payable {
setServiceName(bytes32(0), _name);
}
//@dev set name for msg.sender in cpecified namespace,
// NB msg.sender must be owner of the specified token.
//@param _namespace bytes32 service identifier
//@param _name string that will be set as new address name
function setServiceName(bytes32 _namespace, string memory _name) public payable {
//check fee
require(msg.value >= FEE);
//set name
_setName(_namespace, _name);
//return excess
if (msg.value > FEE) {
msg.sender.transfer(msg.value - FEE);
}
}
//@dev get global name for specified address,
//@param _address the address for whom name string will be returned
function getNameByAddress(address _address) external view returns(string) {
return addressNames[bytes32(0)][_address];
}
//@dev get global name for msg.sender,
function getName() external view returns(string) {
return addressNames[bytes32(0)][msg.sender];
}
//@dev get name for specified address and namespace,
//@param _namespace bytes32 service identifier
//@param _address the address for whom name string will be returned
function getServiceNameByAddress(bytes32 _namespace, address _address) external view returns(string) {
return addressNames[_namespace][_address];
}
//@dev get name for specified namespace and msg.sender,
//@param _namespace bytes32 service identifier
function getServiceName(bytes32 _namespace) external view returns(string) {
return addressNames[_namespace][msg.sender];
}
//@dev get names for specified addresses in global namespace (bytes32(0))
//@param _address address[] array of addresses for whom names will be returned
//@return namesData bytes32
//@return nameLength number of bytes32 in address name, sum of nameLength values equals namesData.length (1 to 1 with _address)
function getNames(address[] _address) external view returns(bytes32[] namesData, uint256[] nameLength) {
return getServiceNames(bytes32(0), _address);
}
//@dev get names for specified tokens
//@param _tokenIds uint256[] array of ids for whom names will be returned
//@return namesData bytes32
//@return nameLength number of bytes32 in token name, sum of nameLength values equals namesData.length (1 to 1 with _tokenIds)
function getTokenNames(address _tokenInterface, uint256[] _tokenIds) external view returns(bytes32[] memory namesData, uint256[] memory nameLength) {
return _getTokenTexts(_tokenInterface, _tokenIds, true);
}
//@dev get names for specified tokens
//@param _tokenIds uint256[] array of ids for whom descriptons will be returned
//@return descriptonData bytes32
//@return descriptionLength number of bytes32 in token name, sum of nameLength values equals namesData.length (1 to 1 with _tokenIds)
function getTokenDescriptions(address _tokenInterface, uint256[] _tokenIds) external view returns(bytes32[] memory descriptonData, uint256[] memory descriptionLength) {
return _getTokenTexts(_tokenInterface, _tokenIds, false);
}
//@dev get names for specified addresses and namespace
//@param _namespace bytes32 namespace identifier
//@param _address address[] array of addresses for whom names will be returned
//@return namesData bytes32
//@return nameLength number of bytes32 in address name, sum of nameLength values equals namesData.length (1 to 1 with _address)
function getServiceNames(bytes32 _namespace, address[] _address) public view returns(bytes32[] memory namesData, uint256[] memory nameLength) {
uint256 length = _address.length;
nameLength = new uint256[](length);
bytes memory stringBytes;
uint256 size = 0;
uint256 i;
for (i = 0; i < length; i ++) {
stringBytes = bytes(addressNames[_namespace][_address[i]]);
size += nameLength[i] = stringBytes.length % 32 == 0 ? stringBytes.length / 32 : stringBytes.length / 32 + 1;
}
namesData = new bytes32[](size);
size = 0;
for (i = 0; i < length; i ++) {
size += _stringToBytes32(addressNames[_namespace][_address[i]], namesData, size);
}
}
function namespaceTaken(bytes32 _namespace) external view returns(bool) {
return takenNamespaces[_namespace];
}
function setFee(uint256 _fee) onlyOwner external {
FEE = _fee;
}
function withdraw() onlyOwner external {
owner.transfer(this.balance);
}
function _setName(bytes32 _namespace, string _name) internal {
addressNames[_namespace][msg.sender] = _name;
if (!takenNamespaces[_namespace]) {
takenNamespaces[_namespace] = true;
}
NameChanged(_namespace, msg.sender, _name);
}
function _setTokenName(address _tokenInterface, uint256 _tokenId, string _name) internal {
tokenNames[_tokenInterface][_tokenId] = _name;
TokenNameChanged(_tokenInterface, _tokenId, _name);
}
function _setTokenDescription(address _tokenInterface, uint256 _tokenId, string _description) internal {
tokenDescriptions[_tokenInterface][_tokenId] = _description;
TokenDescriptionChanged(_tokenInterface, _tokenId, _description);
}
function _getTokenTexts(address _tokenInterface, uint256[] memory _tokenIds, bool names) internal view returns(bytes32[] memory namesData, uint256[] memory nameLength) {
uint256 length = _tokenIds.length;
nameLength = new uint256[](length);
mapping(address => mapping(uint256 => string)) textMap = names ? tokenNames : tokenDescriptions;
bytes memory stringBytes;
uint256 size = 0;
uint256 i;
for (i = 0; i < length; i ++) {
stringBytes = bytes(textMap[_tokenInterface][_tokenIds[i]]);
size += nameLength[i] = stringBytes.length % 32 == 0 ? stringBytes.length / 32 : stringBytes.length / 32 + 1;
}
namesData = new bytes32[](size);
size = 0;
for (i = 0; i < length; i ++) {
size += _stringToBytes32(textMap[_tokenInterface][_tokenIds[i]], namesData, size);
}
}
function _stringToBytes32(string memory source, bytes32[] memory namesData, uint256 _start) internal pure returns (uint256) {
bytes memory stringBytes = bytes(source);
uint256 length = stringBytes.length;
bytes32[] memory result = new bytes32[](length % 32 == 0 ? length / 32 : length / 32 + 1);
bytes32 word;
uint256 index = 0;
uint256 limit = 0;
for (uint256 i = 0; i < length; i += 32) {
limit = i + 32;
assembly {
word := mload(add(source, limit))
}
namesData[_start + index++] = word;
}
return result.length;
}
}
|
get names for specified tokens _tokenIds uint256[] array of ids for whom descriptons will be returnedreturn descriptonData bytes32return descriptionLength number of bytes32 in token name, sum of nameLength values equals namesData.length (1 to 1 with _tokenIds)
|
function getTokenDescriptions(address _tokenInterface, uint256[] _tokenIds) external view returns(bytes32[] memory descriptonData, uint256[] memory descriptionLength) {
return _getTokenTexts(_tokenInterface, _tokenIds, false);
}
| 2,569,560 |
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/MacToken.sol
pragma solidity 0.6.12;
// MacToken with Governance.
contract MacToken is ERC20("MacToken", "MAC"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterFarmer).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "MAC::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "MAC::delegateBySig: invalid nonce");
require(now <= expiry, "MAC::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "MAC::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying MACs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "MAC::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/MasterFarmer.sol
pragma solidity 0.6.12;
interface IMigratorFarmer {
// Perform LP token migration from legacy UniswapV2 to MacdonaldsFarm.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// MacdonaldsFarm must mint EXACTLY the same amount of MacdonaldsFarm LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// MasterFarmer is the master of Macdonalds Farm. He can make and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once MAC is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterFarmer is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of MACs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accMacPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accMacPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. MACs to distribute per block.
uint256 lastRewardBlock; // Last block number that MACs distribution occurs.
uint256 accMacPerShare; // Accumulated MACs per share, times 1e12. See below.
}
// The MAC TOKEN!
MacToken public mac;
// Dev address.
address public devaddr;
// MAC tokens created per block.
uint256 public macPerBlock;
// Bonus muliplier for early mac makers.
uint256 public bonusMultiplier = 40;
// Halving Divider
uint256 public constant HALVING_DIVIDER = 2;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorFarmer public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when MAC mining starts.
uint256 public startBlock;
// uint256 public blockInADay = 5760; // Assume 15s per block
uint256 public halvePeriod;
uint256 public lastHalveBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Halve(uint256 newBonusMultiplier, uint256 nextHalveBlockNumber, uint256 currentBlock);
constructor(
MacToken _mac,
address _devaddr,
uint256 _macPerBlock,
uint256 _startBlock,
uint256 _halvePeriod
) public {
mac = _mac;
devaddr = _devaddr;
macPerBlock = _macPerBlock;
startBlock = _startBlock;
halvePeriod = _halvePeriod;
lastHalveBlock = startBlock;
}
function doHalvingCheck(bool _withUpdate) public {
if (bonusMultiplier <= 1) {
return;
}
bool doHalve = block.number > lastHalveBlock.add(halvePeriod);
if (!doHalve) {
return;
}
bonusMultiplier = bonusMultiplier.div(HALVING_DIVIDER);
lastHalveBlock = block.number;
if (bonusMultiplier == 1) {
emit Halve(bonusMultiplier, 0, block.number);
} else {
emit Halve(bonusMultiplier, block.number + halvePeriod, block.number);
}
if (_withUpdate) {
massUpdatePools();
}
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accMacPerShare: 0
}));
}
// Update the given pool's MAC allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorFarmer _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return bonusMultiplier > 1 ? _to.sub(_from).mul(bonusMultiplier) : _to.sub(_from);
}
// View function to see pending MACs on frontend.
function pendingMac(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accMacPerShare = pool.accMacPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 macReward = multiplier.mul(macPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accMacPerShare = accMacPerShare.add(macReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accMacPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
doHalvingCheck(false);
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 macReward = multiplier.mul(macPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
mac.mint(devaddr, macReward.div(10));
mac.mint(address(this), macReward);
pool.accMacPerShare = pool.accMacPerShare.add(macReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterFarmer for MAC allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accMacPerShare).div(1e12).sub(user.rewardDebt);
safeMacTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accMacPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterFarmer.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accMacPerShare).div(1e12).sub(user.rewardDebt);
safeMacTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accMacPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe mac transfer function, just in case if rounding error causes pool to not have enough MACs.
function safeMacTransfer(address _to, uint256 _amount) internal {
uint256 macBal = mac.balanceOf(address(this));
if (_amount > macBal) {
mac.transfer(_to, macBal);
} else {
mac.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
|
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "MAC::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "MAC::delegateBySig: invalid nonce");
require(now <= expiry, "MAC::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 11,704,744 |
./partial_match/1/0xe91125f34fcEF2854A890DCf02b74Cb2DcbE377f/sources/SpaceToken.sol
|
Creates a new promo Person with the given name, with given _price and assignes it to an address.
|
function createPromoPerson(address _owner, string _name, uint256 _price) public onlyCOO {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
address personOwner = _owner;
if (personOwner == address(0)) {
personOwner = cooAddress;
}
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
_createPerson(_name, personOwner, _price);
}
| 2,592,399 |
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/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);
}
/**
* @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];
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title PauserRole
* @dev Pausers are responsible for pausing/unpausing transfers.
*/
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed token, address indexed account);
event PauserRemoved(address indexed token, address indexed account);
// Mapping from token to token pausers.
mapping(address => Roles.Role) private _pausers;
constructor () internal {}
modifier onlyPauser(address token) {
require(isPauser(token, msg.sender));
_;
}
function isPauser(address token, address account) public view returns (bool) {
return _pausers[token].has(account);
}
function addPauser(address token, address account) public onlyPauser(token) {
_addPauser(token, account);
}
function renouncePauser(address token) public {
_removePauser(token, msg.sender);
}
function _addPauser(address token, address account) internal {
_pausers[token].add(account);
emit PauserAdded(token, account);
}
function _removePauser(address token, address account) internal {
_pausers[token].remove(account);
emit PauserRemoved(token, account);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address indexed token, address account);
event Unpaused(address indexed token, address account);
// Mapping from token to token paused status.
mapping(address => bool) private _paused;
/**
* @return true if the contract is paused, false otherwise.
*/
function paused(address token) public view returns (bool) {
return _paused[token];
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused(address token) {
require(!_paused[token]);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused(address token) {
require(_paused[token]);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause(address token) public onlyPauser(token) whenNotPaused(token) {
_paused[token] = true;
emit Paused(token, msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause(address token) public onlyPauser(token) whenPaused(token) {
_paused[token] = false;
emit Unpaused(token, msg.sender);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title AllowlistAdminRole
* @dev AllowlistAdmins are responsible for assigning and removing Allowlisted accounts.
*/
contract AllowlistAdminRole {
using Roles for Roles.Role;
event AllowlistAdminAdded(address indexed token, address indexed account);
event AllowlistAdminRemoved(address indexed token, address indexed account);
// Mapping from token to token allowlist admins.
mapping(address => Roles.Role) private _allowlistAdmins;
constructor () internal {}
modifier onlyAllowlistAdmin(address token) {
require(isAllowlistAdmin(token, msg.sender));
_;
}
function isAllowlistAdmin(address token, address account) public view returns (bool) {
return _allowlistAdmins[token].has(account);
}
function addAllowlistAdmin(address token, address account) public onlyAllowlistAdmin(token) {
_addAllowlistAdmin(token, account);
}
function renounceAllowlistAdmin(address token) public {
_removeAllowlistAdmin(token, msg.sender);
}
function _addAllowlistAdmin(address token, address account) internal {
_allowlistAdmins[token].add(account);
emit AllowlistAdminAdded(token, account);
}
function _removeAllowlistAdmin(address token, address account) internal {
_allowlistAdmins[token].remove(account);
emit AllowlistAdminRemoved(token, account);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title AllowlistedRole
* @dev Allowlisted accounts have been forbidden by a AllowlistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are AllowlistAdmins (who can also remove
* it), and not Allowlisteds themselves.
*/
contract AllowlistedRole is AllowlistAdminRole {
using Roles for Roles.Role;
event AllowlistedAdded(address indexed token, address indexed account);
event AllowlistedRemoved(address indexed token, address indexed account);
// Mapping from token to token allowlisteds.
mapping(address => Roles.Role) private _allowlisteds;
modifier onlyNotAllowlisted(address token) {
require(!isAllowlisted(token, msg.sender));
_;
}
function isAllowlisted(address token, address account) public view returns (bool) {
return _allowlisteds[token].has(account);
}
function addAllowlisted(address token, address account) public onlyAllowlistAdmin(token) {
_addAllowlisted(token, account);
}
function removeAllowlisted(address token, address account) public onlyAllowlistAdmin(token) {
_removeAllowlisted(token, account);
}
function _addAllowlisted(address token, address account) internal {
_allowlisteds[token].add(account);
emit AllowlistedAdded(token, account);
}
function _removeAllowlisted(address token, address account) internal {
_allowlisteds[token].remove(account);
emit AllowlistedRemoved(token, account);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title BlocklistAdminRole
* @dev BlocklistAdmins are responsible for assigning and removing Blocklisted accounts.
*/
contract BlocklistAdminRole {
using Roles for Roles.Role;
event BlocklistAdminAdded(address indexed token, address indexed account);
event BlocklistAdminRemoved(address indexed token, address indexed account);
// Mapping from token to token blocklist admins.
mapping(address => Roles.Role) private _blocklistAdmins;
constructor () internal {}
modifier onlyBlocklistAdmin(address token) {
require(isBlocklistAdmin(token, msg.sender));
_;
}
function isBlocklistAdmin(address token, address account) public view returns (bool) {
return _blocklistAdmins[token].has(account);
}
function addBlocklistAdmin(address token, address account) public onlyBlocklistAdmin(token) {
_addBlocklistAdmin(token, account);
}
function renounceBlocklistAdmin(address token) public {
_removeBlocklistAdmin(token, msg.sender);
}
function _addBlocklistAdmin(address token, address account) internal {
_blocklistAdmins[token].add(account);
emit BlocklistAdminAdded(token, account);
}
function _removeBlocklistAdmin(address token, address account) internal {
_blocklistAdmins[token].remove(account);
emit BlocklistAdminRemoved(token, account);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title BlocklistedRole
* @dev Blocklisted accounts have been forbidden by a BlocklistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are BlocklistAdmins (who can also remove
* it), and not Blocklisteds themselves.
*/
contract BlocklistedRole is BlocklistAdminRole {
using Roles for Roles.Role;
event BlocklistedAdded(address indexed token, address indexed account);
event BlocklistedRemoved(address indexed token, address indexed account);
// Mapping from token to token blocklisteds.
mapping(address => Roles.Role) private _blocklisteds;
modifier onlyNotBlocklisted(address token) {
require(!isBlocklisted(token, msg.sender));
_;
}
function isBlocklisted(address token, address account) public view returns (bool) {
return _blocklisteds[token].has(account);
}
function addBlocklisted(address token, address account) public onlyBlocklistAdmin(token) {
_addBlocklisted(token, account);
}
function removeBlocklisted(address token, address account) public onlyBlocklistAdmin(token) {
_removeBlocklisted(token, account);
}
function _addBlocklisted(address token, address account) internal {
_blocklisteds[token].add(account);
emit BlocklistedAdded(token, account);
}
function _removeBlocklisted(address token, address account) internal {
_blocklisteds[token].remove(account);
emit BlocklistedRemoved(token, account);
}
}
contract ERC1820Registry {
function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external;
function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address);
function setManager(address _addr, address _newManager) external;
function getManager(address _addr) public view returns (address);
}
/// Base client to interact with the registry.
contract ERC1820Client {
ERC1820Registry constant ERC1820REGISTRY = ERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
function setInterfaceImplementation(string memory _interfaceLabel, address _implementation) internal {
bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel));
ERC1820REGISTRY.setInterfaceImplementer(address(this), interfaceHash, _implementation);
}
function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns(address) {
bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel));
return ERC1820REGISTRY.getInterfaceImplementer(addr, interfaceHash);
}
function delegateManagement(address _newManager) internal {
ERC1820REGISTRY.setManager(address(this), _newManager);
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
contract ERC1820Implementer {
bytes32 constant ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC"));
mapping(bytes32 => bool) internal _interfaceHashes;
function canImplementInterfaceForAddress(bytes32 interfaceHash, address /*addr*/) // Comments to avoid compilation warnings for unused variables.
external
view
returns(bytes32)
{
if(_interfaceHashes[interfaceHash]) {
return ERC1820_ACCEPT_MAGIC;
} else {
return "";
}
}
function _setInterface(string memory interfaceLabel) internal {
_interfaceHashes[keccak256(abi.encodePacked(interfaceLabel))] = true;
}
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400 security token standard
* @dev See https://github.com/SecurityTokenStandard/EIP-Spec/blob/master/eip/eip-1400.md
*/
interface IERC1400 /*is IERC20*/ { // Interfaces can currently not inherit interfaces, but IERC1400 shall include IERC20
// ****************** Document Management *******************
function getDocument(bytes32 name) external view returns (string memory, bytes32);
function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external;
// ******************* Token Information ********************
function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256);
function partitionsOf(address tokenHolder) external view returns (bytes32[] memory);
// *********************** Transfers ************************
function transferWithData(address to, uint256 value, bytes calldata data) external;
function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external;
// *************** Partition Token Transfers ****************
function transferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external returns (bytes32);
function operatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external returns (bytes32);
// ****************** Controller Operation ******************
function isControllable() external view returns (bool);
// function controllerTransfer(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external; // removed because same action can be achieved with "operatorTransferByPartition"
// function controllerRedeem(address tokenHolder, uint256 value, bytes calldata data, bytes calldata operatorData) external; // removed because same action can be achieved with "operatorRedeemByPartition"
// ****************** Operator Management *******************
function authorizeOperator(address operator) external;
function revokeOperator(address operator) external;
function authorizeOperatorByPartition(bytes32 partition, address operator) external;
function revokeOperatorByPartition(bytes32 partition, address operator) external;
// ****************** Operator Information ******************
function isOperator(address operator, address tokenHolder) external view returns (bool);
function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool);
// ********************* Token Issuance *********************
function isIssuable() external view returns (bool);
function issue(address tokenHolder, uint256 value, bytes calldata data) external;
function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external;
// ******************** Token Redemption ********************
function redeem(uint256 value, bytes calldata data) external;
function redeemFrom(address tokenHolder, uint256 value, bytes calldata data) external;
function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external;
function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external;
// ******************* Transfer Validity ********************
// We use different transfer validity functions because those described in the interface don't allow to verify the certificate's validity.
// Indeed, verifying the ecrtificate's validity requires to keeps the function's arguments in the exact same order as the transfer function.
//
// function canTransfer(address to, uint256 value, bytes calldata data) external view returns (byte, bytes32);
// function canTransferFrom(address from, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32);
// function canTransferByPartition(address from, address to, bytes32 partition, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32);
// ******************* Controller Events ********************
// We don't use this event as we don't use "controllerTransfer"
// event ControllerTransfer(
// address controller,
// address indexed from,
// address indexed to,
// uint256 value,
// bytes data,
// bytes operatorData
// );
//
// We don't use this event as we don't use "controllerRedeem"
// event ControllerRedemption(
// address controller,
// address indexed tokenHolder,
// uint256 value,
// bytes data,
// bytes operatorData
// );
// ******************** Document Events *********************
event Document(bytes32 indexed name, string uri, bytes32 documentHash);
// ******************** Transfer Events *********************
event TransferByPartition(
bytes32 indexed fromPartition,
address operator,
address indexed from,
address indexed to,
uint256 value,
bytes data,
bytes operatorData
);
event ChangedPartition(
bytes32 indexed fromPartition,
bytes32 indexed toPartition,
uint256 value
);
// ******************** Operator Events *********************
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
event AuthorizedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder);
event RevokedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder);
// ************** Issuance / Redemption Events **************
event Issued(address indexed operator, address indexed to, uint256 value, bytes data);
event Redeemed(address indexed operator, address indexed from, uint256 value, bytes data);
event IssuedByPartition(bytes32 indexed partition, address indexed operator, address indexed to, uint256 value, bytes data, bytes operatorData);
event RedeemedByPartition(bytes32 indexed partition, address indexed operator, address indexed from, uint256 value, bytes operatorData);
}
/**
* Reason codes - ERC-1066
*
* To improve the token holder experience, canTransfer MUST return a reason byte code
* on success or failure based on the ERC-1066 application-specific status codes specified below.
* An implementation can also return arbitrary data as a bytes32 to provide additional
* information not captured by the reason code.
*
* Code Reason
* 0x50 transfer failure
* 0x51 transfer success
* 0x52 insufficient balance
* 0x53 insufficient allowance
* 0x54 transfers halted (contract paused)
* 0x55 funds locked (lockup period)
* 0x56 invalid sender
* 0x57 invalid receiver
* 0x58 invalid operator (transfer agent)
* 0x59
* 0x5a
* 0x5b
* 0x5a
* 0x5b
* 0x5c
* 0x5d
* 0x5e
* 0x5f token meta or info
*
* These codes are being discussed at: https://ethereum-magicians.org/t/erc-1066-ethereum-status-codes-esc/283/24
*/
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @title IERC1400TokensValidator
* @dev ERC1400TokensValidator interface
*/
interface IERC1400TokensValidator {
function canValidate(
address token,
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external view returns(bool);
function tokensToValidate(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) external;
}
/*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
/**
* @notice Interface to the Minterrole contract
*/
interface IMinterRole {
function isMinter(address account) external view returns (bool);
}
contract ERC1400TokensValidator is IERC1400TokensValidator, Pausable, AllowlistedRole, BlocklistedRole, ERC1820Client, ERC1820Implementer {
using SafeMath for uint256;
string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator";
bytes4 constant internal ERC20_TRANSFER_FUNCTION_ID = bytes4(keccak256("transfer(address,uint256)"));
bytes4 constant internal ERC20_TRANSFERFROM_FUNCTION_ID = bytes4(keccak256("transferFrom(address,address,uint256)"));
// Mapping from token to allowlist activation status.
mapping(address => bool) internal _allowlistActivated;
// Mapping from token to blocklist activation status.
mapping(address => bool) internal _blocklistActivated;
// Mapping from token to partition granularity activation status.
mapping(address => bool) internal _granularityByPartitionActivated;
// Mapping from token to holds activation status.
mapping(address => bool) internal _holdsActivated;
// Mapping from token to self-holds activation status.
mapping(address => bool) internal _selfHoldsActivated;
// Mapping from token to token controllers.
mapping(address => address[]) internal _tokenControllers;
// Mapping from (token, operator) to token controller status.
mapping(address => mapping(address => bool)) internal _isTokenController;
enum HoldStatusCode {
Nonexistent,
Ordered,
Executed,
ExecutedAndKeptOpen,
ReleasedByNotary,
ReleasedByPayee,
ReleasedOnExpiration
}
struct Hold {
bytes32 partition;
address sender;
address recipient;
address notary;
uint256 value;
uint256 expiration;
bytes32 secretHash;
bytes32 secret;
HoldStatusCode status;
}
// Mapping from (token, partition) to partition granularity.
mapping(address => mapping(bytes32 => uint256)) internal _granularityByPartition;
// Mapping from (token, holdId) to hold.
mapping(address => mapping(bytes32 => Hold)) internal _holds;
// Mapping from (token, tokenHolder) to balance on hold.
mapping(address => mapping(address => uint256)) internal _heldBalance;
// Mapping from (token, tokenHolder, partition) to balance on hold of corresponding partition.
mapping(address => mapping(address => mapping(bytes32 => uint256))) internal _heldBalanceByPartition;
// Mapping from (token, partition) to global balance on hold of corresponding partition.
mapping(address => mapping(bytes32 => uint256)) internal _totalHeldBalanceByPartition;
// Total balance on hold.
mapping(address => uint256) internal _totalHeldBalance;
// Mapping from hold parameter's hash to hold's nonce.
mapping(bytes32 => uint256) internal _hashNonce;
// Mapping from (hash, nonce) to hold ID.
mapping(bytes32 => mapping(uint256 => bytes32)) internal _holdIds;
event HoldCreated(
address indexed token,
bytes32 indexed holdId,
bytes32 partition,
address sender,
address recipient,
address indexed notary,
uint256 value,
uint256 expiration,
bytes32 secretHash
);
event HoldReleased(address indexed token, bytes32 holdId, address indexed notary, HoldStatusCode status);
event HoldRenewed(address indexed token, bytes32 holdId, address indexed notary, uint256 oldExpiration, uint256 newExpiration);
event HoldExecuted(address indexed token, bytes32 holdId, address indexed notary, uint256 heldValue, uint256 transferredValue, bytes32 secret);
event HoldExecutedAndKeptOpen(address indexed token, bytes32 holdId, address indexed notary, uint256 heldValue, uint256 transferredValue, bytes32 secret);
/**
* @dev Modifier to verify if sender is a token controller.
*/
modifier onlyTokenController(address token) {
require(
msg.sender == token ||
msg.sender == Ownable(token).owner() ||
_isTokenController[token][msg.sender],
"Sender is not a token controller."
);
_;
}
/**
* @dev Modifier to verify if sender is a pauser.
*/
modifier onlyPauser(address token) {
require(
msg.sender == Ownable(token).owner() ||
_isTokenController[token][msg.sender] ||
isPauser(token, msg.sender),
"Sender is not a pauser"
);
_;
}
/**
* @dev Modifier to verify if sender is an allowlist admin.
*/
modifier onlyAllowlistAdmin(address token) {
require(
msg.sender == Ownable(token).owner() ||
_isTokenController[token][msg.sender] ||
isAllowlistAdmin(token, msg.sender),
"Sender is not an allowlist admin"
);
_;
}
/**
* @dev Modifier to verify if sender is a blocklist admin.
*/
modifier onlyBlocklistAdmin(address token) {
require(
msg.sender == Ownable(token).owner() ||
_isTokenController[token][msg.sender] ||
isBlocklistAdmin(token, msg.sender),
"Sender is not a blocklist admin"
);
_;
}
constructor() public {
ERC1820Implementer._setInterface(ERC1400_TOKENS_VALIDATOR);
}
/**
* @dev Get the list of token controllers for a given token.
* @return Setup of a given token.
*/
function retrieveTokenSetup(address token) external view returns (bool, bool, bool, bool, bool, address[] memory) {
return (
_allowlistActivated[token],
_blocklistActivated[token],
_granularityByPartitionActivated[token],
_holdsActivated[token],
_selfHoldsActivated[token],
_tokenControllers[token]
);
}
/**
* @dev Register token setup.
*/
function registerTokenSetup(
address token,
bool allowlistActivated,
bool blocklistActivated,
bool granularityByPartitionActivated,
bool holdsActivated,
bool selfHoldsActivated,
address[] calldata operators
) external onlyTokenController(token) {
_allowlistActivated[token] = allowlistActivated;
_blocklistActivated[token] = blocklistActivated;
_granularityByPartitionActivated[token] = granularityByPartitionActivated;
_holdsActivated[token] = holdsActivated;
_selfHoldsActivated[token] = selfHoldsActivated;
_setTokenControllers(token, operators);
}
/**
* @dev Set list of token controllers for a given token.
* @param token Token address.
* @param operators Operators addresses.
*/
function _setTokenControllers(address token, address[] memory operators) internal {
for (uint i = 0; i<_tokenControllers[token].length; i++){
_isTokenController[token][_tokenControllers[token][i]] = false;
}
for (uint j = 0; j<operators.length; j++){
_isTokenController[token][operators[j]] = true;
}
_tokenControllers[token] = operators;
}
/**
* @dev Verify if a token transfer can be executed or not, on the validator's perspective.
* @param token Address of the token.
* @param functionSig ID of the function that is called.
* @param partition Name of the partition (left empty for ERC20 transfer).
* @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).
* @return 'true' if the token transfer can be validated, 'false' if not.
*/
function canValidate(
address token,
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) // Comments to avoid compilation warnings for unused variables.
external
view
returns(bool)
{
(bool canValidateToken,) = _canValidate(token, functionSig, partition, operator, from, to, value, data, operatorData);
return canValidateToken;
}
/**
* @dev Function called by the token contract before executing a transfer.
* @param functionSig ID of the function that is called.
* @param partition Name of the partition (left empty for ERC20 transfer).
* @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).
* @return 'true' if the token transfer can be validated, 'false' if not.
*/
function tokensToValidate(
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes calldata data,
bytes calldata operatorData
) // Comments to avoid compilation warnings for unused variables.
external
{
(bool canValidateToken, bytes32 holdId) = _canValidate(msg.sender, functionSig, partition, operator, from, to, value, data, operatorData);
require(canValidateToken, "55"); // 0x55 funds locked (lockup period)
if (_holdsActivated[msg.sender] && holdId != "") {
Hold storage executableHold = _holds[msg.sender][holdId];
_setHoldToExecuted(
msg.sender,
executableHold,
holdId,
value,
executableHold.value,
""
);
}
}
/**
* @dev Verify if a token transfer can be executed or not, on the validator's perspective.
* @return 'true' if the token transfer can be validated, 'false' if not.
* @return hold ID in case a hold can be executed for the given parameters.
*/
function _canValidate(
address token,
bytes4 functionSig,
bytes32 partition,
address operator,
address from,
address to,
uint value,
bytes memory /*data*/,
bytes memory /*operatorData*/
) // Comments to avoid compilation warnings for unused variables.
internal
view
whenNotPaused(token)
returns(bool, bytes32)
{
if(_functionRequiresValidation(functionSig)) {
if(_allowlistActivated[token]) {
if(!isAllowlisted(token, from) || !isAllowlisted(token, to)) {
return (false, "");
}
}
if(_blocklistActivated[token]) {
if(isBlocklisted(token, from) || isBlocklisted(token, to)) {
return (false, "");
}
}
}
if(_granularityByPartitionActivated[token]) {
if(
_granularityByPartition[token][partition] > 0 &&
!_isMultiple(_granularityByPartition[token][partition], value)
) {
return (false, "");
}
}
if (_holdsActivated[token]) {
if(functionSig == ERC20_TRANSFERFROM_FUNCTION_ID) {
(,, bytes32 holdId) = _retrieveHoldHashNonceId(token, partition, operator, from, to, value);
Hold storage hold = _holds[token][holdId];
if (_holdCanBeExecutedAsNotary(hold, operator, value) && value <= IERC1400(token).balanceOfByPartition(partition, from)) {
return (true, holdId);
}
}
if(value > _spendableBalanceOfByPartition(token, partition, from)) {
return (false, "");
}
}
return (true, "");
}
/**
* @dev Get granularity for a given partition.
* @param token Address of the token.
* @param partition Name of the partition.
* @return Granularity of the partition.
*/
function granularityByPartition(address token, bytes32 partition) external view returns (uint256) {
return _granularityByPartition[token][partition];
}
/**
* @dev Set partition granularity
*/
function setGranularityByPartition(
address token,
bytes32 partition,
uint256 granularity
)
external
onlyTokenController(token)
{
_granularityByPartition[token][partition] = granularity;
}
/**
* @dev Create a new token pre-hold.
*/
function preHoldFor(
address token,
bytes32 holdId,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 timeToExpiration,
bytes32 secretHash
)
external
returns (bool)
{
return _createHold(
token,
holdId,
address(0),
recipient,
notary,
partition,
value,
_computeExpiration(timeToExpiration),
secretHash
);
}
/**
* @dev Create a new token pre-hold with expiration date.
*/
function preHoldForWithExpirationDate(
address token,
bytes32 holdId,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 expiration,
bytes32 secretHash
)
external
returns (bool)
{
_checkExpiration(expiration);
return _createHold(
token,
holdId,
address(0),
recipient,
notary,
partition,
value,
expiration,
secretHash
);
}
/**
* @dev Create a new token hold.
*/
function hold(
address token,
bytes32 holdId,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 timeToExpiration,
bytes32 secretHash
)
external
returns (bool)
{
return _createHold(
token,
holdId,
msg.sender,
recipient,
notary,
partition,
value,
_computeExpiration(timeToExpiration),
secretHash
);
}
/**
* @dev Create a new token hold on behalf of the token holder.
*/
function holdFrom(
address token,
bytes32 holdId,
address sender,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 timeToExpiration,
bytes32 secretHash
)
external
returns (bool)
{
require(sender != address(0), "Payer address must not be zero address");
return _createHold(
token,
holdId,
sender,
recipient,
notary,
partition,
value,
_computeExpiration(timeToExpiration),
secretHash
);
}
/**
* @dev Create a new token hold with expiration date.
*/
function holdWithExpirationDate(
address token,
bytes32 holdId,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 expiration,
bytes32 secretHash
)
external
returns (bool)
{
_checkExpiration(expiration);
return _createHold(
token,
holdId,
msg.sender,
recipient,
notary,
partition,
value,
expiration,
secretHash
);
}
/**
* @dev Create a new token hold with expiration date on behalf of the token holder.
*/
function holdFromWithExpirationDate(
address token,
bytes32 holdId,
address sender,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 expiration,
bytes32 secretHash
)
external
returns (bool)
{
_checkExpiration(expiration);
require(sender != address(0), "Payer address must not be zero address");
return _createHold(
token,
holdId,
sender,
recipient,
notary,
partition,
value,
expiration,
secretHash
);
}
/**
* @dev Create a new token hold.
*/
function _createHold(
address token,
bytes32 holdId,
address sender,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 expiration,
bytes32 secretHash
) internal returns (bool)
{
Hold storage newHold = _holds[token][holdId];
require(recipient != address(0), "Payee address must not be zero address");
require(value != 0, "Value must be greater than zero");
require(newHold.value == 0, "This holdId already exists");
require(notary != address(0), "Notary address must not be zero address");
if (sender == address(0)) { // pre-hold (tokens do not already exist)
require(
_canPreHold(token, msg.sender),
"The pre-hold can only be created by the minter"
);
} else { // post-hold (tokens already exist)
require(value <= _spendableBalanceOfByPartition(token, partition, sender), "Amount of the hold can't be greater than the spendable balance of the sender");
require(
_canPostHold(token, partition, msg.sender, sender),
"The hold can only be renewed by the issuer or the payer"
);
}
newHold.partition = partition;
newHold.sender = sender;
newHold.recipient = recipient;
newHold.notary = notary;
newHold.value = value;
newHold.expiration = expiration;
newHold.secretHash = secretHash;
newHold.status = HoldStatusCode.Ordered;
if(sender != address(0)) {
// In case tokens already exist, increase held balance
_increaseHeldBalance(token, newHold, holdId);
}
emit HoldCreated(
token,
holdId,
partition,
sender,
recipient,
notary,
value,
expiration,
secretHash
);
return true;
}
/**
* @dev Release token hold.
*/
function releaseHold(address token, bytes32 holdId) external returns (bool) {
return _releaseHold(token, holdId);
}
/**
* @dev Release token hold.
*/
function _releaseHold(address token, bytes32 holdId) internal returns (bool) {
Hold storage releasableHold = _holds[token][holdId];
require(
releasableHold.status == HoldStatusCode.Ordered || releasableHold.status == HoldStatusCode.ExecutedAndKeptOpen,
"A hold can only be released in status Ordered or ExecutedAndKeptOpen"
);
require(
_isExpired(releasableHold.expiration) ||
(msg.sender == releasableHold.notary) ||
(msg.sender == releasableHold.recipient),
"A not expired hold can only be released by the notary or the payee"
);
if (_isExpired(releasableHold.expiration)) {
releasableHold.status = HoldStatusCode.ReleasedOnExpiration;
} else {
if (releasableHold.notary == msg.sender) {
releasableHold.status = HoldStatusCode.ReleasedByNotary;
} else {
releasableHold.status = HoldStatusCode.ReleasedByPayee;
}
}
if(releasableHold.sender != address(0)) { // In case tokens already exist, decrease held balance
_decreaseHeldBalance(token, releasableHold, releasableHold.value);
}
emit HoldReleased(token, holdId, releasableHold.notary, releasableHold.status);
return true;
}
/**
* @dev Renew hold.
*/
function renewHold(address token, bytes32 holdId, uint256 timeToExpiration) external returns (bool) {
return _renewHold(token, holdId, _computeExpiration(timeToExpiration));
}
/**
* @dev Renew hold with expiration time.
*/
function renewHoldWithExpirationDate(address token, bytes32 holdId, uint256 expiration) external returns (bool) {
_checkExpiration(expiration);
return _renewHold(token, holdId, expiration);
}
/**
* @dev Renew hold.
*/
function _renewHold(address token, bytes32 holdId, uint256 expiration) internal returns (bool) {
Hold storage renewableHold = _holds[token][holdId];
require(
renewableHold.status == HoldStatusCode.Ordered
|| renewableHold.status == HoldStatusCode.ExecutedAndKeptOpen,
"A hold can only be renewed in status Ordered or ExecutedAndKeptOpen"
);
require(!_isExpired(renewableHold.expiration), "An expired hold can not be renewed");
if (renewableHold.sender == address(0)) { // pre-hold (tokens do not already exist)
require(
_canPreHold(token, msg.sender),
"The pre-hold can only be renewed by the minter"
);
} else { // post-hold (tokens already exist)
require(
_canPostHold(token, renewableHold.partition, msg.sender, renewableHold.sender),
"The hold can only be renewed by the issuer or the payer"
);
}
uint256 oldExpiration = renewableHold.expiration;
renewableHold.expiration = expiration;
emit HoldRenewed(
token,
holdId,
renewableHold.notary,
oldExpiration,
expiration
);
return true;
}
/**
* @dev Execute hold.
*/
function executeHold(address token, bytes32 holdId, uint256 value, bytes32 secret) external returns (bool) {
return _executeHold(
token,
holdId,
msg.sender,
value,
secret,
false
);
}
/**
* @dev Execute hold and keep open.
*/
function executeHoldAndKeepOpen(address token, bytes32 holdId, uint256 value, bytes32 secret) external returns (bool) {
return _executeHold(
token,
holdId,
msg.sender,
value,
secret,
true
);
}
/**
* @dev Execute hold.
*/
function _executeHold(
address token,
bytes32 holdId,
address operator,
uint256 value,
bytes32 secret,
bool keepOpenIfHoldHasBalance
) internal returns (bool)
{
Hold storage executableHold = _holds[token][holdId];
bool canExecuteHold;
if(secret != "" && _holdCanBeExecutedAsSecretHolder(executableHold, value, secret)) {
executableHold.secret = secret;
canExecuteHold = true;
} else if(_holdCanBeExecutedAsNotary(executableHold, operator, value)) {
canExecuteHold = true;
}
if(canExecuteHold) {
if (keepOpenIfHoldHasBalance && ((executableHold.value - value) > 0)) {
_setHoldToExecutedAndKeptOpen(
token,
executableHold,
holdId,
value,
value,
secret
);
} else {
_setHoldToExecuted(
token,
executableHold,
holdId,
value,
executableHold.value,
secret
);
}
if (executableHold.sender == address(0)) { // pre-hold (tokens do not already exist)
IERC1400(token).issueByPartition(executableHold.partition, executableHold.recipient, value, "");
} else { // post-hold (tokens already exist)
IERC1400(token).operatorTransferByPartition(executableHold.partition, executableHold.sender, executableHold.recipient, value, "", "");
}
} else {
revert("hold can not be executed");
}
}
/**
* @dev Set hold to executed.
*/
function _setHoldToExecuted(
address token,
Hold storage executableHold,
bytes32 holdId,
uint256 value,
uint256 heldBalanceDecrease,
bytes32 secret
) internal
{
if(executableHold.sender != address(0)) { // In case tokens already exist, decrease held balance
_decreaseHeldBalance(token, executableHold, heldBalanceDecrease);
}
executableHold.status = HoldStatusCode.Executed;
emit HoldExecuted(
token,
holdId,
executableHold.notary,
executableHold.value,
value,
secret
);
}
/**
* @dev Set hold to executed and kept open.
*/
function _setHoldToExecutedAndKeptOpen(
address token,
Hold storage executableHold,
bytes32 holdId,
uint256 value,
uint256 heldBalanceDecrease,
bytes32 secret
) internal
{
if(executableHold.sender != address(0)) { // In case tokens already exist, decrease held balance
_decreaseHeldBalance(token, executableHold, heldBalanceDecrease);
}
executableHold.status = HoldStatusCode.ExecutedAndKeptOpen;
executableHold.value = executableHold.value.sub(value);
emit HoldExecutedAndKeptOpen(
token,
holdId,
executableHold.notary,
executableHold.value,
value,
secret
);
}
/**
* @dev Increase held balance.
*/
function _increaseHeldBalance(address token, Hold storage executableHold, bytes32 holdId) private {
_heldBalance[token][executableHold.sender] = _heldBalance[token][executableHold.sender].add(executableHold.value);
_totalHeldBalance[token] = _totalHeldBalance[token].add(executableHold.value);
_heldBalanceByPartition[token][executableHold.sender][executableHold.partition] = _heldBalanceByPartition[token][executableHold.sender][executableHold.partition].add(executableHold.value);
_totalHeldBalanceByPartition[token][executableHold.partition] = _totalHeldBalanceByPartition[token][executableHold.partition].add(executableHold.value);
_increaseNonce(token, executableHold, holdId);
}
/**
* @dev Decrease held balance.
*/
function _decreaseHeldBalance(address token, Hold storage executableHold, uint256 value) private {
_heldBalance[token][executableHold.sender] = _heldBalance[token][executableHold.sender].sub(value);
_totalHeldBalance[token] = _totalHeldBalance[token].sub(value);
_heldBalanceByPartition[token][executableHold.sender][executableHold.partition] = _heldBalanceByPartition[token][executableHold.sender][executableHold.partition].sub(value);
_totalHeldBalanceByPartition[token][executableHold.partition] = _totalHeldBalanceByPartition[token][executableHold.partition].sub(value);
if(executableHold.status == HoldStatusCode.Ordered) {
_decreaseNonce(token, executableHold);
}
}
/**
* @dev Increase nonce.
*/
function _increaseNonce(address token, Hold storage executableHold, bytes32 holdId) private {
(bytes32 holdHash, uint256 nonce,) = _retrieveHoldHashNonceId(
token, executableHold.partition,
executableHold.notary,
executableHold.sender,
executableHold.recipient,
executableHold.value
);
_hashNonce[holdHash] = nonce.add(1);
_holdIds[holdHash][nonce.add(1)] = holdId;
}
/**
* @dev Decrease nonce.
*/
function _decreaseNonce(address token, Hold storage executableHold) private {
(bytes32 holdHash, uint256 nonce,) = _retrieveHoldHashNonceId(
token,
executableHold.partition,
executableHold.notary,
executableHold.sender,
executableHold.recipient,
executableHold.value
);
_holdIds[holdHash][nonce] = "";
_hashNonce[holdHash] = _hashNonce[holdHash].sub(1);
}
/**
* @dev Check secret.
*/
function _checkSecret(Hold storage executableHold, bytes32 secret) internal view returns (bool) {
if(executableHold.secretHash == sha256(abi.encodePacked(secret))) {
return true;
} else {
return false;
}
}
/**
* @dev Compute expiration time.
*/
function _computeExpiration(uint256 timeToExpiration) internal view returns (uint256) {
uint256 expiration = 0;
if (timeToExpiration != 0) {
expiration = now.add(timeToExpiration);
}
return expiration;
}
/**
* @dev Check expiration time.
*/
function _checkExpiration(uint256 expiration) private view {
require(expiration > now || expiration == 0, "Expiration date must be greater than block timestamp or zero");
}
/**
* @dev Check is expiration date is past.
*/
function _isExpired(uint256 expiration) internal view returns (bool) {
return expiration != 0 && (now >= expiration);
}
/**
* @dev Retrieve hold hash, nonce, and ID for given parameters
*/
function _retrieveHoldHashNonceId(address token, bytes32 partition, address notary, address sender, address recipient, uint value) internal view returns (bytes32, uint256, bytes32) {
// Pack and hash hold parameters
bytes32 holdHash = keccak256(abi.encodePacked(
token,
partition,
sender,
recipient,
notary,
value
));
uint256 nonce = _hashNonce[holdHash];
bytes32 holdId = _holdIds[holdHash][nonce];
return (holdHash, nonce, holdId);
}
/**
* @dev Check if hold can be executed
*/
function _holdCanBeExecuted(Hold storage executableHold, uint value) internal view returns (bool) {
if(!(executableHold.status == HoldStatusCode.Ordered || executableHold.status == HoldStatusCode.ExecutedAndKeptOpen)) {
return false; // A hold can only be executed in status Ordered or ExecutedAndKeptOpen
} else if(value == 0) {
return false; // Value must be greater than zero
} else if(_isExpired(executableHold.expiration)) {
return false; // The hold has already expired
} else if(value > executableHold.value) {
return false; // The value should be equal or less than the held amount
} else {
return true;
}
}
/**
* @dev Check if hold can be executed as secret holder
*/
function _holdCanBeExecutedAsSecretHolder(Hold storage executableHold, uint value, bytes32 secret) internal view returns (bool) {
if(
_checkSecret(executableHold, secret)
&& _holdCanBeExecuted(executableHold, value)) {
return true;
} else {
return false;
}
}
/**
* @dev Check if hold can be executed as notary
*/
function _holdCanBeExecutedAsNotary(Hold storage executableHold, address operator, uint value) internal view returns (bool) {
if(
executableHold.notary == operator
&& _holdCanBeExecuted(executableHold, value)) {
return true;
} else {
return false;
}
}
/**
* @dev Retrieve hold data.
*/
function retrieveHoldData(address token, bytes32 holdId) external view returns (
bytes32 partition,
address sender,
address recipient,
address notary,
uint256 value,
uint256 expiration,
bytes32 secretHash,
bytes32 secret,
HoldStatusCode status)
{
Hold storage retrievedHold = _holds[token][holdId];
return (
retrievedHold.partition,
retrievedHold.sender,
retrievedHold.recipient,
retrievedHold.notary,
retrievedHold.value,
retrievedHold.expiration,
retrievedHold.secretHash,
retrievedHold.secret,
retrievedHold.status
);
}
/**
* @dev Total supply on hold.
*/
function totalSupplyOnHold(address token) external view returns (uint256) {
return _totalHeldBalance[token];
}
/**
* @dev Total supply on hold for a specific partition.
*/
function totalSupplyOnHoldByPartition(address token, bytes32 partition) external view returns (uint256) {
return _totalHeldBalanceByPartition[token][partition];
}
/**
* @dev Get balance on hold of a tokenholder.
*/
function balanceOnHold(address token, address account) external view returns (uint256) {
return _heldBalance[token][account];
}
/**
* @dev Get balance on hold of a tokenholder for a specific partition.
*/
function balanceOnHoldByPartition(address token, bytes32 partition, address account) external view returns (uint256) {
return _heldBalanceByPartition[token][account][partition];
}
/**
* @dev Get spendable balance of a tokenholder.
*/
function spendableBalanceOf(address token, address account) external view returns (uint256) {
return _spendableBalanceOf(token, account);
}
/**
* @dev Get spendable balance of a tokenholder for a specific partition.
*/
function spendableBalanceOfByPartition(address token, bytes32 partition, address account) external view returns (uint256) {
return _spendableBalanceOfByPartition(token, partition, account);
}
/**
* @dev Get spendable balance of a tokenholder.
*/
function _spendableBalanceOf(address token, address account) internal view returns (uint256) {
return IERC20(token).balanceOf(account) - _heldBalance[token][account];
}
/**
* @dev Get spendable balance of a tokenholder for a specific partition.
*/
function _spendableBalanceOfByPartition(address token, bytes32 partition, address account) internal view returns (uint256) {
return IERC1400(token).balanceOfByPartition(partition, account) - _heldBalanceByPartition[token][account][partition];
}
/************************** TOKEN CONTROLLERS *******************************/
/**
* @dev Check if operator can create pre-holds.
* @return 'true' if the operator can create pre-holds, 'false' if not.
*/
function _canPreHold(address token, address operator) internal view returns(bool) {
return IMinterRole(token).isMinter(operator);
}
/**
* @dev Check if operator can create/update holds.
* @return 'true' if the operator can create/update holds, 'false' if not.
*/
function _canPostHold(address token, bytes32 partition, address operator, address sender) internal view returns(bool) {
if (_selfHoldsActivated[token]) {
return IERC1400(token).isOperatorForPartition(partition, operator, sender);
} else {
return _isTokenController[token][operator];
}
}
/**
* @dev Check if validator is activated for the function called in the smart contract.
* @param functionSig ID of the function that is called.
* @return 'true' if the function requires validation, 'false' if not.
*/
function _functionRequiresValidation(bytes4 functionSig) internal pure returns(bool) {
if(_areEqual(functionSig, ERC20_TRANSFER_FUNCTION_ID) || _areEqual(functionSig, ERC20_TRANSFERFROM_FUNCTION_ID)) {
return true;
} else {
return false;
}
}
/**
* @dev Check if 2 variables of type bytes4 are identical.
* @return 'true' if 2 variables are identical, 'false' if not.
*/
function _areEqual(bytes4 a, bytes4 b) internal pure returns(bool) {
for (uint256 i = 0; i < a.length; i++) {
if(a[i] != b[i]) {
return false;
}
}
return true;
}
/**
* @dev Check if 'value' is multiple of 'granularity'.
* @param granularity The granularity that want's to be checked.
* @param value The quantity that want's to be checked.
* @return 'true' if 'value' is a multiple of 'granularity'.
*/
function _isMultiple(uint256 granularity, uint256 value) internal pure returns(bool) {
return(value.div(granularity).mul(granularity) == value);
}
}
|
Get balance on hold of a tokenholder./
|
function balanceOnHold(address token, address account) external view returns (uint256) {
return _heldBalance[token][account];
}
| 1,722,092 |
/**
* MIT License
*
* Copyright (c) 2019 eToroX Labs
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.4.24;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./Storage.sol";
/**
* @title Internal implementation of ERC20 functionality with support
* for a separate storage contract
*/
contract ERC20 {
using SafeMath for uint256;
Storage private externalStorage;
string private name_;
string private symbol_;
uint8 private decimals_;
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/**
* @dev Constructor
* @param name The ERC20 detailed token name
* @param symbol The ERC20 detailed symbol name
* @param decimals Determines the number of decimals of this token
* @param _externalStorage The external storage contract.
* Should be zero address if shouldCreateStorage is true.
* @param initialDeployment Defines whether it should
* create a new external storage. Should be false if
* externalERC20Storage is defined.
*/
constructor(
string name,
string symbol,
uint8 decimals,
Storage _externalStorage,
bool initialDeployment
)
public
{
require(
(_externalStorage != address(0) && (!initialDeployment)) ||
(_externalStorage == address(0) && initialDeployment),
"Cannot both create external storage and use the provided one.");
name_ = name;
symbol_ = symbol;
decimals_ = decimals;
if (initialDeployment) {
externalStorage = new Storage(msg.sender, this);
} else {
externalStorage = _externalStorage;
}
}
/**
* @return The storage used by this contract
*/
function getExternalStorage() public view returns(Storage) {
return externalStorage;
}
/**
* @return the name of the token.
*/
function _name() internal view returns(string) {
return name_;
}
/**
* @return the symbol of the token.
*/
function _symbol() internal view returns(string) {
return symbol_;
}
/**
* @return the number of decimals of the token.
*/
function _decimals() internal view returns(uint8) {
return decimals_;
}
/**
* @dev Total number of tokens in existence
*/
function _totalSupply() internal view returns (uint256) {
return externalStorage.getTotalSupply();
}
/**
* @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) internal view returns (uint256) {
return externalStorage.getBalance(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)
internal
view
returns (uint256)
{
return externalStorage.getAllowed(owner, spender);
}
/**
* @dev Transfer token for a specified addresses
* @param originSender The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address originSender, address to, uint256 value)
internal
returns (bool)
{
require(to != address(0));
externalStorage.decreaseBalance(originSender, value);
externalStorage.increaseBalance(to, value);
emit Transfer(originSender, 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 originSender the original transaction sender
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function _approve(address originSender, address spender, uint256 value)
internal
returns (bool)
{
require(spender != address(0));
externalStorage.setAllowed(originSender, spender, value);
emit Approval(originSender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param originSender the original transaction sender
* @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 originSender,
address from,
address to,
uint256 value
)
internal
returns (bool)
{
externalStorage.decreaseAllowed(from, originSender, value);
_transfer(from, to, value);
emit Approval(
from,
originSender,
externalStorage.getAllowed(from, originSender)
);
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
* @param originSender the original transaction sender
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function _increaseAllowance(
address originSender,
address spender,
uint256 addedValue
)
internal
returns (bool)
{
require(spender != address(0));
externalStorage.increaseAllowed(originSender, spender, addedValue);
emit Approval(
originSender, spender,
externalStorage.getAllowed(originSender, 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 originSender the original transaction sender
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function _decreaseAllowance(
address originSender,
address spender,
uint256 subtractedValue
)
internal
returns (bool)
{
require(spender != address(0));
externalStorage.decreaseAllowed(originSender,
spender,
subtractedValue);
emit Approval(
originSender, spender,
externalStorage.getAllowed(originSender, spender)
);
return true;
}
/**
* @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 returns (bool)
{
require(account != 0);
externalStorage.setTotalSupply(
externalStorage.getTotalSupply().add(value));
externalStorage.increaseBalance(account, value);
emit Transfer(address(0), account, value);
return true;
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param originSender The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address originSender, uint256 value) internal returns (bool)
{
require(originSender != 0);
externalStorage.setTotalSupply(
externalStorage.getTotalSupply().sub(value));
externalStorage.decreaseBalance(originSender, value);
emit Transfer(originSender, address(0), value);
return true;
}
/**
* @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.
* @param originSender the original transaction sender
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address originSender, address account, uint256 value)
internal
returns (bool)
{
require(value <= externalStorage.getAllowed(account, originSender));
externalStorage.decreaseAllowed(account, originSender, value);
_burn(account, value);
emit Approval(account, originSender,
externalStorage.getAllowed(account, originSender));
return true;
}
}
|
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. originSender the original transaction sender account The account whose tokens will be burnt. value The amount that will be burnt./
|
function _burnFrom(address originSender, address account, uint256 value)
internal
returns (bool)
{
require(value <= externalStorage.getAllowed(account, originSender));
externalStorage.decreaseAllowed(account, originSender, value);
_burn(account, value);
emit Approval(account, originSender,
externalStorage.getAllowed(account, originSender));
return true;
}
| 12,899,639 |
./partial_match/56/0x79Ed648f0Fb424Ec37897DF87B9ee80cca65B230/sources/ProofOfApes.sol
|
Retrieve the dividends owned by the caller. If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. The reason for this, is that in the frontend, we will want to get the total divs (global + ref) But in the internal calculations, we want them separate./
|
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return
_includeReferralBonus
? dividendsOf(_customerAddress) + referralBalance_[_customerAddress]
: dividendsOf(_customerAddress);
}
| 11,213,885 |
/**
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
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;
}
}
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 Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface 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);
}
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);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() 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);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract Rhapsody is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Rhapsody", "Rhapsody") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 5;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 5;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 5;
uint256 _sellDevFee = 3;
uint256 _earlySellLiquidityFee = 15;
uint256 _earlySellMarketingFee = 5;
uint256 _earlySellDevFee = 0
; uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 20 / 1000; // 2% maxWallet
swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
launchedAt = block.number;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
// anti bot logic
if (block.number <= (launchedAt + 3) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function Chire(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
}
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("Rhapsody", "Rhapsody") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 5;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 5;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 5;
uint256 _sellDevFee = 3;
uint256 _earlySellLiquidityFee = 15;
uint256 _earlySellMarketingFee = 5;
uint256 _earlySellDevFee = 0
; uint256 totalSupply = 1 * 1e12 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 10,217,794 |
// contracts/Crowns.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.7;
import "./../openzeppelin/contracts/access/Ownable.sol";
import "./../openzeppelin/contracts/GSN/Context.sol";
import "./../openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./../openzeppelin/contracts/math/SafeMath.sol";
import "./../openzeppelin/contracts/utils/Address.sol";
/// @title Official token of the Seascape ecosystem.
/// @author Medet Ahmetson
/// @notice Crowns (CWS) is an ERC-20 token with a PayWave feature.
/// PayWave is a distribution of spent tokens among all current token holders.
/// In order to appear in balance, the paywaved tokens need
/// to be claimed by users by triggering any transaction in the ERC-20 contract.
/// @dev Implementation of the {IERC20} interface.
contract CrownsToken is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
struct Account {
uint256 balance;
uint256 lastPayWave;
}
mapping (address => Account) private _accounts;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private constant _name = "Crowns";
string private constant _symbol = "CWS";
uint8 private immutable _decimals = 18;
uint256 private constant MIN_SPEND = 10 ** 6;
uint256 private constant SCALER = 10 ** 18;
/// @notice Total amount of tokens that have yet to be transferred to token holders as part of the PayWave.
/// @dev Used Variable tracking unclaimed PayWave token amounts.
uint256 public unclaimedPayWave = 0;
/// @notice Amount of tokens spent by users that have not been paywaved yet.
/// @dev Calling the payWave function will move the amount to {totalPayWave}
uint256 public unconfirmedPayWave = 0;
/// @notice Total amount of tokens that were paywaved overall.
/// @dev Total paywaved tokens amount that is always increasing.
uint256 public totalPayWave = 0;
/**
* @dev Emitted when `spent` tokens are moved
* from `unconfirmedPayWave` to `totalPayWave`.
*/
event PayWave(
uint256 spent,
uint256 totalPayWave
);
/**
* @dev Sets the {name} and {symbol} of token.
* Initializes {decimals} with a default value of 18.
* Mints all tokens.
* Transfers ownership to another account. So, the token creator will not be counted as an owner.
*/
constructor () public {
address gameIncentivesHolder = 0x94E169Be9037561aC37D8bb3471c7e35B81708A7;
address liquidityHolder = 0xf409fDF4069c825656ba3e1f931FCde8525F1bEE;
address teamHolder = 0x2Ff42929f444e496D7e856591764E00ee13b7077;
address investHolder = 0x2cfca4ccd9ef6d9420ae1ff26306d179DABAEdC2;
address communityHolder = 0x2C25ba4DB75D43e655647F24fB0cB2e896116dbD;
address newOwner = 0xbfdadB9a06C90B6625aF3C6DAc0Bb7f56a852886;
// 5 million tokens
uint256 gameIncentives = 5e6 * SCALER;
// 1,5 million tokens
uint256 reserve = 15e5 * SCALER; // reserve for the next 5 years.
// 1 million tokens
uint256 community = 1e6 * SCALER;
uint256 team = 1e6 * SCALER;
uint256 investment = 1e6 * SCALER;
// 500,000 tokens
uint256 liquidity = 5e5 * SCALER;
_mint(gameIncentivesHolder, gameIncentives);
_mint(liquidityHolder, liquidity);
_mint(teamHolder, team);
_mint(investHolder, investment);
_mint(communityHolder, community);
_mint(newOwner, reserve);
transferOwnership(newOwner);
}
/**
* @notice Return amount of tokens that {account} gets during the PayWave
* @dev Used both internally and externally to calculate the PayWave amount
* @param account is an address of token holder to calculate for
* @return amount of tokens that player could get
*/
function payWaveOwing (address account) public view returns(uint256) {
Account memory _account = _accounts[account];
uint256 newPayWave = totalPayWave.sub(_account.lastPayWave);
uint256 proportion = _account.balance.mul(newPayWave);
// The PayWave is not a part of total supply, since it was moved out of balances
uint256 supply = _totalSupply.sub(newPayWave);
// PayWave owed proportional to current balance of the account.
// The decimal factor is used to avoid floating issue.
uint256 payWave = proportion.div(supply);
return payWave;
}
/**
* @dev Called before any edit of {account} balance.
* Modifier moves the belonging PayWave amount to its balance.
* @param account is an address of Token holder.
*/
modifier updateAccount(address account) {
uint256 owing = payWaveOwing(account);
_accounts[account].lastPayWave = totalPayWave;
if (owing > 0) {
_accounts[account].balance = _accounts[account].balance.add(owing);
unclaimedPayWave = unclaimedPayWave.sub(owing);
emit Transfer(
address(0),
account,
owing
);
}
_;
}
/**
* @dev Returns the name of the token.
*/
function name() public pure returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public pure 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`).
*
* 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 Returns the amount of tokens in existence.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) public view override returns (uint256) {
return _getBalance(account);
}
/**
* @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) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @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) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @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) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @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) 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 updateAccount(sender) updateAccount(recipient) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Can not send 0 token");
require(_getBalance(sender) >= amount, "ERC20: Not enough token to send");
_beforeTokenTransfer(sender, recipient, amount);
_accounts[sender].balance = _accounts[sender].balance.sub(amount);
_accounts[recipient].balance = _accounts[recipient].balance.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);
_accounts[account].balance = _accounts[account].balance.add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Moves `amount` tokens from `account` to {unconfirmedPayWave} without reducing the
* total supply. Will be paywaved among token holders.
*
* 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 updateAccount(account) virtual {
require(account != address(0), "ERC20: burn from the zero address");
require(_getBalance(account) >= amount, "ERC20: Not enough token to burn");
_beforeTokenTransfer(account, address(0), amount);
_accounts[account].balance = _accounts[account].balance.sub(amount);
unconfirmedPayWave = unconfirmedPayWave.add(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 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 { }
/**
* @notice Spend some token from caller's balance in the game.
* @dev Moves `amount` of token from caller to `unconfirmedPayWave`.
* @param amount Amount of token used to spend
*/
function spend(uint256 amount) public returns(bool) {
require(amount > MIN_SPEND, "Crowns: trying to spend less than expected");
require(_getBalance(msg.sender) >= amount, "Crowns: Not enough balance");
_burn(msg.sender, amount);
return true;
}
function spendFrom(address sender, uint256 amount) public returns(bool) {
require(amount > MIN_SPEND, "Crowns: trying to spend less than expected");
require(_getBalance(sender) >= amount, "Crowns: not enough balance");
_burn(sender, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @notice Return the PayWave amount, when `account` balance was updated.
*/
function getLastPayWave(address account) public view returns (uint256) {
return _accounts[account].lastPayWave;
}
/**
* @dev Returns actual balance of account as a sum of owned divends and current balance.
* @param account Address of Token holder.
* @return Token amount
*/
function _getBalance(address account) private view returns (uint256) {
uint256 balance = _accounts[account].balance;
if (balance == 0) {
return 0;
}
uint256 owing = payWaveOwing(account);
return balance.add(owing);
}
/**
* @notice Pay Wave is a unique feature of Crowns (CWS) token. It redistributes tokens spenth within game among all token holders.
* @dev Moves tokens from {unconfirmedPayWave} to {totalPayWave}.
* Any account balance related functions will use {totalPayWave} to calculate the dividend shares for each account.
*
* Emits a {PayWave} event.
*/
function payWave() public onlyOwner() returns (bool) {
totalPayWave = totalPayWave.add(unconfirmedPayWave);
unclaimedPayWave = unclaimedPayWave.add(unconfirmedPayWave);
uint256 payWaved = unconfirmedPayWave;
unconfirmedPayWave = 0;
emit PayWave (
payWaved,
totalPayWave
);
return true;
}
}
|
Return amount of tokens that {account} gets during the PayWave Used both internally and externally to calculate the PayWave amount account is an address of token holder to calculate for return amount of tokens that player could get/ The PayWave is not a part of total supply, since it was moved out of balances PayWave owed proportional to current balance of the account. The decimal factor is used to avoid floating issue.
|
function payWaveOwing (address account) public view returns(uint256) {
Account memory _account = _accounts[account];
uint256 newPayWave = totalPayWave.sub(_account.lastPayWave);
uint256 proportion = _account.balance.mul(newPayWave);
uint256 supply = _totalSupply.sub(newPayWave);
uint256 payWave = proportion.div(supply);
return payWave;
}
| 14,086,719 |
/**
*Submitted for verification at Etherscan.io on 2021-09-30
*/
// SPDX-License-Identifier: AGPLv3
pragma solidity 0.8.4;
interface IVault {
function withdraw(uint256 amount) external;
function withdraw(uint256 amount, address recipient) external;
function withdrawByStrategyOrder(
uint256 amount,
address recipient,
bool reversed
) external;
function withdrawByStrategyIndex(
uint256 amount,
address recipient,
uint256 strategyIndex
) external;
function deposit(uint256 amount) external;
function setStrategyDebtRatio(uint256[] calldata strategyRetios) external;
function totalAssets() external view returns (uint256);
function getStrategiesLength() external view returns (uint256);
function strategyHarvestTrigger(uint256 index, uint256 callCost) external view returns (bool);
function strategyHarvest(uint256 index) external returns (bool);
function getStrategyAssets(uint256 index) external view returns (uint256);
function token() external view returns (address);
function vault() external view returns (address);
function investTrigger() external view returns (bool);
function invest() external;
}
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() {
_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);
}
}
contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
event LogAddToWhitelist(address indexed user);
event LogRemoveFromWhitelist(address indexed user);
modifier onlyWhitelist() {
require(whitelist[msg.sender], "only whitelist");
_;
}
function addToWhitelist(address user) external onlyOwner {
require(user != address(0), "WhiteList: 0x");
whitelist[user] = true;
emit LogAddToWhitelist(user);
}
function removeFromWhitelist(address user) external onlyOwner {
require(user != address(0), "WhiteList: 0x");
whitelist[user] = false;
emit LogRemoveFromWhitelist(user);
}
}
interface ICurveMetaPool {
function coins(uint256 i) external view returns (address);
function get_virtual_price() external view returns (uint256);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
function calc_token_amount(uint256[2] calldata inAmounts, bool deposit) external view returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function add_liquidity(uint256[2] calldata uamounts, uint256 min_mint_amount) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_uamount
) external;
}
interface IERC20Detailed {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
/**
* @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);
}
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
struct StrategyParams {
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
interface VaultAPI {
function decimals() external view returns (uint256);
function token() external view returns (address);
function vaultAdapter() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
function governance() external view returns (address);
}
/**
* This interface is here for the keeper bot to use.
*/
interface StrategyAPI {
function name() external view returns (string memory);
function vault() external view returns (address);
function want() external view returns (address);
function keeper() external view returns (address);
function isActive() external view returns (bool);
function estimatedTotalAssets() external view returns (uint256);
function expectedReturn() external view returns (uint256);
function tendTrigger(uint256 callCost) external view returns (bool);
function tend() external;
function harvestTrigger(uint256 callCost) external view returns (bool);
function harvest() external;
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
}
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeERC20 for IERC20;
VaultAPI public vault;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == keeper || msg.sender == owner(), "!authorized");
_;
}
modifier onlyOwner() {
require(msg.sender == owner(), "!authorized");
_;
}
constructor(address _vault) {
_initialize(_vault, msg.sender, msg.sender);
}
function name() external view virtual returns (string memory);
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, type(uint256).max); // Give Vault unlimited access (might save gas)
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
}
function setKeeper(address _keeper) external onlyOwner {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* Resolve owner address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function owner() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to owner to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded)
internal
virtual
returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public view virtual returns (bool);
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
*/
function tend() external onlyAuthorized {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold`
* -controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public view virtual returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp - params.lastReport < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp - params.lastReport >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total + debtThreshold < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total - params.totalDebt; // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor * callCost < credit + profit);
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external {
require(msg.sender == vault.vaultAdapter(), 'harvest: Call from vault');
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(
totalAssets > debtOutstanding ? totalAssets : debtOutstanding
);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment - debtOutstanding;
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by owner or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `owner()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by owner.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyOwner {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++)
require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(owner(), IERC20(_token).balanceOf(address(this)));
}
}
/// @notice Yearn V2 vault interface
interface V2YVault {
function deposit(uint256 _amount) external;
function deposit() external;
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw() external returns (uint256);
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function pricePerShare() external view returns (uint256);
function token() external view returns (address);
}
library Math {
/// @notice Returns the largest of two numbers
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/// @notice Returns the smallest of two numbers
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/// @notice 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);
}
}
/// @notice Yearn curve Metapool strategy
/// Deposit stablecoins into Curve metapool - deposit received metapool tokens
/// to Yearn vault. Harvest only repays debts and pull available credit from vault.
/// This strategy can migrate between metapools and yearn vaults, and requires that
/// a new metapool and yearn vault get set and tend run. Theres a 0.5% withdrawal fee on this strategy,
/// this means that there should be a 0.5% buffer on assets before migrating in order,
/// for this strategy not to generate any loss.
/// ########################################
/// Strategy breakdown
/// ########################################
///
/// Want: 3Crv
/// Additional tokens: MetaPoolLP token (Curve), YMetaPoolVault token (yearn)
/// Exposures:
/// Protocol: Curve, Yearn, +1 stablecoin from metapool
/// stablecoins: DAI, USDC, USDT +1 stablecoin from metapool
/// Debt ratio set to 100% - should be only strategy in curveVault
///
/// Strategy logic:
/// Vault => Loan out 3Crv into strategy
/// strategy => invest 3Crv into target Curve meta pool
/// <= get metapool tokens (MLP) in return
/// strategy => invest MLP into yearn YMetaPoolVault
/// <= get Yshares in return
///
/// Harvest: Report back gains/losses to vault:
/// - do not withdraw any assets from Yearn/metapool
/// - do pull and invest any new 3crv available in vault
///
/// Migrate metapool: Move assets from one metapool to another:
/// - Set new target metapool/Yearn vault
/// - Ensure that current gains cover withdrawal fee (Yearn)
/// - Strategy withdraw assetse down to 3Crv tokens and
/// redeploys into new metapool/yearn vault
///
/// Tend: Withdraw available assets from yearn without getting hit by a fee
/// Used to redistribute 3Crv tokens into stablecoins
/// - see lifeguards, distributeCurveVault function
contract StableYearnXPool is BaseStrategy {
using SafeERC20 for IERC20;
IERC20 public lpToken; // Meta lp token (MLP)
// Default Curve metapool
address public curve = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
// Default yearn vault
V2YVault public yVault = V2YVault(address(0x84E13785B5a27879921D6F685f041421C7F482dA));
// Index of 3crv token in metapool
int128 wantIndex = 1;
// Number of tokens in metapool (+1 Stablecoin, 3Crv)
uint256 constant metaPool = 2;
uint256 constant PERCENTAGE_DECIMAL_FACTOR = 10000;
uint256 public decimals = 18;
int256 public difference = 0;
// Curve meta pool to migrate to
address public prepCurve = address(0);
// Yearn vault to migrate to
address public prepYVault = address(0);
event LogNewMigration(address indexed yVault, address indexed curve, address lpToken);
event LogNewMigrationPreperation(address indexed yVault, address indexed curve);
event LogForceMigration(bool status);
event LogMigrationCost(int256 cost);
constructor(address _vault) public BaseStrategy(_vault) {
profitFactor = 1000;
debtThreshold = 1_000_000 * 1e18;
lpToken = want;
}
/// @notice Set migration targets
/// @param _yVault Target Yearn vault
/// @param _curve Target Curve meta pool
function setMetaPool(address _yVault, address _curve) external onlyOwner {
prepYVault = _yVault;
prepCurve = _curve;
emit LogNewMigrationPreperation(_yVault, _curve);
}
function name() external view override returns (string memory) {
return "StrategyCurveXPool";
}
function resetDifference() external onlyOwner {
difference = 0;
}
/// @notice Get the total assets of this strategy.
/// This method is only used to pull out debt if debt ratio has changed.
/// @return Total assets in want this strategy has invested into underlying vault
function estimatedTotalAssets() public view override returns (uint256) {
(uint256 estimatedAssets, ) = _estimatedTotalAssets(true);
return estimatedAssets;
}
/// @notice Expected returns from strategy (gains from pool swaps)
function expectedReturn() public view returns (uint256) {
return _expectedReturn();
}
function _expectedReturn() private view returns (uint256) {
(uint256 estimatedAssets, ) = _estimatedTotalAssets(true);
uint256 debt = vault.strategies(address(this)).totalDebt;
if (debt > estimatedAssets) {
return 0;
} else {
return estimatedAssets - debt;
}
}
/// @notice This strategy doesn't realize profit outside of APY from the vault.
/// This method is only used to pull out debt if debt ratio has changed.
/// @param _debtOutstanding Debt to pay back
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
uint256 lentAssets = 0;
_debtPayment = _debtOutstanding;
address _prepCurve = prepCurve;
address _prepYVault = prepYVault;
uint256 looseAssets;
if (_prepCurve != address(0) && _prepYVault != address(0)){
migratePool(_prepCurve, _prepYVault);
}
(lentAssets, looseAssets) = _estimatedTotalAssets(false);
uint256 debt = vault.strategies(address(this)).totalDebt;
if (lentAssets - looseAssets == 0) {
_debtPayment = Math.min(looseAssets, _debtPayment);
return (_profit, _loss, _debtPayment);
}
if (lentAssets > debt) {
_profit = lentAssets - debt;
uint256 amountToFree = _profit + (_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
// Withdraw what we can withdraw
uint256 newLoose = _withdrawSome(amountToFree, looseAssets);
// If we don't have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
if (_debtPayment == debt) {
_withdrawSome(debt, looseAssets);
_debtPayment = want.balanceOf(address(this));
if (_debtPayment > debt) {
_profit = _debtPayment - debt;
} else {
_loss = debt - _debtPayment;
}
} else {
_loss = debt - lentAssets;
uint256 amountToFree = _debtPayment;
if (amountToFree > 0 && looseAssets < amountToFree) {
// Withdraw what we can withdraw
_debtPayment = _withdrawSome(amountToFree, looseAssets);
}
}
}
}
/// @notice Withdraw amount from yVault/pool
/// @param _amountToFree Expected amount needed
/// @param _loose want balance of contract
function _withdrawSome(uint256 _amountToFree, uint256 _loose) internal returns (uint256) {
uint256 _amount = _amountToFree - _loose;
uint256 yBalance = yVault.balanceOf(address(this));
uint256 lpBalance = lpToken.balanceOf(address(this));
if (yBalance > 0 ) {
// yVault calc are not precise, better to pull out more than needed
uint256 _amount_buffered = _amount * (PERCENTAGE_DECIMAL_FACTOR + 500) / PERCENTAGE_DECIMAL_FACTOR;
uint256 amountInYtokens = convertFromUnderlying(_amount_buffered, decimals, wantIndex);
if (amountInYtokens > yBalance) {
// Can't withdraw more than we own
amountInYtokens = yBalance;
}
uint256 yValue = yVault.withdraw(amountInYtokens);
lpBalance += yValue;
}
ICurveMetaPool _curve = ICurveMetaPool(curve);
uint256 tokenAmount = _curve.calc_withdraw_one_coin(lpBalance, wantIndex);
uint256 minAmount = tokenAmount - (tokenAmount * (9995) / (10000));
_curve.remove_liquidity_one_coin(lpBalance, wantIndex, minAmount);
return Math.min(_amountToFree, want.balanceOf(address(this)));
}
/// @notice Used when emergency stop has been called to empty out strategy
/// @param _amountNeeded Expected amount to withdraw
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 looseAssets = want.balanceOf(address(this));
if (looseAssets < _amountNeeded) {
_liquidatedAmount = _withdrawSome(_amountNeeded, looseAssets);
} else {
_liquidatedAmount = Math.min(_amountNeeded, looseAssets);
}
_loss = _amountNeeded - _liquidatedAmount;
calcDifference(_loss);
}
/// @notice Used to invest any assets sent from the vault during report
/// @param _debtOutstanding outstanding debt
function adjustPosition(uint256 _debtOutstanding) internal override {
uint256 _wantBal = want.balanceOf(address(this));
if (_wantBal > _debtOutstanding) {
ICurveMetaPool _curve = ICurveMetaPool(curve);
uint256[metaPool] memory tokenAmounts;
tokenAmounts[uint256(int256(wantIndex))] = _wantBal;
uint256 minAmount = _curve.calc_token_amount(tokenAmounts, true);
minAmount = minAmount - (minAmount * (9995) / (10000));
_curve.add_liquidity(tokenAmounts, minAmount);
uint256 lpBalance = lpToken.balanceOf(address(this));
yVault.deposit(lpBalance);
}
calcDifference(0);
}
function calcDifference(uint256 _loss) internal {
uint256 debt = vault.strategies(address(this)).totalDebt;
// shouldnt be possible
if (_loss > debt) debt = 0;
if (_loss > 0) debt = debt - _loss;
(uint256 _estimate, ) = _estimatedTotalAssets(false);
if (debt != _estimate) {
difference = int256(debt) - int256(_estimate);
} else {
difference = 0;
}
}
function hardMigration() external onlyOwner() {
prepareMigration(address(vault));
}
/// @notice Prepare for migration by transfering tokens
function prepareMigration(address _newStrategy) internal override {
yVault.withdraw();
ICurveMetaPool _curve = ICurveMetaPool(curve);
uint256 lpBalance = lpToken.balanceOf(address(this));
uint256 tokenAmonut = _curve.calc_withdraw_one_coin(lpBalance, wantIndex);
uint256 minAmount = tokenAmonut - (tokenAmonut * (9995) / (10000));
_curve.remove_liquidity_one_coin(lpToken.balanceOf(address(this)), wantIndex, minAmount);
uint256 looseAssets = want.balanceOf(address(this));
want.safeTransfer(_newStrategy, looseAssets);
}
/// @notice Tokens protected by strategy - want tokens are protected by default
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[1] = address(yVault);
protected[2] = address(lpToken);
return protected;
}
/// @notice Migrate to new metapool
function migratePool(address _prepCurve, address _prepYVault) private {
if (yVault.balanceOf(address(this)) > 0) {
migrateWant();
}
address _lpToken = migrateYearn(_prepYVault, _prepCurve);
emit LogNewMigration(_prepYVault, _prepCurve, _lpToken);
prepCurve = address(0);
prepYVault = address(0);
}
/// @notice Migrate Yearn vault
/// @param _prepYVault Target Yvault
/// @param _prepCurve Target Curve meta pool
function migrateYearn(address _prepYVault, address _prepCurve) private returns (address){
yVault = V2YVault(_prepYVault); // Set the yearn vault for this strategy
curve = _prepCurve;
address _lpToken = yVault.token();
lpToken = IERC20(_lpToken);
if (lpToken.allowance(address(this), _prepYVault) == 0) {
lpToken.safeApprove(_prepYVault, type(uint256).max);
}
if (want.allowance(address(this), _prepCurve) == 0) {
want.safeApprove(_prepCurve, type(uint256).max);
}
return _lpToken;
}
/// @notice Pull out any invested funds before migration
function migrateWant() private returns (bool) {
yVault.withdraw();
ICurveMetaPool _curve = ICurveMetaPool(curve);
uint256 lpBalance = lpToken.balanceOf(address(this));
uint256 tokenAmonut = _curve.calc_withdraw_one_coin(lpBalance, wantIndex);
uint256 minAmount = tokenAmonut - (tokenAmonut * (9995) / (10000));
_curve.remove_liquidity_one_coin(lpToken.balanceOf(address(this)), wantIndex, minAmount);
return true;
}
/// @notice Estimated total assets of strategy
/// @param diff Calc token amounts (curve) underreports total amount, to counteract this
/// we add initial difference from last harvest to estimated total assets,
function _estimatedTotalAssets(bool diff) private view returns (uint256, uint256) {
uint256 amount = yVault.balanceOf(address(this)) * (yVault.pricePerShare()) / (uint256(10)**decimals);
amount += lpToken.balanceOf(address(this));
uint256 estimated = 0;
if (amount > 0) {
estimated = ICurveMetaPool(curve).calc_withdraw_one_coin(amount, wantIndex);
}
uint256 balance = want.balanceOf(address(this));
estimated += balance;
if (diff) {
if (difference > int256(estimated)) return (balance, balance);
return (uint256(int256(estimated) + (difference)), balance);
} else {
return (estimated, balance);
}
}
/// @notice Convert ytokens to want
/// @param amountOfTokens Amount to convert
function convertToUnderlying(
uint256 amountOfTokens,
uint256 _decimals,
int128 index
) private view returns (uint256 balance) {
if (amountOfTokens == 0) {
balance = 0;
} else {
uint256 lpAmount = amountOfTokens * (yVault.pricePerShare()) / (uint256(10)**_decimals);
balance = ICurveMetaPool(curve).calc_withdraw_one_coin(lpAmount, index);
}
}
/// @notice Convert want to ytokens
/// @param amountOfUnderlying Amount to convert
function convertFromUnderlying(
uint256 amountOfUnderlying,
uint256 _decimals,
int128 index
) private view returns (uint256 balance) {
if (amountOfUnderlying == 0) {
balance = 0;
} else {
uint256 lpAmount = wantToLp(amountOfUnderlying, index);
balance = lpAmount * (uint256(10)**_decimals) / (yVault.pricePerShare());
}
}
/// @notice Convert want token to LP meta pool token
/// @param amount Amount to convert
function wantToLp(uint256 amount, int128 index) private view returns (uint256) {
uint256[metaPool] memory tokenAmounts;
tokenAmounts[uint256(int256(index))] = amount;
return ICurveMetaPool(curve).calc_token_amount(tokenAmounts, true);
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
return false;
}
}
|
Perform any Strategy unwinding or other calls necessary to capture the "free return" this Strategy has generated since the last time its core position(s) were adjusted. Examples include unwrapping extra rewards. This call is only used during "normal operation" of a Strategy, and should be optimized to minimize losses as much as possible. This method returns any realized profits and/or realized losses incurred, and should return the total amounts of profits/losses/debt payments (in `want` tokens) for the Vault's accounting (e.g. `want.balanceOf(this) >= _debtPayment + _profit - _loss`). `_debtOutstanding` will be 0 if the Strategy is not past the configured debt limit, otherwise its value will be how far past the debt limit the Strategy is. The Strategy's debt limit is configured in the Vault. NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. It is okay for it to be less than `_debtOutstanding`, as that should only used as a guide for how much is left to pay back. Payments should be made to minimize loss from slippage, debt, withdrawal fees, etc. See `vault.debtOutstanding()`./ Perform any adjustments to the core position(s) of this Strategy given what change the Vault made in the "investable capital" available to the Strategy. Note that all "free capital" in the Strategy after the report was made is available for reinvestment. Also note that this number could be 0, and you should handle that scenario accordingly. See comments regarding `_debtOutstanding` on `prepareReturn()`./ Liquidate up to `_amountNeeded` of `want` of this strategy's positions, irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. This function should return the amount of `want` tokens made available by the liquidation. If there is a difference between them, `_loss` indicates whether the difference is due to a realized loss, or if there is some other sitution at play (e.g. locked funds) where the amount made available is less than what is needed. This function is used during emergency exit instead of `prepareReturn()` to liquidate all of the Strategy's positions back to the Vault. NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained/ Provide a signal to the keeper that `tend()` should be called. The keeper will provide the estimated gas cost that they would pay to call `tend()`, and this function should use that estimate to make a determination if calling it is "worth it" for the keeper. This is not the only consideration into issuing this trigger, for example if the position would be negatively affected if `tend()` is not called shortly, then this can return `true` even if the keeper might be "at a loss" (keepers are always reimbursed by Yearn). `callCost` must be priced in terms of `want`. This call and `harvestTrigger()` should never return `true` at the same time. callCost The keeper's estimated cast cost to call `tend()`. return `true` if `tend()` should be called, `false` otherwise./ Adjust the Strategy's position. The purpose of tending isn't to realize gains, but to maximize yield by reinvesting any returns. See comments on `adjustPosition()`./ Don't take profits with this call, but adjust for better gains
|
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
function adjustPosition(uint256 _debtOutstanding) internal virtual;
function liquidatePosition(uint256 _amountNeeded)
internal
virtual
returns (uint256 _liquidatedAmount, uint256 _loss);
function tendTrigger(uint256 callCost) public view virtual returns (bool);
function tend() external onlyAuthorized {
adjustPosition(vault.debtOutstanding());
}
| 6,580,014 |
./partial_match/1/0xdb3D91Dcb27547d82A09556D1028beEdB04A5902/sources/src/Asset/ERC1155ERC721.sol
|
NOTE: call data should be optimized to order _ids so packedBalance can be used efficiently Last bin updated
|
function _batchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) internal {
require(_ids.length == _values.length, "Inconsistent array length between args");
require(_to != address(0), "Invalid recipient");
bool authorized = mSuperOperators[msg.sender] || operatorsForAll[_from][msg.sender] || _from == msg.sender || msg.sender == address(_sandContract);
uint256 bin;
uint256 index;
uint256 balFrom;
uint256 balTo;
uint256 lastBin;
for (uint256 i = 0; i < _ids.length; i++) {
require(authorized || erc721_operators[_ids[i]] == msg.sender, "Operators not approved");
require(owners[_ids[i]] == _from, "not owner");
require(_values[i] == 1, "cannot transfer nft if amount not 1");
numNFTPerAddress[_from] --;
numNFTPerAddress[_to] ++;
owners[_ids[i]] = _to;
erc721_operators[_ids[i]] = address(0);
emit Transfer(_from, _to, _ids[i]);
(bin, index) = (_ids[i] & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFF).getTokenBinIndex();
if (i == 0) {
lastBin = bin;
balFrom = ObjectLib32.updateTokenBalance(packedTokenBalance[_from][bin], index, _values[i], ObjectLib32.Operations.SUB);
balTo = ObjectLib32.updateTokenBalance(packedTokenBalance[_to][bin], index, _values[i], ObjectLib32.Operations.ADD);
packedTokenBalance[_from][lastBin] = balFrom;
packedTokenBalance[_to][lastBin] = balTo;
balFrom = packedTokenBalance[_from][bin];
balTo = packedTokenBalance[_to][bin];
lastBin = bin;
}
balTo = balTo.updateTokenBalance(index, _values[i], ObjectLib32.Operations.ADD);
}
} else {
for (uint256 i = 0; i < _ids.length; i++) {
require(authorized || erc721_operators[_ids[i]] == msg.sender, "Operators not approved");
require(owners[_ids[i]] == _from, "not owner");
require(_values[i] == 1, "cannot transfer nft if amount not 1");
numNFTPerAddress[_from] --;
numNFTPerAddress[_to] ++;
owners[_ids[i]] = _to;
erc721_operators[_ids[i]] = address(0);
emit Transfer(_from, _to, _ids[i]);
(bin, index) = (_ids[i] & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFF).getTokenBinIndex();
if (i == 0) {
lastBin = bin;
balFrom = ObjectLib32.updateTokenBalance(packedTokenBalance[_from][bin], index, _values[i], ObjectLib32.Operations.SUB);
balTo = ObjectLib32.updateTokenBalance(packedTokenBalance[_to][bin], index, _values[i], ObjectLib32.Operations.ADD);
packedTokenBalance[_from][lastBin] = balFrom;
packedTokenBalance[_to][lastBin] = balTo;
balFrom = packedTokenBalance[_from][bin];
balTo = packedTokenBalance[_to][bin];
lastBin = bin;
}
balTo = balTo.updateTokenBalance(index, _values[i], ObjectLib32.Operations.ADD);
}
} else {
balFrom = balFrom.updateTokenBalance(index, _values[i], ObjectLib32.Operations.SUB);
}
| 9,405,670 |
./full_match/42/0x9a02B92718844E2D285FC278529653D499d29827/sources/Users/apple/Documents/yai-protocol-private/contracts/strategies/yearnStrategy/yearnTestnet.sol
|
Withdraw partial funds, normally used with a vault withdrawal
|
function withdraw(uint256 _amount) external isAuthorized {
emit Withdraw();
rebalance();
uint256 _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
tank = 0;
}
else {
if (tank >= _amount) tank = tank.sub(_amount);
else tank = 0;
}
IERC20(want).safeTransfer(vault, _amount);
}
| 16,295,345 |
./full_match/100/0x697240b2124bEd2B19FB003Ec4e4cFb5b125B0D1/sources/deploy/contracts/tokens/MintableBurnableSyntheticToken.sol
|
Accessor method for the list of member with burner role return array of address with burner role/
|
function getBurnerMembers() external view returns (address[] memory) {
uint256 numberOfMembers = getRoleMemberCount(BURNER_ROLE);
address[] memory members = new address[](numberOfMembers);
for (uint256 j = 0; j < numberOfMembers; j++) {
address newMember = getRoleMember(BURNER_ROLE, j);
members[j] = newMember;
}
return members;
}
| 14,267,079 |
./partial_match/1/0x208BCf9CD1D694D1D3C630362E517940e3724D80/sources/Oracle.sol
|
This will set the number of transactions required before the 'swapAndLiquify' function triggers
|
function set_Number_Of_Transactions_Before_Liquify_Trigger(uint8 number_of_transactions) public onlyOwner {
swapTrigger = number_of_transactions;
}
bool public noFeeToTransfer = true;
| 15,961,570 |
./partial_match/1/0xdefac16715671b7b6aeeFE012125f1E19Ee4b7d7/sources/PrimeDeployable.sol
|
Skip the original init function
|
function init(address) internal override {
}
| 2,630,767 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <=0.8.7;
//import "hardhat/console.sol";
import "prb-math/contracts/PRBMathUD60x18.sol";
// describes the logic of taxes
contract TaxContract {
using PRBMathUD60x18 for uint256;
event OnReward(address indexed account, uint256 value); // who and how much rewards received
event OnTaxInterval(uint256 indexed number, uint256 poolSize, uint256 totalOnAccounts); // when the tax interval was changed
// settings
uint256 _TaxIntervalMinutes = 10080; // taxation interval (7 days)
uint256 _ConstantTaxPercent = 1e16; // the constant component of the tax 100%=1e18
uint256 _MinBalancePercentTransactionForReward = 5e15; // minimal percentage of the balance that you need to spend to get a reward
uint256 _RewardStopAccountPercent = 1e16; // at what percentage of the total issue (except for the router), at the time of transition to the new tax interval, the reward will become 0 (the reward drops when the wallet size approaches this percentage)
uint256 _MaxTaxPercent = 1e17; // maximum tax percentage 100%=1e18
mapping(address => uint256) _taxGettings; // time when account was collected fee last time
mapping(address => uint256) _LastRewardedTransactions; // when were the last transactions made that could participate in receiving rewards (see the rule of min transaction size from the size of the wallet)
uint256 _currentTaxPool; // how much tax fee collected in this tax getting interval
uint256 internal _lastTaxPool; // how much tax fee collected in last tax getting interval
uint256 _lastTaxTime; // last time when tax gettings interval was switched
uint256 _lastTotalOnAccounts; // how much was on account at the time of completion of the previous tax collection
uint256 _givedTax; // how many taxes were distributed (distributed from the pool of past taxation)
uint256 _TaxIntervalNumber; // current tax getting interval number
constructor() {
_lastTaxTime = block.timestamp;
}
// sets the taxation settings
function InitializeTax(
uint256 taxIntervalMinutes,
uint256 constantTaxPercent,
uint256 minBalancePercentTransactionForReward,
uint256 rewardStopAccountPercent,
uint256 maxTaxPercent
) internal {
_TaxIntervalMinutes = taxIntervalMinutes;
_ConstantTaxPercent = constantTaxPercent;
_MinBalancePercentTransactionForReward = minBalancePercentTransactionForReward;
_RewardStopAccountPercent = rewardStopAccountPercent;
_MaxTaxPercent = maxTaxPercent;
_lastTaxTime = block.timestamp;
}
// when were the last transactions made that could participate in receiving rewards (see the rule of min transaction size from the size of the wallet)
function GetLastRewardedTransactionTime(address account)
public
view
returns (uint256)
{
return _LastRewardedTransactions[account];
}
// returns the time when the specified account received the tax or 0 if it did not receive the tax
function GetLastRewardTime(address account) public view returns (uint256) {
return _taxGettings[account];
}
// how many taxes were collected during the previous tax interval
function GetLastTaxPool() public view returns (uint256) {
return _lastTaxPool;
}
// returns the time when the last change of the tax interval occurred, or 0 if there was no change yet
function GetLastTaxPoolTime() public view returns (uint256) {
return _lastTaxTime;
}
// how much was on all accounts (except for the router) at the time of changing the tax interval
function GetLastTotalOnAccounts() public view returns (uint256) {
return _lastTotalOnAccounts;
}
//returns the currently set tax interval in days
function GetTaxIntervalMinutes() public view returns (uint256) {
return _TaxIntervalMinutes;
}
// min percentage of the balance that you need to spend to get a reward 1%=1e18
function GetMinBalancePercentTransactionForReward()
public
view
returns (uint256)
{
return _MinBalancePercentTransactionForReward;
}
// how many taxes are collected for the current tax interval
function GetCurrentTaxPool() public view returns (uint256) {
return _currentTaxPool;
}
// how many taxes were distributed (distributed from the pool of past taxation)
function GetGivedTax() public view returns (uint256) {
return _givedTax;
}
// returns the current tax interval number
// now everything is done taking into account the fact that 0 - until the zero tax interval passes, then 1, etc
function GetTaxIntervalNumber() public view returns (uint256) {
return _TaxIntervalNumber;
}
// how much in total is there an undisclosed tax
function GetTotalTax() public view returns (uint256) {
return _currentTaxPool + _lastTaxPool - _givedTax;
}
// attempt to switch to the next tax interval
// tokensOnAccounts - how many tokens are there in total on all accounts subject to tax distribution (all except the router)
function TryNextTaxInterval(uint256 tokensOnAccounts) internal {
if (block.timestamp < _lastTaxTime + _TaxIntervalMinutes * 1 minutes) return;
//console.log("NEXT_TIME");
// we transfer all the collected for the distribution, plus what was not distributed
_lastTaxPool = _lastTaxPool - _givedTax;
_lastTaxPool += _currentTaxPool;
// we reset the collection of funds and how much was issued
_currentTaxPool = 0;
_givedTax = 0;
// we remember how much money the participants have in their hands (to calculate the share of each)
_lastTotalOnAccounts = tokensOnAccounts;
// we write the current date when the tax interval was changed
_lastTaxTime = block.timestamp;
// update the counter of tax intervals
++_TaxIntervalNumber;
emit OnTaxInterval(_TaxIntervalNumber, _lastTaxPool, _lastTotalOnAccounts);
}
// adds the amount issued from the collected pool
// if more than _lastTaxPool is added, it will add how much is missing to _lastTaxPool
// returns how much was added
function AddGivedTax(uint256 amount) internal returns (uint256) {
uint256 last = _givedTax;
_givedTax += amount;
if (_givedTax > _lastTaxPool) _givedTax = _lastTaxPool;
return _givedTax - last;
}
// adds a tax to the tax pool
function AddTaxToPool(uint256 tax) internal {
_currentTaxPool += tax;
}
// if true, then you can get a reward for the transaction
function IsRewardedTransaction(
uint256 accountBalance,
uint256 transactionAmount
) public view returns (bool) {
// if there was nothing on account, then he does not receive a reward
if (accountBalance == 0) return false;
// how many percent of the transaction from the total account balance
uint256 accountTransactionPercent = PRBMathUD60x18.div(
transactionAmount,
accountBalance
);
return
accountTransactionPercent >= _MinBalancePercentTransactionForReward;
}
// updates information about who has received awards and how much
// throws the event OnReward, if there was a non-zero reward
// returns how much tax the specified account should receive
// returns 0 - if there is no reward
// 1 tax interval, it will return the value >0 only once
// accountBalance - account balance
// taxes are not distributed in the 0 tax interval
function UpdateAccountReward(
address account, // account
uint256 accountBalance, // account balance
uint256 transactionAmount // transfer amount
) internal returns (uint256) {
// limiter if the time of the last receipt of tax is greater than or equal to the time of the last transition to a new taxation cycle
if (account == address(0)) return 0;
// if the transaction is less than min percent, it is not considered
if (!IsRewardedTransaction(accountBalance, transactionAmount)) {
//console.log("is not rewarded transaction!");
return 0;
}
// we remember that we have completed a transaction that can participate in the distribution of rewards
//console.log("rewarded transaction!");
_LastRewardedTransactions[account] = block.timestamp;
// limiter, if the account has already received a reward
if (_taxGettings[account] >= _lastTaxTime + 1 days) return 0;
// if 0 is the tax interval
if (_TaxIntervalNumber == 0) return 0;
// don't need it?
if (_lastTotalOnAccounts == 0) return 0;
// everything was distributed
if (_givedTax >= _lastTaxPool) return 0; // if you have issued more than the tax pool, then we will not issue anything further
// we write when I received a reward (or I didn't get it, because the limiters worked)
_taxGettings[account] = block.timestamp;
// how much interest did the account have at the time of changing the tax interval from the entire issue
uint256 percentOfTotal = PRBMathUD60x18.div(
accountBalance,
_lastTotalOnAccounts
);
// calculate reward
uint256 reward = PRBMathUD60x18.mul(percentOfTotal, _lastTaxPool);
// calculation of the multiplication ratio of the tax (the closer the account to 1% of all accounts, the smaller the coefficient of those 1% = 0 0% = 1e18)
reward = PRBMathUD60x18.mul(
reward,
GetRewardDynamicKoef(accountBalance)
);
// we increase the counter of the issued tax
_givedTax += reward;
//console.log("reward=", reward);
if (reward > 0) emit OnReward(account, reward);
return reward;
}
// returns the reward coefficient
// when 0 of the total number of accounts
// 0 - when 1% of the selected issue (on account)
function GetRewardDynamicKoef(uint256 accountBalance)
public
view
returns (uint256)
{
// how much interest did the account have at the time of changing the tax interval from the entire issue
uint256 percentOfTotal = PRBMathUD60x18.div(
accountBalance,
_lastTotalOnAccounts
);
if (percentOfTotal >= _RewardStopAccountPercent) return 0;
return
1e18 -
PRBMathUD60x18.div(percentOfTotal, _RewardStopAccountPercent);
}
// returns the tax on the specified number of tokens
function GetTax(
uint256 numTokens, // how much do we transfer
uint256 accountBalance, // the balance on the account that transfers
uint256 totalOnAccounts // the entire issue without an router
) public view returns (uint256) {
// calculating the tax
uint256 tax = GetStaticTax(numTokens) +
GetDynamicTax(numTokens, accountBalance, totalOnAccounts);
// limit the tax
uint256 maxTax = PRBMathUD60x18.mul(numTokens, _MaxTaxPercent);
if (tax > maxTax) tax = maxTax;
// the results
return tax;
}
// returns the static amount of the transaction tax
function GetStaticTax(
uint256 numTokens // how much do we transfer
) public view returns (uint256) {
return PRBMathUD60x18.mul(numTokens, _ConstantTaxPercent);
}
// returns the dynamic component of the transaction tax
function GetDynamicTax(
uint256 numTokens, // how much do we transfer
uint256 accountBalance, // the balance on the account that transfers
uint256 totalOnAccounts // the entire emission without the router
) public pure returns (uint256) {
// 0 if the total emission is 0
if (totalOnAccounts == 0) return 0;
// calculation of the dynamic component of the tax (100% of the total token will pay 100% from the top of the transaction size)
// transaction size factor
uint256 transactionK = PRBMathUD60x18.div(numTokens, totalOnAccounts);
// adding a tax
uint256 tax = PRBMathUD60x18.mul(transactionK, numTokens);
// calculation of the dynamic component of the tax (depending on the size of the wallet, an account of 100% of the total token will pay 100% on top)
transactionK = PRBMathUD60x18.div(accountBalance, totalOnAccounts);
// adding a tax
tax += PRBMathUD60x18.mul(transactionK, numTokens);
// the results
return tax;
}
// returns the percentage of the constant component of the tax 100%=1e18
function GetConstantTaxPercent() public view returns (uint256) {
return _ConstantTaxPercent;
}
// returns the percentage at which the dynamic reward becomes 0 1e18=100%
function GetRewardStopAccountPercent() public view returns (uint256) {
return _RewardStopAccountPercent;
}
// // maximum tax percentage 100%=1e18
function GetMaxTaxPercent() public view returns (uint256) {
return _MaxTaxPercent;
}
}
|
returns the time when the specified account received the tax or 0 if it did not receive the tax
|
function GetLastRewardTime(address account) public view returns (uint256) {
return _taxGettings[account];
}
| 6,362,673 |
pragma solidity ^0.4.18;
contract Token {
// owner -> amount
mapping(address => uint256) balances;
// owner -> spender -> max amount
mapping(address => mapping(address => uint256)) allowances;
uint256 supply;
uint256 constant LOG0 = 0;
uint256 constant LOG1 = 1;
uint256 constant LOG2 = 2;
uint256 constant LOG3 = 3;
uint256 constant LOG4 = 4;
uint256 constant SEND = 5;
uint256 constant TRANSFER = uint256(keccak256("Transfer(address,address,uint256)"));
uint256 constant APPROVAL = uint256(keccak256("Approval(address,address,uint256)"));
// Deposits ether with the contract and converts it to tokens.
// One wei is worth one token.
function deposit(address _sender, uint256 _msg_value) public returns (uint256[6] success){
// overflow check. not necessary for 1-to-1 token-to-wei peg, but
// might be good to have in case somebody decides to modify this code
// to have the owner issue tokens, etc...
if (supply + _msg_value < supply) {
return ([uint256(0), 0, 0, 0, 0, 0]);
}
supply += _msg_value;
balances[_sender] += _msg_value;
return ([uint256(1), LOG3, TRANSFER, 0, uint256(_sender), _msg_value]);
}
// Converts tokens to ether and withdraws the ether.
// One token is worth one wei.
function withdraw(address _sender, uint256 _msg_value, uint256 _value) public returns (uint256[10] success) {
if (_msg_value != 0) {
return ([uint256(0), 0, 0, 0, 0, 0, 0, 0, 0, 0]);
}
if (_value <= balances[_sender]) {
balances[_sender] -= _value;
supply -= _value;
return ([uint256(1), 1, SEND, uint256(_sender), _value, LOG3, TRANSFER, uint256(_sender), 0, _value]);
} else {
return ([uint256(0), 0, 0, 0, 0, 0, 0, 0, 0, 0]);
}
}
// Spec: Get the total token supply
function totalSupply(address, uint256 _msg_value) public constant returns (uint256[2] success) {
if (_msg_value != 0) {
return ([uint256(0), 0]);
}
return ([uint256(1), supply]);
}
// Spec: Get the account balance of another account with address _owner
// The spec is a bit surprising to me. Why should this only work for the
// balance of "another account", i.e. only if _owner != _sender?
// For now, I am assuming that this is just due to unclear wording and that
// anybody's balance may be queried this way.
function balanceOf(address, uint256 _msg_value, address _owner) public constant returns (uint256[2] success) {
if (_msg_value != 0) {
return ([uint256(0), 0]);
}
return ([uint256(1), balances[_owner]]);
}
function internalTransfer(address _from, address _to, uint256 _value) internal returns (uint256[7] success) {
if (_value <= balances[_from]) {
balances[_from] -= _value;
balances[_to] += _value;
return ([uint256(1), 1, LOG3, TRANSFER, uint256(_from), uint256(_to), _value]);
} else {
return ([uint256(0), 0, 0, 0, 0, 0, 0]);
}
}
// Spec: Send _value amount of tokens to address _to
function transfer(address _sender, uint256 _msg_value, address _to, uint256 _value) public returns (uint256[7] success) {
if (_msg_value != 0) {
return ([uint256(0), 0, 0, 0, 0, 0, 0]);
}
address _from = _sender;
return internalTransfer(_from, _to, _value);
}
// Spec: Send _value amount of tokens from address _from to address _to
function transferFrom(address _sender, uint256 _msg_value, address _from, address _to, uint256 _value) public returns (uint256[7] success) {
if (_msg_value != 0) {
return ([uint256(0), 0, 0, 0, 0, 0, 0]);
}
address _spender = _sender;
if(_value <= allowances[_from][_spender]) {
uint256[7] memory ret = internalTransfer(_from, _to, _value);
if (ret[0] == 1) {
allowances[_from][_spender] -= _value;
return ret;
}
return ([uint256(0), 0, 0, 0, 0, 0, 0]);
}
return ([uint256(0), 0, 0, 0, 0, 0, 0]);
}
// Spec: Allow _spender to withdraw from your account, multiple times, up
// to the _value amount. If this function is called again it overwrites the
// current allowance with _value.
function approve(address _sender, uint256 _msg_value, address _spender, uint256 _value) public returns (uint256[7] success) {
if (_msg_value != 0) {
return ([uint256(0), 0, 0, 0, 0, 0, 0]);
}
address _owner = _sender;
allowances[_owner][_spender] = _value;
return ([uint256(1), 1, LOG3, APPROVAL, uint256(_sender), uint256(_spender), _value]);
}
// Spec: Returns the amount which _spender is still allowed to withdraw
// from _owner.
// What if the allowance is higher than the balance of the owner?
// Callers should be careful to use min(allowance, balanceOf) to make sure
// that the allowance is actually present in the account!
function allowance(address, uint256 _msg_value, address _owner, address _spender) public constant returns (uint256[2] success) {
if (_msg_value != 0) {
return ([uint256(0), 0]);
}
return ([uint256(1), allowances[_owner][_spender]]);
}
}
|
Spec: Allow _spender to withdraw from your account, multiple times, up to the _value amount. If this function is called again it overwrites the current allowance with _value.
|
function approve(address _sender, uint256 _msg_value, address _spender, uint256 _value) public returns (uint256[7] success) {
if (_msg_value != 0) {
return ([uint256(0), 0, 0, 0, 0, 0, 0]);
}
address _owner = _sender;
allowances[_owner][_spender] = _value;
return ([uint256(1), 1, LOG3, APPROVAL, uint256(_sender), uint256(_spender), _value]);
}
| 12,759,157 |
/**
*Submitted for verification at Etherscan.io on 2021-04-10
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
abstract contract IGem {
function dec() virtual public returns (uint);
function gem() virtual public returns (IGem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
abstract contract IJoin {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public view returns (IGem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract IManager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
abstract contract IDFSRegistry {
function getAddr(bytes32 _id) public view virtual returns (address);
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public virtual;
function startContractChange(bytes32 _id, address _newContractAddr) public virtual;
function approveContractChange(bytes32 _id) public virtual;
function cancelContractChange(bytes32 _id) public virtual;
function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual;
}
interface IERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
library Address {
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);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
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);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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 Edited so it always first approves 0 and then the value, because of non standard tokens
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/// @title A stateful contract that holds and can change owner/admin
contract AdminVault {
address public owner;
address public admin;
constructor() {
owner = msg.sender;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function changeOwner(address _owner) public {
require(admin == msg.sender, "msg.sender not admin");
owner = _owner;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function changeAdmin(address _admin) public {
require(admin == msg.sender, "msg.sender not admin");
admin = _admin;
}
}
/// @title AdminAuth Handles owner/admin privileges over smart contracts
contract AdminAuth {
using SafeERC20 for IERC20;
AdminVault public constant adminVault = AdminVault(0xCCf3d848e08b94478Ed8f46fFead3008faF581fD);
modifier onlyOwner() {
require(adminVault.owner() == msg.sender, "msg.sender not owner");
_;
}
modifier onlyAdmin() {
require(adminVault.admin() == msg.sender, "msg.sender not admin");
_;
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(_receiver).transfer(_amount);
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
/// @notice Destroy the contract
function kill() public onlyAdmin {
selfdestruct(payable(msg.sender));
}
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(
address _contract,
address _caller,
string memory _logName,
bytes memory _data
) public {
emit LogEvent(_contract, _caller, _logName, _data);
}
}
/// @title Stores all the important DFS addresses and can be changed (timelock)
contract DFSRegistry is AdminAuth {
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists";
string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists";
string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process";
string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger";
string public constant ERR_CHANGE_NOT_READY = "Change not ready yet";
string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0";
string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change";
string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change";
struct Entry {
address contractAddr;
uint256 waitPeriod;
uint256 changeStartTime;
bool inContractChange;
bool inWaitPeriodChange;
bool exists;
}
mapping(bytes32 => Entry) public entries;
mapping(bytes32 => address) public previousAddresses;
mapping(bytes32 => address) public pendingAddresses;
mapping(bytes32 => uint256) public pendingWaitTimes;
/// @notice Given an contract id returns the registered address
/// @dev Id is keccak256 of the contract name
/// @param _id Id of contract
function getAddr(bytes32 _id) public view returns (address) {
return entries[_id].contractAddr;
}
/// @notice Helper function to easily query if id is registered
/// @param _id Id of contract
function isRegistered(bytes32 _id) public view returns (bool) {
return entries[_id].exists;
}
/////////////////////////// OWNER ONLY FUNCTIONS ///////////////////////////
/// @notice Adds a new contract to the registry
/// @param _id Id of contract
/// @param _contractAddr Address of the contract
/// @param _waitPeriod Amount of time to wait before a contract address can be changed
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public onlyOwner {
require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS);
entries[_id] = Entry({
contractAddr: _contractAddr,
waitPeriod: _waitPeriod,
changeStartTime: 0,
inContractChange: false,
inWaitPeriodChange: false,
exists: true
});
// Remember tha address so we can revert back to old addr if needed
previousAddresses[_id] = _contractAddr;
logger.Log(
address(this),
msg.sender,
"AddNewContract",
abi.encode(_id, _contractAddr, _waitPeriod)
);
}
/// @notice Reverts to the previous address immediately
/// @dev In case the new version has a fault, a quick way to fallback to the old contract
/// @param _id Id of contract
function revertToPreviousAddress(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR);
address currentAddr = entries[_id].contractAddr;
entries[_id].contractAddr = previousAddresses[_id];
logger.Log(
address(this),
msg.sender,
"RevertToPreviousAddress",
abi.encode(_id, currentAddr, previousAddresses[_id])
);
}
/// @notice Starts an address change for an existing entry
/// @dev Can override a change that is currently in progress
/// @param _id Id of contract
/// @param _newContractAddr Address of the new contract
function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE);
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inContractChange = true;
pendingAddresses[_id] = _newContractAddr;
logger.Log(
address(this),
msg.sender,
"StartContractChange",
abi.encode(_id, entries[_id].contractAddr, _newContractAddr)
);
}
/// @notice Changes new contract address, correct time must have passed
/// @param _id Id of contract
function approveContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
address oldContractAddr = entries[_id].contractAddr;
entries[_id].contractAddr = pendingAddresses[_id];
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
pendingAddresses[_id] = address(0);
previousAddresses[_id] = oldContractAddr;
logger.Log(
address(this),
msg.sender,
"ApproveContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Cancel pending change
/// @param _id Id of contract
function cancelContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
address oldContractAddr = pendingAddresses[_id];
pendingAddresses[_id] = address(0);
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Starts the change for waitPeriod
/// @param _id Id of contract
/// @param _newWaitPeriod New wait time
function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE);
pendingWaitTimes[_id] = _newWaitPeriod;
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inWaitPeriodChange = true;
logger.Log(
address(this),
msg.sender,
"StartWaitPeriodChange",
abi.encode(_id, _newWaitPeriod)
);
}
/// @notice Changes new wait period, correct time must have passed
/// @param _id Id of contract
function approveWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
uint256 oldWaitTime = entries[_id].waitPeriod;
entries[_id].waitPeriod = pendingWaitTimes[_id];
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
pendingWaitTimes[_id] = 0;
logger.Log(
address(this),
msg.sender,
"ApproveWaitPeriodChange",
abi.encode(_id, oldWaitTime, entries[_id].waitPeriod)
);
}
/// @notice Cancel wait period change
/// @param _id Id of contract
function cancelWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
uint256 oldWaitPeriod = pendingWaitTimes[_id];
pendingWaitTimes[_id] = 0;
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelWaitPeriodChange",
abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod)
);
}
}
/// @title Implements Action interface and common helpers for passing inputs
abstract contract ActionBase is AdminAuth {
address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C;
DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR);
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value";
string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value";
/// @dev Subscription params index range [128, 255]
uint8 public constant SUB_MIN_INDEX_VALUE = 128;
uint8 public constant SUB_MAX_INDEX_VALUE = 255;
/// @dev Return params index range [1, 127]
uint8 public constant RETURN_MIN_INDEX_VALUE = 1;
uint8 public constant RETURN_MAX_INDEX_VALUE = 127;
/// @dev If the input value should not be replaced
uint8 public constant NO_PARAM_MAPPING = 0;
/// @dev We need to parse Flash loan actions in a different way
enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION }
/// @notice Parses inputs and runs the implemented action through a proxy
/// @dev Is called by the TaskExecutor chaining actions together
/// @param _callData Array of input values each value encoded as bytes
/// @param _subData Array of subscribed vales, replaces input values if specified
/// @param _paramMapping Array that specifies how return and subscribed values are mapped in input
/// @param _returnValues Returns values from actions before, which can be injected in inputs
/// @return Returns a bytes32 value through DSProxy, each actions implements what that value is
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual returns (bytes32);
/// @notice Parses inputs and runs the single implemented action through a proxy
/// @dev Used to save gas when executing a single action directly
function executeActionDirect(bytes[] memory _callData) public virtual payable;
/// @notice Returns the type of action we are implementing
function actionType() public pure virtual returns (uint8);
//////////////////////////// HELPER METHODS ////////////////////////////
/// @notice Given an uint256 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamUint(
uint _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (uint) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = uint(_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (uint));
}
}
return _param;
}
/// @notice Given an addr input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamAddr(
address _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (address) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = address(bytes20((_returnValues[getReturnIndex(_mapType)])));
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (address));
}
}
return _param;
}
/// @notice Given an bytes32 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamABytes32(
bytes32 _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (bytes32) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = (_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32));
}
}
return _param;
}
/// @notice Checks if the paramMapping value indicated that we need to inject values
/// @param _type Indicated the type of the input
function isReplaceable(uint8 _type) internal pure returns (bool) {
return _type != NO_PARAM_MAPPING;
}
/// @notice Checks if the paramMapping value is in the return value range
/// @param _type Indicated the type of the input
function isReturnInjection(uint8 _type) internal pure returns (bool) {
return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in return array value
/// @param _type Indicated the type of the input
function getReturnIndex(uint8 _type) internal pure returns (uint8) {
require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE);
return (_type - RETURN_MIN_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in sub array value
/// @param _type Indicated the type of the input
function getSubIndex(uint8 _type) internal pure returns (uint8) {
require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE);
return (_type - SUB_MIN_INDEX_VALUE);
}
}
/// @title Open a new Maker vault
contract McdOpen is ActionBase {
/// @inheritdoc ActionBase
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
(address joinAddr, address mcdManager) = parseInputs(_callData);
joinAddr = _parseParamAddr(joinAddr, _paramMapping[0], _subData, _returnValues);
uint256 newVaultId = _mcdOpen(joinAddr, mcdManager);
return bytes32(newVaultId);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes[] memory _callData) public payable override {
(address joinAddr, address mcdManager) = parseInputs(_callData);
_mcdOpen(joinAddr, mcdManager);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
/// @notice Opens up an empty vault
/// @param _joinAddr Join address of the maker collateral
/// @param _mcdManager The manager address we are using
function _mcdOpen(address _joinAddr, address _mcdManager) internal returns (uint256 vaultId) {
bytes32 ilk = IJoin(_joinAddr).ilk();
vaultId = IManager(_mcdManager).open(ilk, address(this));
logger.Log(
address(this),
msg.sender,
"McdOpen",
abi.encode(vaultId, _joinAddr, _mcdManager)
);
}
function parseInputs(bytes[] memory _callData)
internal
pure
returns (address joinAddr, address mcdManager)
{
joinAddr = abi.decode(_callData[0], (address));
mcdManager = abi.decode(_callData[1], (address));
}
}
|
Opens up an empty vault _joinAddr Join address of the maker collateral _mcdManager The manager address we are using
|
function _mcdOpen(address _joinAddr, address _mcdManager) internal returns (uint256 vaultId) {
bytes32 ilk = IJoin(_joinAddr).ilk();
vaultId = IManager(_mcdManager).open(ilk, address(this));
logger.Log(
address(this),
msg.sender,
"McdOpen",
abi.encode(vaultId, _joinAddr, _mcdManager)
);
}
| 2,285,153 |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
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;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbUintsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
uint256 value;
}
struct BlockNumbUints {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbUints storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (uint256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbUintsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbUints storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbUintsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbIntsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
int256 value;
}
struct BlockNumbInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbInts storage self)
internal
view
returns (int256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbIntsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbIntsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbDisdIntsLib {
using SafeMathIntLib for int256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Discount {
int256 tier;
int256 value;
}
struct Entry {
uint256 blockNumber;
int256 nominal;
Discount[] discounts;
}
struct BlockNumbDisdInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentNominalValue(BlockNumbDisdInts storage self)
internal
view
returns (int256)
{
return nominalValueAt(self, block.number);
}
function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier)
internal
view
returns (int256)
{
return discountedValueAt(self, block.number, tier);
}
function currentEntry(BlockNumbDisdInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).nominal;
}
function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier)
internal
view
returns (int256)
{
Entry memory entry = entryAt(self, _blockNumber);
if (0 < entry.discounts.length) {
uint256 index = indexByTier(entry.discounts, tier);
if (0 < index)
return entry.nominal.mul(
ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value)
).div(
ConstantsLib.PARTS_PER()
);
else
return entry.nominal;
} else
return entry.nominal;
}
function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbDisdIntsLib.sol:101]"
);
self.entries.length++;
Entry storage entry = self.entries[self.entries.length - 1];
entry.blockNumber = blockNumber;
entry.nominal = nominal;
}
function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
internal
{
require(discountTiers.length == discountValues.length, "Parameter array lengths mismatch [BlockNumbDisdIntsLib.sol:118]");
addNominalEntry(self, blockNumber, nominal);
Entry storage entry = self.entries[self.entries.length - 1];
for (uint256 i = 0; i < discountTiers.length; i++)
entry.discounts.push(Discount(discountTiers[i], discountValues[i]));
}
function count(BlockNumbDisdInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbDisdInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbDisdIntsLib.sol:148]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
/// @dev The index returned here is 1-based
function indexByTier(Discount[] memory discounts, int256 tier)
internal
pure
returns (uint256)
{
require(0 < discounts.length, "No discounts found [BlockNumbDisdIntsLib.sol:161]");
for (uint256 i = discounts.length; i > 0; i--)
if (tier >= discounts[i - 1].tier)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbReferenceCurrenciesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Currency currency;
}
struct BlockNumbReferenceCurrencies {
mapping(address => mapping(uint256 => Entry[])) entriesByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return currencyAt(self, referenceCurrency, block.number);
}
function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry storage)
{
return entryAt(self, referenceCurrency, block.number);
}
function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return entryAt(self, referenceCurrency, _blockNumber).currency;
}
function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)];
}
function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber,
MonetaryTypesLib.Currency memory referenceCurrency, MonetaryTypesLib.Currency memory currency)
internal
{
require(
0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length ||
blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber,
"Later entry found for currency [BlockNumbReferenceCurrenciesLib.sol:67]"
);
self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency));
}
function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (uint256)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length;
}
function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry[] storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id];
}
function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length, "No entries found for currency [BlockNumbReferenceCurrenciesLib.sol:97]");
for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--)
if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbFiguresLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Figure value;
}
struct BlockNumbFigures {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbFigures storage self)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbFigures storage self)
internal
view
returns (Entry storage)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure memory value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbFiguresLib.sol:65]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbFigures storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbFigures storage self)
internal
view
returns (Entry[] storage)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbFiguresLib.sol:95]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Configuration
* @notice An oracle for configurations values
*/
contract Configuration is Modifiable, Ownable, Servable {
using SafeMathIntLib for int256;
using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints;
using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts;
using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts;
using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies;
using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public OPERATIONAL_MODE_ACTION = "operational_mode";
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum OperationalMode {Normal, Exit}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
OperationalMode public operationalMode = OperationalMode.Normal;
BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber;
BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber;
BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber;
uint256 public earliestSettlementBlockNumber;
bool public earliestSettlementBlockNumberUpdateDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetOperationalModeExitEvent();
event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues);
event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal);
event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId);
event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt,
uint256 stakeCurrencyId);
event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber);
event DisableEarliestSettlementBlockNumberUpdateEvent();
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
updateDelayBlocksByBlockNumber.addEntry(block.number, 0);
}
//
// Public functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set operational mode to Exit
/// @dev Once operational mode is set to Exit it may not be set back to Normal
function setOperationalModeExit()
public
onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION)
{
operationalMode = OperationalMode.Exit;
emit SetOperationalModeExitEvent();
}
/// @notice Return true if operational mode is Normal
function isOperationalModeNormal()
public
view
returns (bool)
{
return OperationalMode.Normal == operationalMode;
}
/// @notice Return true if operational mode is Exit
function isOperationalModeExit()
public
view
returns (bool)
{
return OperationalMode.Exit == operationalMode;
}
/// @notice Get the current value of update delay blocks
/// @return The value of update delay blocks
function updateDelayBlocks()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of update delay blocks values
/// @return The count of update delay blocks values
function updateDelayBlocksCount()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.count();
}
/// @notice Set the number of update delay blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newUpdateDelayBlocks The new update delay blocks value
function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks);
emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks);
}
/// @notice Get the current value of confirmation blocks
/// @return The value of confirmation blocks
function confirmationBlocks()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of confirmation blocks values
/// @return The count of confirmation blocks values
function confirmationBlocksCount()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.count();
}
/// @notice Set the number of confirmation blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newConfirmationBlocks The new confirmation blocks value
function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks);
emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks);
}
/// @notice Get number of trade maker fee block number tiers
function tradeMakerFeesCount()
public
view
returns (uint256)
{
return tradeMakerFeeByBlockNumber.count();
}
/// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeMakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of trade taker fee block number tiers
function tradeTakerFeesCount()
public
view
returns (uint256)
{
return tradeTakerFeeByBlockNumber.count();
}
/// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeTakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers
function paymentFeesCount()
public
view
returns (uint256)
{
return paymentFeeByBlockNumber.count();
}
/// @notice Get payment relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function paymentFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers of given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment relative fee for given currency at given block number, possibly discounted by
/// discount tier value
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param discountTier The concerned discount tier
function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier)
public
view
returns (int256)
{
if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt(
blockNumber, discountTier
);
else
return paymentFee(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values for given currency at given
/// block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry(
fromBlockNumber, nominal, discountTiers, discountValues
);
emit SetCurrencyPaymentFeeEvent(
fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues
);
}
/// @notice Get number of minimum trade maker fee block number tiers
function tradeMakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeMakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade maker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeMakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade maker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum trade taker fee block number tiers
function tradeTakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeTakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade taker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeTakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade taker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers
function paymentMinimumFeesCount()
public
view
returns (uint256)
{
return paymentMinimumFeeByBlockNumber.count();
}
/// @notice Get payment minimum relative fee at given block number
/// @param blockNumber The concerned block number
function paymentMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return paymentMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set payment minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers for given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment minimum relative fee for given currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber);
else
return paymentMinimumFee(blockNumber);
}
/// @notice Set payment minimum relative fee for given currency at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Minimum relative fee
function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal);
emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal);
}
/// @notice Get number of fee currencies for the given reference currency
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrenciesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId));
}
/// @notice Get the fee currency for the given reference currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (address ct, uint256 id)
{
MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt(
MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber
);
ct = _feeCurrency.ct;
id = _feeCurrency.id;
}
/// @notice Set the fee currency for the given reference currency at given block number
/// @param fromBlockNumber Block number from which the update applies
/// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20)
/// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH)
/// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20)
function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
feeCurrencyByCurrencyBlockNumber.addEntry(
fromBlockNumber,
MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId),
MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId)
);
emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId,
feeCurrencyCt, feeCurrencyId);
}
/// @notice Get the current value of wallet lock timeout
/// @return The value of wallet lock timeout
function walletLockTimeout()
public
view
returns (uint256)
{
return walletLockTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of wallet lock
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of cancel order challenge timeout
/// @return The value of cancel order challenge timeout
function cancelOrderChallengeTimeout()
public
view
returns (uint256)
{
return cancelOrderChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of cancel order challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of settlement challenge timeout
/// @return The value of settlement challenge timeout
function settlementChallengeTimeout()
public
view
returns (uint256)
{
return settlementChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of settlement challenges
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of fraud stake fraction
/// @return The value of fraud stake fraction
function fraudStakeFraction()
public
view
returns (uint256)
{
return fraudStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in fraud challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of wallet settlement stake fraction
/// @return The value of wallet settlement stake fraction
function walletSettlementStakeFraction()
public
view
returns (uint256)
{
return walletSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by wallet
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake fraction
/// @return The value of operator settlement stake fraction
function operatorSettlementStakeFraction()
public
view
returns (uint256)
{
return operatorSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake
/// @return The value of operator settlement stake
function operatorSettlementStake()
public
view
returns (int256 amount, address currencyCt, uint256 currencyId)
{
MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue();
amount = stake.amount;
currencyCt = stake.currency.ct;
currencyId = stake.currency.id;
}
/// @notice Set figure of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeAmount The amount gained
/// @param stakeCurrencyCt The address of currency gained
/// @param stakeCurrencyId The ID of currency gained
function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount,
address stakeCurrencyCt, uint256 stakeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId));
operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake);
emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId);
}
/// @notice Set the block number of the earliest settlement initiation
/// @param _earliestSettlementBlockNumber The block number of the earliest settlement
function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber)
public
onlyOperator
{
require(!earliestSettlementBlockNumberUpdateDisabled, "Earliest settlement block number update disabled [Configuration.sol:715]");
earliestSettlementBlockNumber = _earliestSettlementBlockNumber;
emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber);
}
/// @notice Disable further updates to the earliest settlement block number
/// @dev This operation can not be undone
function disableEarliestSettlementBlockNumberUpdate()
public
onlyOperator
{
earliestSettlementBlockNumberUpdateDisabled = true;
emit DisableEarliestSettlementBlockNumberUpdateEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDelayedBlockNumber(uint256 blockNumber) {
require(
0 == updateDelayBlocksByBlockNumber.count() ||
blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue(),
"Block number not sufficiently delayed [Configuration.sol:735]"
);
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that has a client fund property
*/
contract Configurable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Configuration public configuration;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the configuration contract
/// @param newConfiguration The (address of) Configuration contract instance
function setConfiguration(Configuration newConfiguration)
public
onlyDeployer
notNullAddress(address(newConfiguration))
notSameAddresses(address(newConfiguration), address(configuration))
{
// Set new configuration
Configuration oldConfiguration = configuration;
configuration = newConfiguration;
// Emit event
emit SetConfigurationEvent(oldConfiguration, newConfiguration);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier configurationInitialized() {
require(address(configuration) != address(0), "Configuration not initialized [Configurable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that contains registered beneficiaries
*/
contract Benefactor is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Beneficiary[] public beneficiaries;
mapping(address => uint256) public beneficiaryIndexByAddress;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterBeneficiaryEvent(Beneficiary beneficiary);
event DeregisterBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given beneficiary
/// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] > 0)
return false;
beneficiaries.push(beneficiary);
beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length;
// Emit event
emit RegisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Deregister the given beneficiary
/// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] == 0)
return false;
uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1;
if (idx < beneficiaries.length - 1) {
// Remap the last item in the array to this index
beneficiaries[idx] = beneficiaries[beneficiaries.length - 1];
beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;
}
beneficiaries.length--;
beneficiaryIndexByAddress[_beneficiary] = 0;
// Emit event
emit DeregisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Gauge whether the given address is the one of a registered beneficiary
/// @param beneficiary Address of beneficiary
/// @return true if beneficiary is registered, else false
function isRegisteredBeneficiary(Beneficiary beneficiary)
public
view
returns (bool)
{
return beneficiaryIndexByAddress[address(beneficiary)] > 0;
}
/// @notice Get the count of registered beneficiaries
/// @return The count of registered beneficiaries
function registeredBeneficiariesCount()
public
view
returns (uint256)
{
return beneficiaries.length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AuthorizableServable
* @notice A servable that may be authorized and unauthorized
*/
contract AuthorizableServable is Servable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public initialServiceAuthorizationDisabled;
mapping(address => bool) public initialServiceAuthorizedMap;
mapping(address => mapping(address => bool)) public initialServiceWalletUnauthorizedMap;
mapping(address => mapping(address => bool)) public serviceWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletTouchedMap;
mapping(address => mapping(address => bytes32[])) public serviceWalletActionList;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AuthorizeInitialServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
event UnauthorizeRegisteredServiceEvent(address wallet, address service);
event UnauthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Add service to initial whitelist of services
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeInitialService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(!initialServiceAuthorizationDisabled);
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Enable all actions for given wallet
initialServiceAuthorizedMap[service] = true;
// Emit event
emit AuthorizeInitialServiceEvent(msg.sender, service);
}
/// @notice Disable further initial authorization of services
/// @dev This operation can not be undone
function disableInitialServiceAuthorization()
public
onlyDeployer
{
initialServiceAuthorizationDisabled = true;
}
/// @notice Authorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Ensure service is not initial. Initial services are not authorized per action.
require(!initialServiceAuthorizedMap[service]);
// Enable all actions for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = true;
// Emit event
emit AuthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Unauthorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function unauthorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// If initial service then disable it
if (initialServiceAuthorizedMap[service])
initialServiceWalletUnauthorizedMap[service][msg.sender] = true;
// Else disable all actions for given wallet
else {
serviceWalletAuthorizedMap[service][msg.sender] = false;
for (uint256 i = 0; i < serviceWalletActionList[service][msg.sender].length; i++)
serviceActionWalletAuthorizedMap[service][serviceWalletActionList[service][msg.sender][i]][msg.sender] = true;
}
// Emit event
emit UnauthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Gauge whether the given service is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param wallet The address of the concerned wallet
/// @return true if service is authorized for the given wallet, else false
function isAuthorizedRegisteredService(address service, address wallet)
public
view
returns (bool)
{
return isRegisteredActiveService(service) &&
(isInitialServiceAuthorizedForWallet(service, wallet) || serviceWalletAuthorizedMap[service][wallet]);
}
/// @notice Authorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function authorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service action is registered
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial
require(!initialServiceAuthorizedMap[service]);
// Enable service action for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = false;
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = true;
if (!serviceActionWalletTouchedMap[service][actionHash][msg.sender]) {
serviceActionWalletTouchedMap[service][actionHash][msg.sender] = true;
serviceWalletActionList[service][msg.sender].push(actionHash);
}
// Emit event
emit AuthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Unauthorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function unauthorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service is registered and action enabled
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial as it can not be unauthorized per action
require(!initialServiceAuthorizedMap[service]);
// Disable service action for given wallet
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = false;
// Emit event
emit UnauthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Gauge whether the given service action is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param action The concerned service action
/// @param wallet The address of the concerned wallet
/// @return true if service action is authorized for the given wallet, else false
function isAuthorizedRegisteredServiceAction(address service, string memory action, address wallet)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isEnabledServiceAction(service, action) &&
(
isInitialServiceAuthorizedForWallet(service, wallet) ||
serviceWalletAuthorizedMap[service][wallet] ||
serviceActionWalletAuthorizedMap[service][actionHash][wallet]
);
}
function isInitialServiceAuthorizedForWallet(address service, address wallet)
private
view
returns (bool)
{
return initialServiceAuthorizedMap[service] ? !initialServiceWalletUnauthorizedMap[service][wallet] : false;
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyAuthorizedService(address wallet) {
require(isAuthorizedRegisteredService(msg.sender, wallet));
_;
}
modifier onlyAuthorizedServiceAction(string memory action, address wallet) {
require(isAuthorizedRegisteredServiceAction(msg.sender, action, wallet));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library NonFungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256[] ids;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256[])) idsByCurrency;
mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory)
{
return self.idsByCurrency[currencyCt][currencyId];
}
function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp)
internal
view
returns (int256[] memory)
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length)
return new int256[](0);
indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1);
int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1);
for (uint256 i = indexLow; i < indexUp; i++)
idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i];
return idsByCurrency;
}
function idsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.idsByCurrency[currencyCt][currencyId].length;
}
function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 < self.idIndexById[currencyCt][currencyId][id];
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256[] memory, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.ids, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.ids, record.blockNumber);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
{
int256[] memory ids = new int256[](1);
ids[0] = id;
set(self, ids, currencyCt, currencyId);
}
function set(Balance storage self, int256[] memory ids, address currencyCt, uint256 currencyId)
internal
{
uint256 i;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId] = ids;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function reset(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId].length = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
if (0 < self.idIndexById[currencyCt][currencyId][id])
return false;
self.idsByCurrency[currencyCt][currencyId].push(id);
self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
uint256 index = self.idIndexById[currencyCt][currencyId][id];
if (0 == index)
return false;
if (index < self.idsByCurrency[currencyCt][currencyId].length) {
self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1];
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index;
}
self.idsByCurrency[currencyCt][currencyId].length--;
self.idIndexById[currencyCt][currencyId][id] = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function transfer(Balance storage _from, Balance storage _to, int256 id,
address currencyCt, uint256 currencyId)
internal
returns (bool)
{
return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Balance tracker
* @notice An ownable to track balances of generic types
*/
contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the fungible balance (amount) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param indexLow The lower index of IDs
/// @param indexUp The upper index of IDs
/// @return The stored balance
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
/// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
/// @notice Get the count of non-fungible IDs of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of IDs
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
/// @notice Gauge whether the ID is included in the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param id The ID of the concerned unit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if ID is included, else false
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
/// @notice Set the balance of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if setting fungible balance, else false
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param ids The ids of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function setIds(address wallet, bytes32 _type, int256[] memory ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
// Update the balance
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Add the given value to the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to add
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if adding fungible balance, else false
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Subtract the given value from the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to subtract
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if subtracting fungible balance, else false
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
/// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
/// @notice Get the count of fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the fungible balance record for the given wallet, type, currency
/// log entry index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of non-fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and record index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of tracked balance types
/// @return The count of tracked balance types
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
/// @notice Get the count of tracked wallets
/// @return The count of tracked wallets
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
/// @notice Get the default full set of balance types
/// @return The set of all balance types
function allBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _allBalanceTypes;
}
/// @notice Get the default set of active balance types
/// @return The set of active balance types
function activeBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _activeBalanceTypes;
}
/// @notice Get the subset of tracked wallets in the given index range
/// @param low The lower index
/// @param up The upper index
/// @return The subset of tracked wallets
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < trackedWallets.length, "No tracked wallets found [BalanceTracker.sol:473]");
require(low <= up, "Bounds parameters mismatch [BalanceTracker.sol:474]");
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title BalanceTrackable
* @notice An ownable that has a balance tracker property
*/
contract BalanceTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
BalanceTracker public balanceTracker;
bool public balanceTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker);
event FreezeBalanceTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the balance tracker contract
/// @param newBalanceTracker The (address of) BalanceTracker contract instance
function setBalanceTracker(BalanceTracker newBalanceTracker)
public
onlyDeployer
notNullAddress(address(newBalanceTracker))
notSameAddresses(address(newBalanceTracker), address(balanceTracker))
{
// Require that this contract has not been frozen
require(!balanceTrackerFrozen, "Balance tracker frozen [BalanceTrackable.sol:43]");
// Update fields
BalanceTracker oldBalanceTracker = balanceTracker;
balanceTracker = newBalanceTracker;
// Emit event
emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeBalanceTracker()
public
onlyDeployer
{
balanceTrackerFrozen = true;
// Emit event
emit FreezeBalanceTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier balanceTrackerInitialized() {
require(address(balanceTracker) != address(0), "Balance tracker not initialized [BalanceTrackable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Transaction tracker
* @notice An ownable to track transactions of generic types
*/
contract TransactionTracker is Ownable, Servable {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct TransactionRecord {
int256 value;
uint256 blockNumber;
address currencyCt;
uint256 currencyId;
}
struct TransactionLog {
TransactionRecord[] records;
mapping(address => mapping(uint256 => uint256[])) recordIndicesByCurrency;
}
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSIT_TRANSACTION_TYPE = "deposit";
string constant public WITHDRAWAL_TRANSACTION_TYPE = "withdrawal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositTransactionType;
bytes32 public withdrawalTransactionType;
mapping(address => mapping(bytes32 => TransactionLog)) private transactionLogByWalletType;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositTransactionType = keccak256(abi.encodePacked(DEPOSIT_TRANSACTION_TYPE));
withdrawalTransactionType = keccak256(abi.encodePacked(WITHDRAWAL_TRANSACTION_TYPE));
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Add a transaction record of the given wallet, type, value and currency
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param value The concerned value (amount of fungible, id of non-fungible)
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function add(address wallet, bytes32 _type, int256 value, address currencyCt,
uint256 currencyId)
public
onlyActiveService
{
transactionLogByWalletType[wallet][_type].records.length++;
uint256 index = transactionLogByWalletType[wallet][_type].records.length - 1;
transactionLogByWalletType[wallet][_type].records[index].value = value;
transactionLogByWalletType[wallet][_type].records[index].blockNumber = block.number;
transactionLogByWalletType[wallet][_type].records[index].currencyCt = currencyCt;
transactionLogByWalletType[wallet][_type].records[index].currencyId = currencyId;
transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId].push(index);
}
/// @notice Get the number of transaction records for the given wallet and type
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @return The count of transaction records
function count(address wallet, bytes32 _type)
public
view
returns (uint256)
{
return transactionLogByWalletType[wallet][_type].records.length;
}
/// @notice Get the transaction record for the given wallet and type by the given index
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param index The concerned log index
/// @return The transaction record
function getByIndex(address wallet, bytes32 _type, uint256 index)
public
view
returns (int256 value, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
TransactionRecord storage entry = transactionLogByWalletType[wallet][_type].records[index];
value = entry.value;
blockNumber = entry.blockNumber;
currencyCt = entry.currencyCt;
currencyId = entry.currencyId;
}
/// @notice Get the transaction record for the given wallet and type by the given block number
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param _blockNumber The concerned block number
/// @return The transaction record
function getByBlockNumber(address wallet, bytes32 _type, uint256 _blockNumber)
public
view
returns (int256 value, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return getByIndex(wallet, _type, _indexByBlockNumber(wallet, _type, _blockNumber));
}
/// @notice Get the number of transaction records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of transaction records
function countByCurrency(address wallet, bytes32 _type, address currencyCt,
uint256 currencyId)
public
view
returns (uint256)
{
return transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId].length;
}
/// @notice Get the transaction record for the given wallet, type and currency by the given index
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param index The concerned log index
/// @return The transaction record
function getByCurrencyIndex(address wallet, bytes32 _type, address currencyCt,
uint256 currencyId, uint256 index)
public
view
returns (int256 value, uint256 blockNumber)
{
uint256 entryIndex = transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId][index];
TransactionRecord storage entry = transactionLogByWalletType[wallet][_type].records[entryIndex];
value = entry.value;
blockNumber = entry.blockNumber;
}
/// @notice Get the transaction record for the given wallet, type and currency by the given block number
/// @param wallet The address of the concerned wallet
/// @param _type The transaction type
/// @param _blockNumber The concerned block number
/// @return The transaction record
function getByCurrencyBlockNumber(address wallet, bytes32 _type, address currencyCt,
uint256 currencyId, uint256 _blockNumber)
public
view
returns (int256 value, uint256 blockNumber)
{
return getByCurrencyIndex(
wallet, _type, currencyCt, currencyId,
_indexByCurrencyBlockNumber(
wallet, _type, currencyCt, currencyId, _blockNumber
)
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _indexByBlockNumber(address wallet, bytes32 _type, uint256 blockNumber)
private
view
returns (uint256)
{
require(
0 < transactionLogByWalletType[wallet][_type].records.length,
"No transactions found for wallet and type [TransactionTracker.sol:187]"
);
for (uint256 i = transactionLogByWalletType[wallet][_type].records.length - 1; i >= 0; i--)
if (blockNumber >= transactionLogByWalletType[wallet][_type].records[i].blockNumber)
return i;
revert();
}
function _indexByCurrencyBlockNumber(address wallet, bytes32 _type, address currencyCt,
uint256 currencyId, uint256 blockNumber)
private
view
returns (uint256)
{
require(
0 < transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId].length,
"No transactions found for wallet, type and currency [TransactionTracker.sol:203]"
);
for (uint256 i = transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId].length - 1; i >= 0; i--) {
uint256 j = transactionLogByWalletType[wallet][_type].recordIndicesByCurrency[currencyCt][currencyId][i];
if (blockNumber >= transactionLogByWalletType[wallet][_type].records[j].blockNumber)
return j;
}
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransactionTrackable
* @notice An ownable that has a transaction tracker property
*/
contract TransactionTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransactionTracker public transactionTracker;
bool public transactionTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransactionTrackerEvent(TransactionTracker oldTransactionTracker, TransactionTracker newTransactionTracker);
event FreezeTransactionTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the transaction tracker contract
/// @param newTransactionTracker The (address of) TransactionTracker contract instance
function setTransactionTracker(TransactionTracker newTransactionTracker)
public
onlyDeployer
notNullAddress(address(newTransactionTracker))
notSameAddresses(address(newTransactionTracker), address(transactionTracker))
{
// Require that this contract has not been frozen
require(!transactionTrackerFrozen, "Transaction tracker frozen [TransactionTrackable.sol:43]");
// Update fields
TransactionTracker oldTransactionTracker = transactionTracker;
transactionTracker = newTransactionTracker;
// Emit event
emit SetTransactionTrackerEvent(oldTransactionTracker, newTransactionTracker);
}
/// @notice Freeze the transaction tracker from further updates
/// @dev This operation can not be undone
function freezeTransactionTracker()
public
onlyDeployer
{
transactionTrackerFrozen = true;
// Emit event
emit FreezeTransactionTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transactionTrackerInitialized() {
require(address(transactionTracker) != address(0), "Transaction track not initialized [TransactionTrackable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Wallet locker
* @notice An ownable to lock and unlock wallets' balance holdings of specific currency(ies)
*/
contract WalletLocker is Ownable, Configurable, AuthorizableServable {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct FungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256 amount;
uint256 visibleTime;
uint256 unlockTime;
}
struct NonFungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256[] ids;
uint256 visibleTime;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => FungibleLock[]) public walletFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyFungibleLockCount;
mapping(address => NonFungibleLock[]) public walletNonFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerNonFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyNonFungibleLockCount;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event LockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event LockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event UnlockFungibleEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Lock the given locked wallet's fungible amount of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param amount The amount to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked amount is visible, a.o. for seizure
function lockFungibleByProxy(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletFungibleLocks[lockedWallet].length);
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletFungibleLocks[lockedWallet][lockIndex - 1].amount = amount;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Lock the given locked wallet's non-fungible IDs of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param ids The IDs to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked ids are visible, a.o. for seizure
function lockNonFungibleByProxy(address lockedWallet, address lockerWallet, int256[] memory ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletNonFungibleLocks[lockedWallet].length);
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids = ids;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Unlock the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Get the number of fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of fungible locks
function fungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletFungibleLocks[wallet].length;
}
/// @notice Get the number of non-fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of non-fungible locks
function nonFungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletNonFungibleLocks[wallet].length;
}
/// @notice Get the fungible amount of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedAmount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
}
/// @notice Get the count of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedIdsCount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids.length;
}
/// @notice Get the set of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet and whose indices are in the given range of indices
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param low The lower ID index
/// @param up The upper ID index
function lockedIdsByIndices(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId,
uint256 low, uint256 up)
public
view
returns (int256[] memory)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return new int256[](0);
NonFungibleLock storage lock = walletNonFungibleLocks[lockedWallet][lockIndex - 1];
if (0 == lock.ids.length)
return new int256[](0);
up = up.clampMax(lock.ids.length - 1);
int256[] memory _ids = new int256[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_ids[i - low] = lock.ids[i];
return _ids;
}
/// @notice Gauge whether the given wallet is locked
/// @param wallet The address of the concerned wallet
/// @return true if wallet is locked, else false
function isLocked(address wallet)
public
view
returns (bool)
{
return 0 < walletFungibleLocks[wallet].length ||
0 < walletNonFungibleLocks[wallet].length;
}
/// @notice Gauge whether the given wallet and currency is locked
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if wallet/currency pair is locked, else false
function isLocked(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < walletCurrencyFungibleLockCount[wallet][currencyCt][currencyId] ||
0 < walletCurrencyNonFungibleLockCount[wallet][currencyCt][currencyId];
}
/// @notice Gauge whether the given locked wallet and currency is locked by the given locker wallet
/// @param lockedWallet The address of the concerned locked wallet
/// @param lockerWallet The address of the concerned locker wallet
/// @return true if lockedWallet is locked by lockerWallet, else false
function isLocked(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] ||
0 < lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
}
//
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256)
{
int256 amount = walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
if (lockIndex < walletFungibleLocks[lockedWallet].length) {
walletFungibleLocks[lockedWallet][lockIndex - 1] =
walletFungibleLocks[lockedWallet][walletFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return amount;
}
function _unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256[] memory)
{
int256[] memory ids = walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids;
if (lockIndex < walletNonFungibleLocks[lockedWallet].length) {
walletNonFungibleLocks[lockedWallet][lockIndex - 1] =
walletNonFungibleLocks[lockedWallet][walletNonFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletNonFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return ids;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title WalletLockable
* @notice An ownable that has a wallet locker property
*/
contract WalletLockable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
WalletLocker public walletLocker;
bool public walletLockerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetWalletLockerEvent(WalletLocker oldWalletLocker, WalletLocker newWalletLocker);
event FreezeWalletLockerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the wallet locker contract
/// @param newWalletLocker The (address of) WalletLocker contract instance
function setWalletLocker(WalletLocker newWalletLocker)
public
onlyDeployer
notNullAddress(address(newWalletLocker))
notSameAddresses(address(newWalletLocker), address(walletLocker))
{
// Require that this contract has not been frozen
require(!walletLockerFrozen, "Wallet locker frozen [WalletLockable.sol:43]");
// Update fields
WalletLocker oldWalletLocker = walletLocker;
walletLocker = newWalletLocker;
// Emit event
emit SetWalletLockerEvent(oldWalletLocker, newWalletLocker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeWalletLocker()
public
onlyDeployer
{
walletLockerFrozen = true;
// Emit event
emit FreezeWalletLockerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier walletLockerInitialized() {
require(address(walletLocker) != address(0), "Wallet locker not initialized [WalletLockable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/**
* @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);
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
/**
* @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 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 ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title RevenueToken
* @dev Implementation of the EIP20 standard token (also known as ERC20 token) with added
* calculation of balance blocks at every transfer.
*/
contract RevenueToken is ERC20Mintable {
using SafeMath for uint256;
bool public mintingDisabled;
address[] public holders;
mapping(address => bool) public holdersMap;
mapping(address => uint256[]) public balances;
mapping(address => uint256[]) public balanceBlocks;
mapping(address => uint256[]) public balanceBlockNumbers;
event DisableMinting();
/**
* @notice Disable further minting
* @dev This operation can not be undone
*/
function disableMinting()
public
onlyMinter
{
mintingDisabled = true;
emit DisableMinting();
}
/**
* @notice 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)
{
require(!mintingDisabled, "Minting disabled [RevenueToken.sol:60]");
// Call super's mint, including event emission
bool minted = super.mint(to, value);
if (minted) {
// Adjust balance blocks
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return minted;
}
/**
* @notice Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address to, uint256 value)
public
returns (bool)
{
// Call super's transfer, including event emission
bool transferred = super.transfer(to, value);
if (transferred) {
// Adjust balance blocks
addBalanceBlocks(msg.sender);
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return transferred;
}
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @dev Beware that to change the approve amount you first have to reduce the addresses'
* allowance to zero by calling `approve(spender, 0)` if it is not already 0 to mitigate the race
* condition described here:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender 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)
{
// Prevent the update of non-zero allowance
require(
0 == value || 0 == allowance(msg.sender, spender),
"Value or allowance non-zero [RevenueToken.sol:121]"
);
// Call super's approve, including event emission
return super.approve(spender, value);
}
/**
* @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
* @return A boolean that indicates if the operation was successful.
*/
function transferFrom(address from, address to, uint256 value)
public
returns (bool)
{
// Call super's transferFrom, including event emission
bool transferred = super.transferFrom(from, to, value);
if (transferred) {
// Adjust balance blocks
addBalanceBlocks(from);
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return transferred;
}
/**
* @notice Calculate the amount of balance blocks, i.e. the area under the curve (AUC) of
* balance as function of block number
* @dev The AUC is used as weight for the share of revenue that a token holder may claim
* @param account The account address for which calculation is done
* @param startBlock The start block number considered
* @param endBlock The end block number considered
* @return The calculated AUC
*/
function balanceBlocksIn(address account, uint256 startBlock, uint256 endBlock)
public
view
returns (uint256)
{
require(startBlock < endBlock, "Bounds parameters mismatch [RevenueToken.sol:173]");
require(account != address(0), "Account is null address [RevenueToken.sol:174]");
if (balanceBlockNumbers[account].length == 0 || endBlock < balanceBlockNumbers[account][0])
return 0;
uint256 i = 0;
while (i < balanceBlockNumbers[account].length && balanceBlockNumbers[account][i] < startBlock)
i++;
uint256 r;
if (i >= balanceBlockNumbers[account].length)
r = balances[account][balanceBlockNumbers[account].length - 1].mul(endBlock.sub(startBlock));
else {
uint256 l = (i == 0) ? startBlock : balanceBlockNumbers[account][i - 1];
uint256 h = balanceBlockNumbers[account][i];
if (h > endBlock)
h = endBlock;
h = h.sub(startBlock);
r = (h == 0) ? 0 : balanceBlocks[account][i].mul(h).div(balanceBlockNumbers[account][i].sub(l));
i++;
while (i < balanceBlockNumbers[account].length && balanceBlockNumbers[account][i] < endBlock) {
r = r.add(balanceBlocks[account][i]);
i++;
}
if (i >= balanceBlockNumbers[account].length)
r = r.add(
balances[account][balanceBlockNumbers[account].length - 1].mul(
endBlock.sub(balanceBlockNumbers[account][balanceBlockNumbers[account].length - 1])
)
);
else if (balanceBlockNumbers[account][i - 1] < endBlock)
r = r.add(
balanceBlocks[account][i].mul(
endBlock.sub(balanceBlockNumbers[account][i - 1])
).div(
balanceBlockNumbers[account][i].sub(balanceBlockNumbers[account][i - 1])
)
);
}
return r;
}
/**
* @notice Get the count of balance updates for the given account
* @return The count of balance updates
*/
function balanceUpdatesCount(address account)
public
view
returns (uint256)
{
return balanceBlocks[account].length;
}
/**
* @notice Get the count of holders
* @return The count of holders
*/
function holdersCount()
public
view
returns (uint256)
{
return holders.length;
}
/**
* @notice Get the subset of holders (optionally with positive balance only) in the given 0 based index range
* @param low The lower inclusive index
* @param up The upper inclusive index
* @param posOnly List only positive balance holders
* @return The subset of positive balance registered holders in the given range
*/
function holdersByIndices(uint256 low, uint256 up, bool posOnly)
public
view
returns (address[] memory)
{
require(low <= up, "Bounds parameters mismatch [RevenueToken.sol:259]");
up = up > holders.length - 1 ? holders.length - 1 : up;
uint256 length = 0;
if (posOnly) {
for (uint256 i = low; i <= up; i++)
if (0 < balanceOf(holders[i]))
length++;
} else
length = up - low + 1;
address[] memory _holders = new address[](length);
uint256 j = 0;
for (uint256 i = low; i <= up; i++)
if (!posOnly || 0 < balanceOf(holders[i]))
_holders[j++] = holders[i];
return _holders;
}
function addBalanceBlocks(address account)
private
{
uint256 length = balanceBlockNumbers[account].length;
balances[account].push(balanceOf(account));
if (0 < length)
balanceBlocks[account].push(
balances[account][length - 1].mul(
block.number.sub(balanceBlockNumbers[account][length - 1])
)
);
else
balanceBlocks[account].push(0);
balanceBlockNumbers[account].push(block.number);
}
}
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(address(this), spender) == 0));
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must equal true).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
require(address(token).isContract());
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success);
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)));
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Balance tracker
* @notice An ownable that allows a beneficiary to extract tokens in
* a number of batches each a given release time
*/
contract TokenMultiTimelock is Ownable {
using SafeERC20 for IERC20;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Release {
uint256 earliestReleaseTime;
uint256 amount;
uint256 blockNumber;
bool done;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
IERC20 public token;
address public beneficiary;
Release[] public releases;
uint256 public totalLockedAmount;
uint256 public executedReleasesCount;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTokenEvent(IERC20 token);
event SetBeneficiaryEvent(address beneficiary);
event DefineReleaseEvent(uint256 earliestReleaseTime, uint256 amount, uint256 blockNumber);
event SetReleaseBlockNumberEvent(uint256 index, uint256 blockNumber);
event ReleaseEvent(uint256 index, uint256 blockNumber, uint256 earliestReleaseTime,
uint256 actualReleaseTime, uint256 amount);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer)
Ownable(deployer)
public
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the address of token
/// @param _token The address of token
function setToken(IERC20 _token)
public
onlyOperator
notNullOrThisAddress(address(_token))
{
// Require that the token has not previously been set
require(address(token) == address(0), "Token previously set [TokenMultiTimelock.sol:73]");
// Update beneficiary
token = _token;
// Emit event
emit SetTokenEvent(token);
}
/// @notice Set the address of beneficiary
/// @param _beneficiary The new address of beneficiary
function setBeneficiary(address _beneficiary)
public
onlyOperator
notNullAddress(_beneficiary)
{
// Update beneficiary
beneficiary = _beneficiary;
// Emit event
emit SetBeneficiaryEvent(beneficiary);
}
/// @notice Define a set of new releases
/// @param earliestReleaseTimes The timestamp after which the corresponding amount may be released
/// @param amounts The amounts to be released
/// @param releaseBlockNumbers The set release block numbers for releases whose earliest release time
/// is in the past
function defineReleases(uint256[] memory earliestReleaseTimes, uint256[] memory amounts, uint256[] memory releaseBlockNumbers)
onlyOperator
public
{
require(
earliestReleaseTimes.length == amounts.length,
"Earliest release times and amounts lengths mismatch [TokenMultiTimelock.sol:105]"
);
require(
earliestReleaseTimes.length >= releaseBlockNumbers.length,
"Earliest release times and release block numbers lengths mismatch [TokenMultiTimelock.sol:109]"
);
// Require that token address has been set
require(address(token) != address(0), "Token not initialized [TokenMultiTimelock.sol:115]");
for (uint256 i = 0; i < earliestReleaseTimes.length; i++) {
// Update the total amount locked by this contract
totalLockedAmount += amounts[i];
// Require that total amount locked is less than or equal to the token balance of
// this contract
require(token.balanceOf(address(this)) >= totalLockedAmount, "Total locked amount overrun [TokenMultiTimelock.sol:123]");
// Retrieve early block number where available
uint256 blockNumber = i < releaseBlockNumbers.length ? releaseBlockNumbers[i] : 0;
// Add release
releases.push(Release(earliestReleaseTimes[i], amounts[i], blockNumber, false));
// Emit event
emit DefineReleaseEvent(earliestReleaseTimes[i], amounts[i], blockNumber);
}
}
/// @notice Get the count of releases
/// @return The number of defined releases
function releasesCount()
public
view
returns (uint256)
{
return releases.length;
}
/// @notice Set the block number of a release that is not done
/// @param index The index of the release
/// @param blockNumber The updated block number
function setReleaseBlockNumber(uint256 index, uint256 blockNumber)
public
onlyBeneficiary
{
// Require that the release is not done
require(!releases[index].done, "Release previously done [TokenMultiTimelock.sol:154]");
// Update the release block number
releases[index].blockNumber = blockNumber;
// Emit event
emit SetReleaseBlockNumberEvent(index, blockNumber);
}
/// @notice Transfers tokens held in the indicated release to beneficiary.
/// @param index The index of the release
function release(uint256 index)
public
onlyBeneficiary
{
// Get the release object
Release storage _release = releases[index];
// Require that this release has been properly defined by having non-zero amount
require(0 < _release.amount, "Release amount not strictly positive [TokenMultiTimelock.sol:173]");
// Require that this release has not already been executed
require(!_release.done, "Release previously done [TokenMultiTimelock.sol:176]");
// Require that the current timestamp is beyond the nominal release time
require(block.timestamp >= _release.earliestReleaseTime, "Block time stamp less than earliest release time [TokenMultiTimelock.sol:179]");
// Set release done
_release.done = true;
// Set release block number if not previously set
if (0 == _release.blockNumber)
_release.blockNumber = block.number;
// Bump number of executed releases
executedReleasesCount++;
// Decrement the total locked amount
totalLockedAmount -= _release.amount;
// Execute transfer
token.safeTransfer(beneficiary, _release.amount);
// Emit event
emit ReleaseEvent(index, _release.blockNumber, _release.earliestReleaseTime, block.timestamp, _release.amount);
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyBeneficiary() {
require(msg.sender == beneficiary, "Message sender not beneficiary [TokenMultiTimelock.sol:204]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
contract RevenueTokenManager is TokenMultiTimelock {
using SafeMathUintLib for uint256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256[] public totalReleasedAmounts;
uint256[] public totalReleasedAmountBlocks;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer)
public
TokenMultiTimelock(deployer)
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Transfers tokens held in the indicated release to beneficiary
/// and update amount blocks
/// @param index The index of the release
function release(uint256 index)
public
onlyBeneficiary
{
// Call release of multi timelock
super.release(index);
// Add amount blocks
_addAmountBlocks(index);
}
/// @notice Calculate the released amount blocks, i.e. the area under the curve (AUC) of
/// release amount as function of block number
/// @param startBlock The start block number considered
/// @param endBlock The end block number considered
/// @return The calculated AUC
function releasedAmountBlocksIn(uint256 startBlock, uint256 endBlock)
public
view
returns (uint256)
{
require(startBlock < endBlock, "Bounds parameters mismatch [RevenueTokenManager.sol:60]");
if (executedReleasesCount == 0 || endBlock < releases[0].blockNumber)
return 0;
uint256 i = 0;
while (i < executedReleasesCount && releases[i].blockNumber < startBlock)
i++;
uint256 r;
if (i >= executedReleasesCount)
r = totalReleasedAmounts[executedReleasesCount - 1].mul(endBlock.sub(startBlock));
else {
uint256 l = (i == 0) ? startBlock : releases[i - 1].blockNumber;
uint256 h = releases[i].blockNumber;
if (h > endBlock)
h = endBlock;
h = h.sub(startBlock);
r = (h == 0) ? 0 : totalReleasedAmountBlocks[i].mul(h).div(releases[i].blockNumber.sub(l));
i++;
while (i < executedReleasesCount && releases[i].blockNumber < endBlock) {
r = r.add(totalReleasedAmountBlocks[i]);
i++;
}
if (i >= executedReleasesCount)
r = r.add(
totalReleasedAmounts[executedReleasesCount - 1].mul(
endBlock.sub(releases[executedReleasesCount - 1].blockNumber)
)
);
else if (releases[i - 1].blockNumber < endBlock)
r = r.add(
totalReleasedAmountBlocks[i].mul(
endBlock.sub(releases[i - 1].blockNumber)
).div(
releases[i].blockNumber.sub(releases[i - 1].blockNumber)
)
);
}
return r;
}
/// @notice Get the block number of the release
/// @param index The index of the release
/// @return The block number of the release;
function releaseBlockNumbers(uint256 index)
public
view
returns (uint256)
{
return releases[index].blockNumber;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _addAmountBlocks(uint256 index)
private
{
// Push total amount released and total released amount blocks
if (0 < index) {
totalReleasedAmounts.push(
totalReleasedAmounts[index - 1] + releases[index].amount
);
totalReleasedAmountBlocks.push(
totalReleasedAmounts[index - 1].mul(
releases[index].blockNumber.sub(releases[index - 1].blockNumber)
)
);
} else {
totalReleasedAmounts.push(releases[index].amount);
totalReleasedAmountBlocks.push(0);
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TokenHolderRevenueFund
* @notice Fund that manages the revenue earned by revenue token holders.
*/
contract TokenHolderRevenueFund is Ownable, AccrualBeneficiary, Servable, TransferControllerManageable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public CLOSE_ACCRUAL_PERIOD_ACTION = "close_accrual_period";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
RevenueTokenManager public revenueTokenManager;
FungibleBalanceLib.Balance private periodAccrual;
CurrenciesLib.Currencies private periodCurrencies;
FungibleBalanceLib.Balance private aggregateAccrual;
CurrenciesLib.Currencies private aggregateCurrencies;
TxHistoryLib.TxHistory private txHistory;
mapping(address => mapping(address => mapping(uint256 => uint256[]))) public claimedAccrualBlockNumbersByWalletCurrency;
mapping(address => mapping(uint256 => uint256[])) public accrualBlockNumbersByCurrency;
mapping(address => mapping(uint256 => mapping(uint256 => int256))) public aggregateAccrualAmountByCurrencyBlockNumber;
mapping(address => FungibleBalanceLib.Balance) private stagedByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetRevenueTokenManagerEvent(RevenueTokenManager oldRevenueTokenManager,
RevenueTokenManager newRevenueTokenManager);
event ReceiveEvent(address wallet, int256 amount, address currencyCt,
uint256 currencyId);
event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId);
event CloseAccrualPeriodEvent(int256 periodAmount, int256 aggregateAmount, address currencyCt,
uint256 currencyId);
event ClaimAndTransferToBeneficiaryEvent(address wallet, string balanceType, int256 amount,
address currencyCt, uint256 currencyId, string standard);
event ClaimAndTransferToBeneficiaryByProxyEvent(address wallet, string balanceType, int256 amount,
address currencyCt, uint256 currencyId, string standard);
event ClaimAndStageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address from, int256 amount, address currencyCt, uint256 currencyId,
string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the revenue token manager contract
/// @param newRevenueTokenManager The (address of) RevenueTokenManager contract instance
function setRevenueTokenManager(RevenueTokenManager newRevenueTokenManager)
public
onlyDeployer
notNullAddress(address(newRevenueTokenManager))
{
if (newRevenueTokenManager != revenueTokenManager) {
// Set new revenue token
RevenueTokenManager oldRevenueTokenManager = revenueTokenManager;
revenueTokenManager = newRevenueTokenManager;
// Emit event
emit SetRevenueTokenManagerEvent(oldRevenueTokenManager, newRevenueTokenManager);
}
}
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balances
periodAccrual.add(amount, address(0), 0);
aggregateAccrual.add(amount, address(0), 0);
// Add currency to in-use lists
periodCurrencies.add(address(0), 0);
aggregateCurrencies.add(address(0), 0);
// Add to transaction history
txHistory.addDeposit(amount, address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt, uint256 currencyId,
string memory standard)
public
{
receiveTokensTo(msg.sender, "", amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [TokenHolderRevenueFund.sol:157]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [TokenHolderRevenueFund.sol:166]");
// Add to balances
periodAccrual.add(amount, currencyCt, currencyId);
aggregateAccrual.add(amount, currencyCt, currencyId);
// Add currency to in-use lists
periodCurrencies.add(currencyCt, currencyId);
aggregateCurrencies.add(currencyCt, currencyId);
// Add to transaction history
txHistory.addDeposit(amount, currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the period accrual balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The current period's accrual balance
function periodAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return periodAccrual.get(currencyCt, currencyId);
}
/// @notice Get the aggregate accrual balance of the given currency, including contribution from the
/// current accrual period
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The aggregate accrual balance
function aggregateAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return aggregateAccrual.get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded in the accrual period
/// @return The number of currencies in the current accrual period
function periodCurrenciesCount()
public
view
returns (uint256)
{
return periodCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range in the current accrual period
function periodCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return periodCurrencies.getByIndices(low, up);
}
/// @notice Get the count of currencies ever recorded
/// @return The number of currencies ever recorded
function aggregateCurrenciesCount()
public
view
returns (uint256)
{
return aggregateCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have ever been recorded
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range ever recorded
function aggregateCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return aggregateCurrencies.getByIndices(low, up);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Get the staged balance of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The staged balance
function stagedBalance(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return stagedByWallet[wallet].get(currencyCt, currencyId);
}
/// @notice Close the current accrual period of the given currencies
/// @param currencies The concerned currencies
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies)
public
onlyEnabledServiceAction(CLOSE_ACCRUAL_PERIOD_ACTION)
{
// Clear period accrual stats
for (uint256 i = 0; i < currencies.length; i++) {
MonetaryTypesLib.Currency memory currency = currencies[i];
// Get the amount of the accrual period
int256 periodAmount = periodAccrual.get(currency.ct, currency.id);
// Register this block number as accrual block number of currency
accrualBlockNumbersByCurrency[currency.ct][currency.id].push(block.number);
// Store the aggregate accrual balance of currency at this block number
aggregateAccrualAmountByCurrencyBlockNumber[currency.ct][currency.id][block.number] = aggregateAccrualBalance(
currency.ct, currency.id
);
if (periodAmount > 0) {
// Reset period accrual of currency
periodAccrual.set(0, currency.ct, currency.id);
// Remove currency from period in-use list
periodCurrencies.removeByCurrency(currency.ct, currency.id);
}
// Emit event
emit CloseAccrualPeriodEvent(
periodAmount,
aggregateAccrualAmountByCurrencyBlockNumber[currency.ct][currency.id][block.number],
currency.ct, currency.id
);
}
}
/// @notice Claim accrual and transfer to beneficiary
/// @param beneficiary The concerned beneficiary
/// @param destWallet The concerned destination wallet of the transfer
/// @param balanceType The target balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function claimAndTransferToBeneficiary(Beneficiary beneficiary, address destWallet, string memory balanceType,
address currencyCt, uint256 currencyId, string memory standard)
public
{
// Claim accrual and obtain the claimed amount
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Transfer ETH to the beneficiary
if (address(0) == currencyCt && 0 == currencyId)
beneficiary.receiveEthersTo.value(uint256(claimedAmount))(destWallet, balanceType);
else {
// Approve of beneficiary
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(claimedAmount), currencyCt, currencyId
)
);
require(success, "Approval by controller failed [TokenHolderRevenueFund.sol:349]");
// Transfer tokens to the beneficiary
beneficiary.receiveTokensTo(destWallet, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
// Emit event
emit ClaimAndTransferToBeneficiaryEvent(msg.sender, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
/// @notice Claim accrual and stage for later withdrawal
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function claimAndStage(address currencyCt, uint256 currencyId)
public
{
// Claim accrual and obtain the claimed amount
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Update staged balance
stagedByWallet[msg.sender].add(claimedAmount, currencyCt, currencyId);
// Emit event
emit ClaimAndStageEvent(msg.sender, claimedAmount, currencyCt, currencyId);
}
/// @notice Withdraw from staged balance of msg.sender
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Require that amount is strictly positive
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [TokenHolderRevenueFund.sol:384]");
// Clamp amount to the max given by staged balance
amount = amount.clampMax(stagedByWallet[msg.sender].get(currencyCt, currencyId));
// Subtract to per-wallet staged balance
stagedByWallet[msg.sender].sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Dispatch by controller failed [TokenHolderRevenueFund.sol:403]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _claim(address wallet, address currencyCt, uint256 currencyId)
private
returns (int256)
{
// Require that at least one accrual period has terminated
require(0 < accrualBlockNumbersByCurrency[currencyCt][currencyId].length, "No terminated accrual period found [TokenHolderRevenueFund.sol:418]");
// Calculate lower block number as last accrual block number claimed for currency c by wallet OR 0
uint256[] storage claimedAccrualBlockNumbers = claimedAccrualBlockNumbersByWalletCurrency[wallet][currencyCt][currencyId];
uint256 bnLow = (0 == claimedAccrualBlockNumbers.length ? 0 : claimedAccrualBlockNumbers[claimedAccrualBlockNumbers.length - 1]);
// Set upper block number as last accrual block number
uint256 bnUp = accrualBlockNumbersByCurrency[currencyCt][currencyId][accrualBlockNumbersByCurrency[currencyCt][currencyId].length - 1];
// Require that lower block number is below upper block number
require(bnLow < bnUp, "Bounds parameters mismatch [TokenHolderRevenueFund.sol:428]");
// Calculate the amount that is claimable in the span between lower and upper block numbers
int256 claimableAmount = aggregateAccrualAmountByCurrencyBlockNumber[currencyCt][currencyId][bnUp]
- (0 == bnLow ? 0 : aggregateAccrualAmountByCurrencyBlockNumber[currencyCt][currencyId][bnLow]);
// Require that claimable amount is strictly positive
require(claimableAmount.isNonZeroPositiveInt256(), "Claimable amount not strictly positive [TokenHolderRevenueFund.sol:435]");
// Retrieve the balance blocks of wallet
int256 walletBalanceBlocks = int256(
RevenueToken(address(revenueTokenManager.token())).balanceBlocksIn(wallet, bnLow, bnUp)
);
// Retrieve the released amount blocks
int256 releasedAmountBlocks = int256(
revenueTokenManager.releasedAmountBlocksIn(bnLow, bnUp)
);
// Calculate the claimed amount
int256 claimedAmount = walletBalanceBlocks.mul_nn(claimableAmount).mul_nn(1e18).div_nn(releasedAmountBlocks.mul_nn(1e18));
// Store upper bound as the last claimed accrual block number for currency
claimedAccrualBlockNumbers.push(bnUp);
// Return the claimed amount
return claimedAmount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Client fund
* @notice Where clients’ crypto is deposited into, staged and withdrawn from.
*/
contract ClientFund is Ownable, Beneficiary, Benefactor, AuthorizableServable, TransferControllerManageable,
BalanceTrackable, TransactionTrackable, WalletLockable {
using SafeMathIntLib for int256;
address[] public seizedWallets;
mapping(address => bool) public seizedByWallet;
TokenHolderRevenueFund public tokenHolderRevenueFund;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTokenHolderRevenueFundEvent(TokenHolderRevenueFund oldTokenHolderRevenueFund,
TokenHolderRevenueFund newTokenHolderRevenueFund);
event ReceiveEvent(address wallet, string balanceType, int256 value, address currencyCt,
uint256 currencyId, string standard);
event WithdrawEvent(address wallet, int256 value, address currencyCt, uint256 currencyId,
string standard);
event StageEvent(address wallet, int256 value, address currencyCt, uint256 currencyId,
string standard);
event UnstageEvent(address wallet, int256 value, address currencyCt, uint256 currencyId,
string standard);
event UpdateSettledBalanceEvent(address wallet, int256 value, address currencyCt,
uint256 currencyId);
event StageToBeneficiaryEvent(address sourceWallet, Beneficiary beneficiary, int256 value,
address currencyCt, uint256 currencyId, string standard);
event TransferToBeneficiaryEvent(address wallet, Beneficiary beneficiary, int256 value,
address currencyCt, uint256 currencyId, string standard);
event SeizeBalancesEvent(address seizedWallet, address seizerWallet, int256 value,
address currencyCt, uint256 currencyId);
event ClaimRevenueEvent(address claimer, string balanceType, address currencyCt,
uint256 currencyId, string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) Beneficiary() Benefactor()
public
{
serviceActivationTimeout = 1 weeks;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the token holder revenue fund contract
/// @param newTokenHolderRevenueFund The (address of) TokenHolderRevenueFund contract instance
function setTokenHolderRevenueFund(TokenHolderRevenueFund newTokenHolderRevenueFund)
public
onlyDeployer
notNullAddress(address(newTokenHolderRevenueFund))
notSameAddresses(address(newTokenHolderRevenueFund), address(tokenHolderRevenueFund))
{
// Set new token holder revenue fund
TokenHolderRevenueFund oldTokenHolderRevenueFund = tokenHolderRevenueFund;
tokenHolderRevenueFund = newTokenHolderRevenueFund;
// Emit event
emit SetTokenHolderRevenueFundEvent(oldTokenHolderRevenueFund, newTokenHolderRevenueFund);
}
/// @notice Fallback function that deposits ethers to msg.sender's deposited balance
function()
external
payable
{
receiveEthersTo(msg.sender, balanceTracker.DEPOSITED_BALANCE_TYPE());
}
/// @notice Receive ethers to the given wallet's balance of the given type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type
function receiveEthersTo(address wallet, string memory balanceType)
public
payable
{
int256 value = SafeMathIntLib.toNonZeroInt256(msg.value);
// Register reception
_receiveTo(wallet, balanceType, value, address(0), 0, true);
// Emit event
emit ReceiveEvent(wallet, balanceType, value, address(0), 0, "");
}
/// @notice Receive token to msg.sender's balance of the given type
/// @dev The wallet must approve of this ClientFund's transfer prior to calling this function
/// @param balanceType The target balance type
/// @param value The value (amount of fungible, id of non-fungible) to receive
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokens(string memory balanceType, int256 value, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, balanceType, value, currencyCt, currencyId, standard);
}
/// @notice Receive token to the given wallet's balance of the given type
/// @dev The wallet must approve of this ClientFund's transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type
/// @param value The value (amount of fungible, id of non-fungible) to receive
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function receiveTokensTo(address wallet, string memory balanceType, int256 value, address currencyCt,
uint256 currencyId, string memory standard)
public
{
require(value.isNonZeroPositiveInt256());
// Get transfer controller
TransferController controller = transferController(currencyCt, standard);
// Execute transfer
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(value), currencyCt, currencyId
)
);
require(success);
// Register reception
_receiveTo(wallet, balanceType, value, currencyCt, currencyId, controller.isFungible());
// Emit event
emit ReceiveEvent(wallet, balanceType, value, currencyCt, currencyId, standard);
}
/// @notice Update the settled balance by the difference between provided off-chain balance amount
/// and deposited on-chain balance, where deposited balance is resolved at the given block number
/// @param wallet The address of the concerned wallet
/// @param value The target balance value (amount of fungible, id of non-fungible), i.e. off-chain balance
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
/// @param blockNumber The block number to which the settled balance is updated
function updateSettledBalance(address wallet, int256 value, address currencyCt, uint256 currencyId,
string memory standard, uint256 blockNumber)
public
onlyAuthorizedService(wallet)
notNullAddress(wallet)
{
require(value.isPositiveInt256());
if (_isFungible(currencyCt, currencyId, standard)) {
(int256 depositedValue,) = balanceTracker.fungibleRecordByBlockNumber(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId, blockNumber
);
balanceTracker.set(
wallet, balanceTracker.settledBalanceType(), value.sub(depositedValue),
currencyCt, currencyId, true
);
} else {
balanceTracker.sub(
wallet, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, false
);
balanceTracker.add(
wallet, balanceTracker.settledBalanceType(), value, currencyCt, currencyId, false
);
}
// Emit event
emit UpdateSettledBalanceEvent(wallet, value, currencyCt, currencyId);
}
/// @notice Stage a value for subsequent withdrawal
/// @param wallet The address of the concerned wallet
/// @param value The value (amount of fungible, id of non-fungible) to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function stage(address wallet, int256 value, address currencyCt, uint256 currencyId,
string memory standard)
public
onlyAuthorizedService(wallet)
{
require(value.isNonZeroPositiveInt256());
// Deduce fungibility
bool fungible = _isFungible(currencyCt, currencyId, standard);
// Subtract stage value from settled, possibly also from deposited
value = _subtractSequentially(wallet, balanceTracker.activeBalanceTypes(), value, currencyCt, currencyId, fungible);
// Add to staged
balanceTracker.add(
wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible
);
// Emit event
emit StageEvent(wallet, value, currencyCt, currencyId, standard);
}
/// @notice Unstage a staged value
/// @param value The value (amount of fungible, id of non-fungible) to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function unstage(int256 value, address currencyCt, uint256 currencyId, string memory standard)
public
{
require(value.isNonZeroPositiveInt256());
// Deduce fungibility
bool fungible = _isFungible(currencyCt, currencyId, standard);
// Subtract unstage value from staged
value = _subtractFromStaged(msg.sender, value, currencyCt, currencyId, fungible);
// Add to deposited
balanceTracker.add(
msg.sender, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, fungible
);
// Emit event
emit UnstageEvent(msg.sender, value, currencyCt, currencyId, standard);
}
/// @notice Stage the value from wallet to the given beneficiary and targeted to wallet
/// @param wallet The address of the concerned wallet
/// @param beneficiary The (address of) concerned beneficiary contract
/// @param value The value (amount of fungible, id of non-fungible) to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function stageToBeneficiary(address wallet, Beneficiary beneficiary, int256 value,
address currencyCt, uint256 currencyId, string memory standard)
public
onlyAuthorizedService(wallet)
{
// Deduce fungibility
bool fungible = _isFungible(currencyCt, currencyId, standard);
// Subtract stage value from settled, possibly also from deposited
value = _subtractSequentially(wallet, balanceTracker.activeBalanceTypes(), value, currencyCt, currencyId, fungible);
// Execute transfer
_transferToBeneficiary(wallet, beneficiary, value, currencyCt, currencyId, standard);
// Emit event
emit StageToBeneficiaryEvent(wallet, beneficiary, value, currencyCt, currencyId, standard);
}
/// @notice Transfer the given value of currency to the given beneficiary without target wallet
/// @param wallet The address of the concerned wallet
/// @param beneficiary The (address of) concerned beneficiary contract
/// @param value The value (amount of fungible, id of non-fungible) to transfer
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function transferToBeneficiary(address wallet, Beneficiary beneficiary, int256 value,
address currencyCt, uint256 currencyId, string memory standard)
public
onlyAuthorizedService(wallet)
{
// Execute transfer
_transferToBeneficiary(wallet, beneficiary, value, currencyCt, currencyId, standard);
// Emit event
emit TransferToBeneficiaryEvent(wallet, beneficiary, value, currencyCt, currencyId, standard);
}
/// @notice Seize balances in the given currency of the given wallet, provided that the wallet
/// is locked by the caller
/// @param wallet The address of the concerned wallet whose balances are seized
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function seizeBalances(address wallet, address currencyCt, uint256 currencyId, string memory standard)
public
{
if (_isFungible(currencyCt, currencyId, standard))
_seizeFungibleBalances(wallet, msg.sender, currencyCt, currencyId);
else
_seizeNonFungibleBalances(wallet, msg.sender, currencyCt, currencyId);
// Add to the store of seized wallets
if (!seizedByWallet[wallet]) {
seizedByWallet[wallet] = true;
seizedWallets.push(wallet);
}
}
/// @notice Withdraw the given amount from staged balance
/// @param value The value (amount of fungible, id of non-fungible) to withdraw
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 value, address currencyCt, uint256 currencyId, string memory standard)
public
{
require(value.isNonZeroPositiveInt256());
// Require that msg.sender and currency is not locked
require(!walletLocker.isLocked(msg.sender, currencyCt, currencyId));
// Deduce fungibility
bool fungible = _isFungible(currencyCt, currencyId, standard);
// Subtract unstage value from staged
value = _subtractFromStaged(msg.sender, value, currencyCt, currencyId, fungible);
// Log record of this transaction
transactionTracker.add(
msg.sender, transactionTracker.withdrawalTransactionType(), value, currencyCt, currencyId
);
// Execute transfer
_transferToWallet(msg.sender, value, currencyCt, currencyId, standard);
// Emit event
emit WithdrawEvent(msg.sender, value, currencyCt, currencyId, standard);
}
/// @notice Get the seized status of given wallet
/// @param wallet The address of the concerned wallet
/// @return true if wallet is seized, false otherwise
function isSeizedWallet(address wallet)
public
view
returns (bool)
{
return seizedByWallet[wallet];
}
/// @notice Get the number of wallets whose funds have been seized
/// @return Number of wallets
function seizedWalletsCount()
public
view
returns (uint256)
{
return seizedWallets.length;
}
/// @notice Claim revenue from token holder revenue fund based on this contract's holdings of the
/// revenue token, this so that revenue may be shared amongst revenue token holders in nahmii
/// @param claimer The concerned address of claimer that will subsequently distribute revenue in nahmii
/// @param balanceType The target balance type for the reception in this contract
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function claimRevenue(address claimer, string memory balanceType, address currencyCt,
uint256 currencyId, string memory standard)
public
onlyOperator
{
tokenHolderRevenueFund.claimAndTransferToBeneficiary(
this, claimer, balanceType,
currencyCt, currencyId, standard
);
emit ClaimRevenueEvent(claimer, balanceType, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _receiveTo(address wallet, string memory balanceType, int256 value, address currencyCt,
uint256 currencyId, bool fungible)
private
{
bytes32 balanceHash = 0 < bytes(balanceType).length ?
keccak256(abi.encodePacked(balanceType)) :
balanceTracker.depositedBalanceType();
// Add to per-wallet staged balance
if (balanceTracker.stagedBalanceType() == balanceHash)
balanceTracker.add(
wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible
);
// Add to per-wallet deposited balance
else if (balanceTracker.depositedBalanceType() == balanceHash) {
balanceTracker.add(
wallet, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, fungible
);
// Log record of this transaction
transactionTracker.add(
wallet, transactionTracker.depositTransactionType(), value, currencyCt, currencyId
);
}
else
revert();
}
function _subtractSequentially(address wallet, bytes32[] memory balanceTypes, int256 value, address currencyCt,
uint256 currencyId, bool fungible)
private
returns (int256)
{
if (fungible)
return _subtractFungibleSequentially(wallet, balanceTypes, value, currencyCt, currencyId);
else
return _subtractNonFungibleSequentially(wallet, balanceTypes, value, currencyCt, currencyId);
}
function _subtractFungibleSequentially(address wallet, bytes32[] memory balanceTypes, int256 amount, address currencyCt, uint256 currencyId)
private
returns (int256)
{
// Require positive amount
require(0 <= amount);
uint256 i;
int256 totalBalanceAmount = 0;
for (i = 0; i < balanceTypes.length; i++)
totalBalanceAmount = totalBalanceAmount.add(
balanceTracker.get(
wallet, balanceTypes[i], currencyCt, currencyId
)
);
// Clamp amount to stage
amount = amount.clampMax(totalBalanceAmount);
int256 _amount = amount;
for (i = 0; i < balanceTypes.length; i++) {
int256 typeAmount = balanceTracker.get(
wallet, balanceTypes[i], currencyCt, currencyId
);
if (typeAmount >= _amount) {
balanceTracker.sub(
wallet, balanceTypes[i], _amount, currencyCt, currencyId, true
);
break;
} else {
balanceTracker.set(
wallet, balanceTypes[i], 0, currencyCt, currencyId, true
);
_amount = _amount.sub(typeAmount);
}
}
return amount;
}
function _subtractNonFungibleSequentially(address wallet, bytes32[] memory balanceTypes, int256 id, address currencyCt, uint256 currencyId)
private
returns (int256)
{
for (uint256 i = 0; i < balanceTypes.length; i++)
if (balanceTracker.hasId(wallet, balanceTypes[i], id, currencyCt, currencyId)) {
balanceTracker.sub(wallet, balanceTypes[i], id, currencyCt, currencyId, false);
break;
}
return id;
}
function _subtractFromStaged(address wallet, int256 value, address currencyCt, uint256 currencyId, bool fungible)
private
returns (int256)
{
if (fungible) {
// Clamp value to unstage
value = value.clampMax(
balanceTracker.get(wallet, balanceTracker.stagedBalanceType(), currencyCt, currencyId)
);
// Require positive value
require(0 <= value);
} else {
// Require that value is included in staged balance
require(balanceTracker.hasId(wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId));
}
// Subtract from deposited balance
balanceTracker.sub(wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible);
return value;
}
function _transferToBeneficiary(address destWallet, Beneficiary beneficiary,
int256 value, address currencyCt, uint256 currencyId, string memory standard)
private
{
require(value.isNonZeroPositiveInt256());
require(isRegisteredBeneficiary(beneficiary));
// Transfer funds to the beneficiary
if (address(0) == currencyCt && 0 == currencyId)
beneficiary.receiveEthersTo.value(uint256(value))(destWallet, "");
else {
// Get transfer controller
TransferController controller = transferController(currencyCt, standard);
// Approve of beneficiary
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(value), currencyCt, currencyId
)
);
require(success);
// Transfer funds to the beneficiary
beneficiary.receiveTokensTo(destWallet, "", value, currencyCt, currencyId, controller.standard());
}
}
function _transferToWallet(address payable wallet,
int256 value, address currencyCt, uint256 currencyId, string memory standard)
private
{
// Transfer ETH
if (address(0) == currencyCt && 0 == currencyId)
wallet.transfer(uint256(value));
else {
// Get transfer controller
TransferController controller = transferController(currencyCt, standard);
// Transfer token
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), wallet, uint256(value), currencyCt, currencyId
)
);
require(success);
}
}
function _seizeFungibleBalances(address lockedWallet, address lockerWallet, address currencyCt,
uint256 currencyId)
private
{
// Get the locked amount
int256 amount = walletLocker.lockedAmount(lockedWallet, lockerWallet, currencyCt, currencyId);
// Require that locked amount is strictly positive
require(amount > 0);
// Subtract stage value from settled, possibly also from deposited
_subtractFungibleSequentially(lockedWallet, balanceTracker.allBalanceTypes(), amount, currencyCt, currencyId);
// Add to staged balance of sender
balanceTracker.add(
lockerWallet, balanceTracker.stagedBalanceType(), amount, currencyCt, currencyId, true
);
// Emit event
emit SeizeBalancesEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
function _seizeNonFungibleBalances(address lockedWallet, address lockerWallet, address currencyCt,
uint256 currencyId)
private
{
// Require that locked ids has entries
uint256 lockedIdsCount = walletLocker.lockedIdsCount(lockedWallet, lockerWallet, currencyCt, currencyId);
require(0 < lockedIdsCount);
// Get the locked amount
int256[] memory ids = walletLocker.lockedIdsByIndices(
lockedWallet, lockerWallet, currencyCt, currencyId, 0, lockedIdsCount - 1
);
for (uint256 i = 0; i < ids.length; i++) {
// Subtract from settled, possibly also from deposited
_subtractNonFungibleSequentially(lockedWallet, balanceTracker.allBalanceTypes(), ids[i], currencyCt, currencyId);
// Add to staged balance of sender
balanceTracker.add(
lockerWallet, balanceTracker.stagedBalanceType(), ids[i], currencyCt, currencyId, false
);
// Emit event
emit SeizeBalancesEvent(lockedWallet, lockerWallet, ids[i], currencyCt, currencyId);
}
}
function _isFungible(address currencyCt, uint256 currencyId, string memory standard)
private
view
returns (bool)
{
return (address(0) == currencyCt && 0 == currencyId) || transferController(currencyCt, standard).isFungible();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title ClientFundable
* @notice An ownable that has a client fund property
*/
contract ClientFundable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
ClientFund public clientFund;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetClientFundEvent(ClientFund oldClientFund, ClientFund newClientFund);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the client fund contract
/// @param newClientFund The (address of) ClientFund contract instance
function setClientFund(ClientFund newClientFund) public
onlyDeployer
notNullAddress(address(newClientFund))
notSameAddresses(address(newClientFund), address(clientFund))
{
// Update field
ClientFund oldClientFund = clientFund;
clientFund = newClientFund;
// Emit event
emit SetClientFundEvent(oldClientFund, newClientFund);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier clientFundInitialized() {
require(address(clientFund) != address(0), "Client fund not initialized [ClientFundable.sol:51]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Community vote
* @notice An oracle for relevant decisions made by the community.
*/
contract CommunityVote is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => bool) doubleSpenderByWallet;
uint256 maxDriipNonce;
uint256 maxNullNonce;
bool dataAvailable;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
dataAvailable = true;
}
//
// Results functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the max driip nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxDriipNonce()
public
view
returns (uint256)
{
return maxDriipNonce;
}
/// @notice Get the max null settlement nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxNullNonce()
public
view
returns (uint256)
{
return maxNullNonce;
}
/// @notice Get the data availability status
/// @return true if data is available
function isDataAvailable()
public
view
returns (bool)
{
return dataAvailable;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title CommunityVotable
* @notice An ownable that has a community vote property
*/
contract CommunityVotable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
CommunityVote public communityVote;
bool public communityVoteFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote);
event FreezeCommunityVoteEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the community vote contract
/// @param newCommunityVote The (address of) CommunityVote contract instance
function setCommunityVote(CommunityVote newCommunityVote)
public
onlyDeployer
notNullAddress(address(newCommunityVote))
notSameAddresses(address(newCommunityVote), address(communityVote))
{
require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]");
// Set new community vote
CommunityVote oldCommunityVote = communityVote;
communityVote = newCommunityVote;
// Emit event
emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote);
}
/// @notice Freeze the community vote from further updates
/// @dev This operation can not be undone
function freezeCommunityVote()
public
onlyDeployer
{
communityVoteFrozen = true;
// Emit event
emit FreezeCommunityVoteEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier communityVoteInitialized() {
require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBenefactor
* @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount
*/
contract AccrualBenefactor is Benefactor {
using SafeMathIntLib for int256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => int256) private _beneficiaryFractionMap;
int256 public totalBeneficiaryFraction;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterAccrualBeneficiaryEvent(Beneficiary beneficiary, int256 fraction);
event DeregisterAccrualBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given accrual beneficiary for the entirety fraction
/// @param beneficiary Address of accrual beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
return registerFractionalBeneficiary(AccrualBeneficiary(address(beneficiary)), ConstantsLib.PARTS_PER());
}
/// @notice Register the given accrual beneficiary for the given fraction
/// @param beneficiary Address of accrual beneficiary to be registered
/// @param fraction Fraction of benefits to be given
function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]");
require(
totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(),
"Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]"
);
if (!super.registerBeneficiary(beneficiary))
return false;
_beneficiaryFractionMap[address(beneficiary)] = fraction;
totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction);
// Emit event
emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction);
return true;
}
/// @notice Deregister the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
if (!super.deregisterBeneficiary(beneficiary))
return false;
address _beneficiary = address(beneficiary);
totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[_beneficiary]);
_beneficiaryFractionMap[_beneficiary] = 0;
// Emit event
emit DeregisterAccrualBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Get the fraction of benefits that is granted the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary
/// @return The beneficiary's fraction
function beneficiaryFraction(AccrualBeneficiary beneficiary)
public
view
returns (int256)
{
return _beneficiaryFractionMap[address(beneficiary)];
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title RevenueFund
* @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst
* accrual beneficiaries.
*/
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance periodAccrual;
CurrenciesLib.Currencies periodCurrencies;
FungibleBalanceLib.Balance aggregateAccrual;
CurrenciesLib.Currencies aggregateCurrencies;
TxHistoryLib.TxHistory private txHistory;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event CloseAccrualPeriodEvent();
event RegisterServiceEvent(address service);
event DeregisterServiceEvent(address service);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balances
periodAccrual.add(amount, address(0), 0);
aggregateAccrual.add(amount, address(0), 0);
// Add currency to stores of currencies
periodCurrencies.add(address(0), 0);
aggregateCurrencies.add(address(0), 0);
// Add to transaction history
txHistory.addDeposit(amount, address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount,
address currencyCt, uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [RevenueFund.sol:124]");
// Add to balances
periodAccrual.add(amount, currencyCt, currencyId);
aggregateAccrual.add(amount, currencyCt, currencyId);
// Add currency to stores of currencies
periodCurrencies.add(currencyCt, currencyId);
aggregateCurrencies.add(currencyCt, currencyId);
// Add to transaction history
txHistory.addDeposit(amount, currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the period accrual balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The current period's accrual balance
function periodAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return periodAccrual.get(currencyCt, currencyId);
}
/// @notice Get the aggregate accrual balance of the given currency, including contribution from the
/// current accrual period
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The aggregate accrual balance
function aggregateAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return aggregateAccrual.get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded in the accrual period
/// @return The number of currencies in the current accrual period
function periodCurrenciesCount()
public
view
returns (uint256)
{
return periodCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range in the current accrual period
function periodCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return periodCurrencies.getByIndices(low, up);
}
/// @notice Get the count of currencies ever recorded
/// @return The number of currencies ever recorded
function aggregateCurrenciesCount()
public
view
returns (uint256)
{
return aggregateCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have ever been recorded
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range ever recorded
function aggregateCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return aggregateCurrencies.getByIndices(low, up);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Close the current accrual period of the given currencies
/// @param currencies The concerned currencies
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies)
public
onlyOperator
{
require(
ConstantsLib.PARTS_PER() == totalBeneficiaryFraction,
"Total beneficiary fraction out of bounds [RevenueFund.sol:236]"
);
// Execute transfer
for (uint256 i = 0; i < currencies.length; i++) {
MonetaryTypesLib.Currency memory currency = currencies[i];
int256 remaining = periodAccrual.get(currency.ct, currency.id);
if (0 >= remaining)
continue;
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
if (beneficiaryFraction(beneficiary) > 0) {
int256 transferable = periodAccrual.get(currency.ct, currency.id)
.mul(beneficiaryFraction(beneficiary))
.div(ConstantsLib.PARTS_PER());
if (transferable > remaining)
transferable = remaining;
if (transferable > 0) {
// Transfer ETH to the beneficiary
if (currency.ct == address(0))
beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), "");
// Transfer token to the beneficiary
else {
TransferController controller = transferController(currency.ct, "");
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id
)
);
require(success, "Approval by controller failed [RevenueFund.sol:274]");
beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, "");
}
remaining = remaining.sub(transferable);
}
}
}
// Roll over remaining to next accrual period
periodAccrual.set(remaining, currency.ct, currency.id);
}
// Close accrual period of accrual beneficiaries
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
// Require that beneficiary fraction is strictly positive
if (0 >= beneficiaryFraction(beneficiary))
continue;
// Close accrual period
beneficiary.closeAccrualPeriod(currencies);
}
// Emit event
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SettlementChallengeTypesLib
* @dev Types for settlement challenges
*/
library SettlementChallengeTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum Status {Qualified, Disqualified}
struct Proposal {
address wallet;
uint256 nonce;
uint256 referenceBlockNumber;
uint256 definitionBlockNumber;
uint256 expirationTime;
// Status
Status status;
// Amounts
Amounts amounts;
// Currency
MonetaryTypesLib.Currency currency;
// Info on challenged driip
Driip challenged;
// True is equivalent to reward coming from wallet's balance
bool walletInitiated;
// True if proposal has been terminated
bool terminated;
// Disqualification
Disqualification disqualification;
}
struct Amounts {
// Cumulative (relative) transfer info
int256 cumulativeTransfer;
// Stage info
int256 stage;
// Balances after amounts have been staged
int256 targetBalance;
}
struct Driip {
// Kind ("payment", "trade", ...)
string kind;
// Hash (of operator)
bytes32 hash;
}
struct Disqualification {
// Challenger
address challenger;
uint256 nonce;
uint256 blockNumber;
// Info on candidate driip
Driip candidate;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeState
* @notice Where null settlements challenge state is managed
*/
contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if initiated by the concerned challenged wallet
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:143]");
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:197]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No settlement found for wallet and currency [NullSettlementChallengeState.sol:226]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber,
proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:269]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:284]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal challenge nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:298]");
return proposals[index - 1].nonce;
}
/// @notice Get the settlement proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:312]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the settlement proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:326]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the settlement proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:340]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:354]");
return proposals[index - 1].status;
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:368]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:382]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the settlement proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:396]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the settlement proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:410]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the settlement proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:424]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the settlement proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:438]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:452]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:466]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated)
private
{
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [NullSettlementChallengeState.sol:478]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [NullSettlementChallengeState.sol:479]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
}
function _removeProposal(uint256 index)
private
returns (bool)
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log record of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId
);
(int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId
);
// Set amount as the sum of deposited and settled
amount = depositedAmount.add(settledAmount);
// Set block number as the latest of deposited and settled
blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementState
* @notice Where null settlement state is managed
*/
contract NullSettlementState is Ownable, Servable, CommunityVotable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public SET_MAX_NULL_NONCE_ACTION = "set_max_null_nonce";
string constant public SET_MAX_NONCE_ACTION = "set_max_nonce";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256 public maxNullNonce;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetMaxNullNonceEvent(uint256 maxNullNonce);
event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency,
uint256 maxNonce);
event UpdateMaxNullNonceFromCommunityVoteEvent(uint256 maxNullNonce);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the max null nonce
/// @param _maxNullNonce The max nonce
function setMaxNullNonce(uint256 _maxNullNonce)
public
onlyEnabledServiceAction(SET_MAX_NULL_NONCE_ACTION)
{
// Update max nonce value
maxNullNonce = _maxNullNonce;
// Emit event
emit SetMaxNullNonceEvent(_maxNullNonce);
}
/// @notice Get the max null nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The max nonce
function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256) {
return walletCurrencyMaxNonce[wallet][currency.ct][currency.id];
}
/// @notice Set the max null nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @param _maxNullNonce The max nonce
function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency,
uint256 _maxNullNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
// Update max nonce value
walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = _maxNullNonce;
// Emit event
emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, _maxNullNonce);
}
/// @notice Update the max null settlement nonce property from CommunityVote contract
function updateMaxNullNonceFromCommunityVote()
public
{
uint256 _maxNullNonce = communityVote.getMaxNullNonce();
if (0 == _maxNullNonce)
return;
maxNullNonce = _maxNullNonce;
// Emit event
emit UpdateMaxNullNonceFromCommunityVoteEvent(maxNullNonce);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementChallengeState
* @notice Where driip settlement challenge state is managed
*/
contract DriipSettlementChallengeState is Ownable, Servable, Configurable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
string constant public QUALIFY_PROPOSAL_ACTION = "qualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
mapping(address => mapping(uint256 => mapping(address => mapping(uint256 => uint256)))) public proposalIndexByWalletNonceCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event DisqualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
event QualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param cumulativeTransferAmount The proposal cumulative transfer amount
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if reward from candidate balance
/// @param challengedHash The candidate driip hash
/// @param challengedKind The candidate driip kind
function initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated, challengedHash, challengedKind
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated, challengedHash, challengedKind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param clearNonce Clear wallet-nonce-currency triplet entry
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce,
bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:163]");
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:223]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:253]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance,
currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice (Re)Qualify a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function qualifyProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(QUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:282]");
// Emit event
emit QualifyProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].disqualification.challenger,
proposals[index - 1].disqualification.nonce,
proposals[index - 1].disqualification.candidate.hash,
proposals[index - 1].disqualification.candidate.kind
);
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
delete proposals[index - 1].disqualification;
}
/// @notice Gauge whether a driip settlement challenge for the given wallet-nonce-currency
/// triplet has been proposed and not later removed
/// @param wallet The address of the concerned wallet
/// @param nonce The wallet nonce
/// @param currency The concerned currency
/// @return true if driip settlement challenge has been, else false
function hasProposal(address wallet, uint256 nonce, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:340]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:355]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the proposal nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:369]");
return proposals[index - 1].nonce;
}
/// @notice Get the proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:383]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal definition block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:397]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:411]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:425]");
return proposals[index - 1].status;
}
/// @notice Get the proposal cumulative transfer amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal cumulative transfer amount
function proposalCumulativeTransferAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:439]");
return proposals[index - 1].amounts.cumulativeTransfer;
}
/// @notice Get the proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:453]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:467]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the proposal challenged hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged hash
function proposalChallengedHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:481]");
return proposals[index - 1].challenged.hash;
}
/// @notice Get the proposal challenged kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged kind
function proposalChallengedKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:495]");
return proposals[index - 1].challenged.kind;
}
/// @notice Get the proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:509]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:523]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:537]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:551]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:565]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:579]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
private
{
// Require that there is no other proposal on the given wallet-nonce-currency triplet
require(
0 == proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id],
"Existing proposal found for wallet, nonce and currency [DriipSettlementChallengeState.sol:592]"
);
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [DriipSettlementChallengeState.sol:598]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [DriipSettlementChallengeState.sol:599]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.cumulativeTransfer = cumulativeTransferAmount;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
proposals[index - 1].challenged.hash = challengedHash;
proposals[index - 1].challenged.kind = challengedKind;
// Update index of wallet-nonce-currency triplet
proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id] = index;
}
function _removeProposal(uint256 index)
private
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlement
* @notice Where null settlement are finalized
*/
contract NullSettlement is Ownable, Configurable, ClientFundable, CommunityVotable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementChallengeState public nullSettlementChallengeState;
NullSettlementState public nullSettlementState;
DriipSettlementChallengeState public driipSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event SetNullSettlementStateEvent(NullSettlementState oldNullSettlementState,
NullSettlementState newNullSettlementState);
event SetDriipSettlementChallengeStateEvent(DriipSettlementChallengeState oldDriipSettlementChallengeState,
DriipSettlementChallengeState newDriipSettlementChallengeState);
event SettleNullEvent(address wallet, address currencyCt, uint256 currencyId, string standard);
event SettleNullByProxyEvent(address proxy, address wallet, address currencyCt,
uint256 currencyId, string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the null settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Set the null settlement state contract
/// @param newNullSettlementState The (address of) NullSettlementState contract instance
function setNullSettlementState(NullSettlementState newNullSettlementState)
public
onlyDeployer
notNullAddress(address(newNullSettlementState))
{
NullSettlementState oldNullSettlementState = nullSettlementState;
nullSettlementState = newNullSettlementState;
emit SetNullSettlementStateEvent(oldNullSettlementState, nullSettlementState);
}
/// @notice Set the driip settlement challenge state contract
/// @param newDriipSettlementChallengeState The (address of) DriipSettlementChallengeState contract instance
function setDriipSettlementChallengeState(DriipSettlementChallengeState newDriipSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newDriipSettlementChallengeState))
{
DriipSettlementChallengeState oldDriipSettlementChallengeState = driipSettlementChallengeState;
driipSettlementChallengeState = newDriipSettlementChallengeState;
emit SetDriipSettlementChallengeStateEvent(oldDriipSettlementChallengeState, driipSettlementChallengeState);
}
/// @notice Settle null
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token to be settled (discarded if settling ETH)
function settleNull(address currencyCt, uint256 currencyId, string memory standard)
public
{
// Settle null
_settleNull(msg.sender, MonetaryTypesLib.Currency(currencyCt, currencyId), standard);
// Emit event
emit SettleNullEvent(msg.sender, currencyCt, currencyId, standard);
}
/// @notice Settle null by proxy
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token to be settled (discarded if settling ETH)
function settleNullByProxy(address wallet, address currencyCt, uint256 currencyId, string memory standard)
public
onlyOperator
{
// Settle null of wallet
_settleNull(wallet, MonetaryTypesLib.Currency(currencyCt, currencyId), standard);
// Emit event
emit SettleNullByProxyEvent(msg.sender, wallet, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _settleNull(address wallet, MonetaryTypesLib.Currency memory currency, string memory standard)
private
{
// Require that there is no overlapping driip settlement challenge
require(
!driipSettlementChallengeState.hasProposal(wallet, currency) ||
driipSettlementChallengeState.hasProposalTerminated(wallet, currency),
"Overlapping driip settlement challenge proposal found [NullSettlement.sol:136]"
);
// Require that null settlement challenge proposal has been initiated
require(nullSettlementChallengeState.hasProposal(wallet, currency), "No proposal found [NullSettlement.sol:143]");
// Require that null settlement challenge proposal has not been terminated already
require(!nullSettlementChallengeState.hasProposalTerminated(wallet, currency), "Proposal found terminated [NullSettlement.sol:146]");
// Require that null settlement challenge proposal has expired
require(nullSettlementChallengeState.hasProposalExpired(wallet, currency), "Proposal found not expired [NullSettlement.sol:149]");
// Require that null settlement challenge qualified
require(SettlementChallengeTypesLib.Status.Qualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
), "Proposal found not qualified [NullSettlement.sol:152]");
// Require that operational mode is normal and data is available, or that nonce is
// smaller than max null nonce
require(configuration.isOperationalModeNormal(), "Not normal operational mode [NullSettlement.sol:158]");
require(communityVote.isDataAvailable(), "Data not available [NullSettlement.sol:159]");
// Get null settlement challenge proposal nonce
uint256 nonce = nullSettlementChallengeState.proposalNonce(wallet, currency);
// If wallet has previously settled balance of the concerned currency with higher
// null settlement nonce, then don't settle again
require(nonce >= nullSettlementState.maxNonceByWalletAndCurrency(wallet, currency), "Nonce deemed smaller than max nonce by wallet and currency [NullSettlement.sol:166]");
// Update settled nonce of wallet and currency
nullSettlementState.setMaxNonceByWalletAndCurrency(wallet, currency, nonce);
// Stage the proposed amount
clientFund.stage(
wallet,
nullSettlementChallengeState.proposalStageAmount(
wallet, currency
),
currency.ct, currency.id, standard
);
// Remove null settlement challenge proposal
nullSettlementChallengeState.terminateProposal(wallet, currency);
}
}
|
Require positive amount Clamp amount to stage
|
function _subtractFungibleSequentially(address wallet, bytes32[] memory balanceTypes, int256 amount, address currencyCt, uint256 currencyId)
private
returns (int256)
{
require(0 <= amount);
uint256 i;
int256 totalBalanceAmount = 0;
for (i = 0; i < balanceTypes.length; i++)
totalBalanceAmount = totalBalanceAmount.add(
balanceTracker.get(
wallet, balanceTypes[i], currencyCt, currencyId
)
);
amount = amount.clampMax(totalBalanceAmount);
int256 _amount = amount;
for (i = 0; i < balanceTypes.length; i++) {
int256 typeAmount = balanceTracker.get(
wallet, balanceTypes[i], currencyCt, currencyId
);
if (typeAmount >= _amount) {
balanceTracker.sub(
wallet, balanceTypes[i], _amount, currencyCt, currencyId, true
);
break;
balanceTracker.set(
wallet, balanceTypes[i], 0, currencyCt, currencyId, true
);
_amount = _amount.sub(typeAmount);
}
}
return amount;
}
| 14,081,012 |
/**
*Submitted for verification at Etherscan.io on 2021-02-06
*/
// SPDX-License-Identifier: GPL
pragma solidity 0.6.12;
interface IPairFeeDistribution {
function addpair(address pair) external;
}
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
library SafeMath256 {
/**
* @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;
}
}
/*
This library defines a decimal floating point number. It has 8 decimal significant digits. Its maximum value is 9.9999999e+15.
And its minimum value is 1.0e-16. The following golang code explains its detail implementation.
func buildPrice(significant int, exponent int) uint32 {
if !(10000000 <= significant && significant <= 99999999) {
panic("Invalid significant")
}
if !(-16 <= exponent && exponent <= 15) {
panic("Invalid exponent")
}
return uint32(((exponent+16)<<27)|significant);
}
func priceToFloat(price uint32) float64 {
exponent := int(price>>27)
significant := float64(price&((1<<27)-1))
return significant * math.Pow10(exponent-23)
}
*/
// A price presented as a rational number
struct RatPrice {
uint numerator; // at most 54bits
uint denominator; // at most 76bits
}
library DecFloat32 {
uint32 public constant MANTISSA_MASK = (1<<27) - 1;
uint32 public constant MAX_MANTISSA = 9999_9999;
uint32 public constant MIN_MANTISSA = 1000_0000;
uint32 public constant MIN_PRICE = MIN_MANTISSA;
uint32 public constant MAX_PRICE = (31<<27)|MAX_MANTISSA;
// 10 ** (i + 1)
function powSmall(uint32 i) internal pure returns (uint) {
uint x = 2695994666777834996822029817977685892750687677375768584125520488993233305610;
return (x >> (32*i)) & ((1<<32)-1);
}
// 10 ** (i * 8)
function powBig(uint32 i) internal pure returns (uint) {
uint y = 3402823669209384634633746076162356521930955161600000001;
return (y >> (64*i)) & ((1<<64)-1);
}
// if price32=( 0<<27)|12345678 then numerator=12345678 denominator=100000000000000000000000
// if price32=( 1<<27)|12345678 then numerator=12345678 denominator=10000000000000000000000
// if price32=( 2<<27)|12345678 then numerator=12345678 denominator=1000000000000000000000
// if price32=( 3<<27)|12345678 then numerator=12345678 denominator=100000000000000000000
// if price32=( 4<<27)|12345678 then numerator=12345678 denominator=10000000000000000000
// if price32=( 5<<27)|12345678 then numerator=12345678 denominator=1000000000000000000
// if price32=( 6<<27)|12345678 then numerator=12345678 denominator=100000000000000000
// if price32=( 7<<27)|12345678 then numerator=12345678 denominator=10000000000000000
// if price32=( 8<<27)|12345678 then numerator=12345678 denominator=1000000000000000
// if price32=( 9<<27)|12345678 then numerator=12345678 denominator=100000000000000
// if price32=(10<<27)|12345678 then numerator=12345678 denominator=10000000000000
// if price32=(11<<27)|12345678 then numerator=12345678 denominator=1000000000000
// if price32=(12<<27)|12345678 then numerator=12345678 denominator=100000000000
// if price32=(13<<27)|12345678 then numerator=12345678 denominator=10000000000
// if price32=(14<<27)|12345678 then numerator=12345678 denominator=1000000000
// if price32=(15<<27)|12345678 then numerator=12345678 denominator=100000000
// if price32=(16<<27)|12345678 then numerator=12345678 denominator=10000000
// if price32=(17<<27)|12345678 then numerator=12345678 denominator=1000000
// if price32=(18<<27)|12345678 then numerator=12345678 denominator=100000
// if price32=(19<<27)|12345678 then numerator=12345678 denominator=10000
// if price32=(20<<27)|12345678 then numerator=12345678 denominator=1000
// if price32=(21<<27)|12345678 then numerator=12345678 denominator=100
// if price32=(22<<27)|12345678 then numerator=12345678 denominator=10
// if price32=(23<<27)|12345678 then numerator=12345678 denominator=1
// if price32=(24<<27)|12345678 then numerator=123456780 denominator=1
// if price32=(25<<27)|12345678 then numerator=1234567800 denominator=1
// if price32=(26<<27)|12345678 then numerator=12345678000 denominator=1
// if price32=(27<<27)|12345678 then numerator=123456780000 denominator=1
// if price32=(28<<27)|12345678 then numerator=1234567800000 denominator=1
// if price32=(29<<27)|12345678 then numerator=12345678000000 denominator=1
// if price32=(30<<27)|12345678 then numerator=123456780000000 denominator=1
// if price32=(31<<27)|12345678 then numerator=1234567800000000 denominator=1
function expandPrice(uint32 price32) internal pure returns (RatPrice memory) {
uint s = price32&((1<<27)-1);
uint32 a = price32 >> 27;
RatPrice memory price;
if(a >= 24) {
uint32 b = a - 24;
price.numerator = s * powSmall(b);
price.denominator = 1;
} else if(a == 23) {
price.numerator = s;
price.denominator = 1;
} else {
uint32 b = 22 - a;
price.numerator = s;
price.denominator = powSmall(b&0x7) * powBig(b>>3);
}
return price;
}
function getExpandPrice(uint price) internal pure returns(uint numerator, uint denominator) {
uint32 m = uint32(price) & MANTISSA_MASK;
require(MIN_MANTISSA <= m && m <= MAX_MANTISSA, "Invalid Price");
RatPrice memory actualPrice = expandPrice(uint32(price));
return (actualPrice.numerator, actualPrice.denominator);
}
}
library ProxyData {
uint public constant COUNT = 5;
uint public constant INDEX_FACTORY = 0;
uint public constant INDEX_MONEY_TOKEN = 1;
uint public constant INDEX_STOCK_TOKEN = 2;
uint public constant INDEX_GRA = 3;
uint public constant INDEX_OTHER = 4;
uint public constant OFFSET_PRICE_DIV = 0;
uint public constant OFFSET_PRICE_MUL = 64;
uint public constant OFFSET_STOCK_UNIT = 64+64;
uint public constant OFFSET_IS_ONLY_SWAP = 64+64+64;
function factory(uint[5] memory proxyData) internal pure returns (address) {
return address(proxyData[INDEX_FACTORY]);
}
function money(uint[5] memory proxyData) internal pure returns (address) {
return address(proxyData[INDEX_MONEY_TOKEN]);
}
function stock(uint[5] memory proxyData) internal pure returns (address) {
return address(proxyData[INDEX_STOCK_TOKEN]);
}
function graContract(uint[5] memory proxyData) internal pure returns (address) {
return address(proxyData[INDEX_GRA]);
}
function priceMul(uint[5] memory proxyData) internal pure returns (uint64) {
return uint64(proxyData[INDEX_OTHER]>>OFFSET_PRICE_MUL);
}
function priceDiv(uint[5] memory proxyData) internal pure returns (uint64) {
return uint64(proxyData[INDEX_OTHER]>>OFFSET_PRICE_DIV);
}
function stockUnit(uint[5] memory proxyData) internal pure returns (uint64) {
return uint64(proxyData[INDEX_OTHER]>>OFFSET_STOCK_UNIT);
}
function isOnlySwap(uint[5] memory proxyData) internal pure returns (bool) {
return uint8(proxyData[INDEX_OTHER]>>OFFSET_IS_ONLY_SWAP) != 0;
}
function fill(uint[5] memory proxyData, uint expectedCallDataSize) internal pure {
uint size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := calldatasize()
}
require(size == expectedCallDataSize, "INVALID_CALLDATASIZE");
// solhint-disable-next-line no-inline-assembly
assembly {
let offset := sub(size, 160)
calldatacopy(proxyData, offset, 160)
}
}
}
interface IGraSwapFactory {
event PairCreated(address indexed pair, address stock, address money, bool isOnlySwap);
function createPair(address stock, address money, bool isOnlySwap) external returns (address pair);
function setFeeToAddresses(address _feeTo_1, address _feeTo_2, address _feeToPrivate) external;
function setFeeToSetter(address) external;
function setFeeBPS(uint32 bps) external;
function setPairLogic(address implLogic) external;
function allPairsLength() external view returns (uint);
function feeTo_1() external view returns (address);
function feeTo_2() external view returns (address);
function feeToPrivate() external view returns (address);
function feeToSetter() external view returns (address);
function feeBPS() external view returns (uint32);
function pairLogic() external returns (address);
function getTokensFromPair(address pair) external view returns (address stock, address money);
function tokensToPair(address stock, address money, bool isOnlySwap) external view returns (address pair);
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IGraSwapBlackList {
// event OwnerChanged(address);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event AddedBlackLists(address[]);
event RemovedBlackLists(address[]);
function owner()external view returns (address);
// function newOwner()external view returns (address);
function isBlackListed(address)external view returns (bool);
// function changeOwner(address ownerToSet) external;
// function updateOwner() external;
function transferOwnership(address newOwner) external;
function addBlackLists(address[] calldata accounts)external;
function removeBlackLists(address[] calldata accounts)external;
}
interface IGraWhiteList {
event AppendWhiter(address adder);
event RemoveWhiter(address remover);
function appendWhiter(address account) external;
function removeWhiter(address account) external;
function isWhiter(address account) external;
function isNotWhiter(address account) external;
}
interface IGraSwapToken is IERC20, IGraSwapBlackList, IGraWhiteList{
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
// function multiTransfer(uint256[] calldata mixedAddrVal) external returns (bool);
function batchTransfer(address[] memory addressList, uint256[] memory amountList) external returns (bool);
}
interface IGraSwapERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IGraSwapPool {
// more liquidity was minted
event Mint(address indexed sender, uint stockAndMoneyAmount, address indexed to);
// liquidity was burned
event Burn(address indexed sender, uint stockAndMoneyAmount, address indexed to);
// amounts of reserved stock and money in this pair changed
event Sync(uint reserveStockAndMoney);
function internalStatus() external view returns(uint[3] memory res);
function getReserves() external view returns (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID);
function getBooked() external view returns (uint112 bookedStock, uint112 bookedMoney, uint32 firstBuyID);
function stock() external returns (address);
function money() external returns (address);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint stockAmount, uint moneyAmount);
function skim(address to) external;
function sync() external;
}
interface IGraSwapPair {
event NewLimitOrder(uint data); // new limit order was sent by an account
event NewMarketOrder(uint data); // new market order was sent by an account
event OrderChanged(uint data); // old orders in orderbook changed
event DealWithPool(uint data); // new order deal with the AMM pool
event RemoveOrder(uint data); // an order was removed from the orderbook
// Return three prices in rational number form, i.e., numerator/denominator.
// They are: the first sell order's price; the first buy order's price; the current price of the AMM pool.
function getPrices() external returns (
uint firstSellPriceNumerator,
uint firstSellPriceDenominator,
uint firstBuyPriceNumerator,
uint firstBuyPriceDenominator,
uint poolPriceNumerator,
uint poolPriceDenominator);
// This function queries a list of orders in orderbook. It starts from 'id' and iterates the single-linked list, util it reaches the end,
// or until it has found 'maxCount' orders. If 'id' is 0, it starts from the beginning of the single-linked list.
// It may cost a lot of gas. So you'd not to call in on chain. It is mainly for off-chain query.
// The first uint256 returned by this function is special: the lowest 24 bits is the first order's id and the the higher bits is block height.
// THe other uint256s are all corresponding to an order record of the single-linked list.
function getOrderList(bool isBuy, uint32 id, uint32 maxCount) external view returns (uint[] memory);
// remove an order from orderbook and return its booked (i.e. frozen) money to maker
// 'id' points to the order to be removed
// prevKey points to 3 previous orders in the single-linked list
function removeOrder(bool isBuy, uint32 id, uint72 positionID) external;
function removeOrders(uint[] calldata rmList) external;
// Try to deal a new limit order or insert it into orderbook
// its suggested order id is 'id' and suggested positions are in 'prevKey'
// prevKey points to 3 existing orders in the single-linked list
// the order's sender is 'sender'. the order's amount is amount*stockUnit, which is the stock amount to be sold or bought.
// the order's price is 'price32', which is decimal floating point value.
function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32, uint32 id, uint72 prevKey) external payable;
// Try to deal a new market order. 'sender' pays 'inAmount' of 'inputToken', in exchange of the other token kept by this pair
function addMarketOrder(address inputToken, address sender, uint112 inAmount) external payable returns (uint);
// Given the 'amount' of stock and decimal floating point price 'price32', calculate the 'stockAmount' and 'moneyAmount' to be traded
function calcStockAndMoney(uint64 amount, uint32 price32) external pure returns (uint stockAmount, uint moneyAmount);
}
abstract contract GraSwapERC20 is IGraSwapERC20 {
using SafeMath256 for uint;
uint internal _unusedVar0;
uint internal _unusedVar1;
uint internal _unusedVar2;
uint internal _unusedVar3;
uint internal _unusedVar4;
uint internal _unusedVar5;
uint internal _unusedVar6;
uint internal _unusedVar7;
uint internal _unusedVar8;
uint internal _unusedVar9;
uint internal _unlocked = 1;
modifier lock() {
require(_unlocked == 1, "GraSwap: LOCKED");
_unlocked = 0;
_;
_unlocked = 1;
}
string private constant _NAME = "GraSwap-Share";
uint8 private constant _DECIMALS = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
function symbol() virtual external override returns (string memory);
function name() external view override returns (string memory) {
return _NAME;
}
function decimals() external view override returns (uint8) {
return _DECIMALS;
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external override returns (bool) {
if (allowance[from][msg.sender] != uint(- 1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
// An order can be compressed into 256 bits and saved using one SSTORE instruction
// The orders form a single-linked list. The preceding order points to the following order with nextID
struct Order { //total 256 bits
address sender; //160 bits, sender creates this order
uint32 price; // 32-bit decimal floating point number
uint64 amount; // 42 bits are used, the stock amount to be sold or bought
uint32 nextID; // 22 bits are used
}
// When the match engine of orderbook runs, it uses follow context to cache data in memory
struct Context {
// this order is a limit order
bool isLimitOrder;
// the new order's id, it is only used when a limit order is not fully dealt
uint32 newOrderID;
// for buy-order, it's remained money amount; for sell-order, it's remained stock amount
uint remainAmount;
// it points to the first order in the opposite order book against current order
uint32 firstID;
// it points to the first order in the buy-order book
uint32 firstBuyID;
// it points to the first order in the sell-order book
uint32 firstSellID;
// the amount goes into the pool, for buy-order, it's money amount; for sell-order, it's stock amount
uint amountIntoPool;
// the total dealt money and stock in the order book
uint dealMoneyInBook;
uint dealStockInBook;
// cache these values from storage to memory
uint reserveMoney;
uint reserveStock;
uint bookedMoney;
uint bookedStock;
// reserveMoney or reserveStock is changed
bool reserveChanged;
// the taker has dealt in the orderbook
bool hasDealtInOrderBook;
// the current taker order
Order order;
// the following data come from proxy
uint64 stockUnit;
uint64 priceMul;
uint64 priceDiv;
address stockToken;
address moneyToken;
address graContract;
address factory;
}
// GraSwapPair combines a Uniswap-like AMM and an orderbook
abstract contract GraSwapPool is GraSwapERC20, IGraSwapPool {
using SafeMath256 for uint;
uint private constant _MINIMUM_LIQUIDITY = 10 ** 3;
bytes4 internal constant _SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
// reserveMoney and reserveStock are both uint112, id is 22 bits; they are compressed into a uint256 word
uint internal _reserveStockAndMoneyAndFirstSellID;
// bookedMoney and bookedStock are both uint112, id is 22 bits; they are compressed into a uint256 word
uint internal _bookedStockAndMoneyAndFirstBuyID;
uint private _kLast;
uint32 private constant _OS = 2; // owner's share
uint32 private constant _LS = 3; // liquidity-provider's share
function internalStatus() external override view returns(uint[3] memory res) {
res[0] = _reserveStockAndMoneyAndFirstSellID;
res[1] = _bookedStockAndMoneyAndFirstBuyID;
res[2] = _kLast;
}
function stock() external override returns (address) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0));
return ProxyData.stock(proxyData);
}
function money() external override returns (address) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0));
return ProxyData.money(proxyData);
}
// the following 4 functions load&store compressed storage
function getReserves() public override view returns (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) {
uint temp = _reserveStockAndMoneyAndFirstSellID;
reserveStock = uint112(temp);
reserveMoney = uint112(temp>>112);
firstSellID = uint32(temp>>224);
}
function _setReserves(uint stockAmount, uint moneyAmount, uint32 firstSellID) internal {
require(stockAmount < uint(1<<112) && moneyAmount < uint(1<<112), "GraSwap: OVERFLOW");
uint temp = (moneyAmount<<112)|stockAmount;
emit Sync(temp);
temp = (uint(firstSellID)<<224)| temp;
_reserveStockAndMoneyAndFirstSellID = temp;
}
function getBooked() public override view returns (uint112 bookedStock, uint112 bookedMoney, uint32 firstBuyID) {
uint temp = _bookedStockAndMoneyAndFirstBuyID;
bookedStock = uint112(temp);
bookedMoney = uint112(temp>>112);
firstBuyID = uint32(temp>>224);
}
function _setBooked(uint stockAmount, uint moneyAmount, uint32 firstBuyID) internal {
require(stockAmount < uint(1<<112) && moneyAmount < uint(1<<112), "GraSwap: OVERFLOW");
_bookedStockAndMoneyAndFirstBuyID = (uint(firstBuyID)<<224)|(moneyAmount<<112)|stockAmount;
}
function _myBalance(address token) internal view returns (uint) {
if(token==address(0)) {
return address(this).balance;
} else {
return IERC20(token).balanceOf(address(this));
}
}
// safely transfer ERC20 tokens, or ETH (when token==0)
function _safeTransfer(address token, address to, uint value, address graContract) internal {
if(value==0) {return;}
if(token==address(0)) {
// limit gas to 9000 to prevent gastoken attacks
// solhint-disable-next-line avoid-low-level-calls
to.call{value: value, gas: 9000}(new bytes(0)); //we ignore its return value purposely
return;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(_SELECTOR, to, value));
success = success && (data.length == 0 || abi.decode(data, (bool)));
if(!success) { // for failsafe
address graContractOwner = IGraSwapToken(graContract).owner();
// solhint-disable-next-line avoid-low-level-calls
(success, data) = token.call(abi.encodeWithSelector(_SELECTOR, graContractOwner, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "GraSwap: TRANSFER_FAILED");
}
}
// Give feeToAddresses some liquidity tokens if K got increased since last liquidity-changing
function _mintFee(uint112 _reserve0, uint112 _reserve1, uint[5] memory proxyData) private returns (bool feeOn) {
address feeTo_1 = IGraSwapFactory(ProxyData.factory(proxyData)).feeTo_1();
address feeTo_2 = IGraSwapFactory(ProxyData.factory(proxyData)).feeTo_2();
address feeToPrivate = IGraSwapFactory(ProxyData.factory(proxyData)).feeToPrivate();
feeOn = (feeTo_1 != address(0) && feeTo_2 != address(0) && feeToPrivate != address(0));
uint kLast = _kLast;
// gas savings to use cached kLast
if (feeOn) {
if (kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast)).mul(_OS);
uint denominator = rootK.mul(_LS).add(rootKLast.mul(_OS));
uint liquidity = numerator / denominator;
if (liquidity > 0) {
uint liquidity_p1 = liquidity.div(4); // 10%
uint liquidity_p2 = liquidity.div(8); // 5%
uint liquidity_p3 = liquidity.mul(5).div(8); // 25%
if (liquidity_p1 > 0) {
_mint(feeTo_1, liquidity_p1);
}
if (liquidity_p2 > 0) {
_mint(feeTo_2, liquidity_p2);
}
if (liquidity_p2 > 0) {
_mint(feeToPrivate, liquidity_p3);
}
}
}
}
} else if (kLast != 0) {
_kLast = 0;
}
}
// mint new liquidity tokens to 'to'
function mint(address to) external override lock returns (uint liquidity) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1));
(uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves();
(uint112 bookedStock, uint112 bookedMoney, ) = getBooked();
uint stockBalance = _myBalance(ProxyData.stock(proxyData));
uint moneyBalance = _myBalance(ProxyData.money(proxyData));
require(stockBalance >= uint(bookedStock) + uint(reserveStock) &&
moneyBalance >= uint(bookedMoney) + uint(reserveMoney), "GraSwap: INVALID_BALANCE");
stockBalance -= uint(bookedStock);
moneyBalance -= uint(bookedMoney);
uint stockAmount = stockBalance - uint(reserveStock);
uint moneyAmount = moneyBalance - uint(reserveMoney);
bool feeOn = _mintFee(reserveStock, reserveMoney, proxyData);
uint _totalSupply = totalSupply;
// gas savings by caching totalSupply in memory,
// must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(stockAmount.mul(moneyAmount)).sub(_MINIMUM_LIQUIDITY);
_mint(address(0), _MINIMUM_LIQUIDITY);
// permanently lock the first _MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(stockAmount.mul(_totalSupply) / uint(reserveStock),
moneyAmount.mul(_totalSupply) / uint(reserveMoney));
}
require(liquidity > 0, "GraSwap: INSUFFICIENT_MINTED");
_mint(to, liquidity);
_setReserves(stockBalance, moneyBalance, firstSellID);
if (feeOn) _kLast = stockBalance.mul(moneyBalance);
emit Mint(msg.sender, (moneyAmount<<112)|stockAmount, to);
}
// burn liquidity tokens and send stock&money to 'to'
function burn(address to) external override lock returns (uint stockAmount, uint moneyAmount) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1));
(uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves();
(uint bookedStock, uint bookedMoney, ) = getBooked();
uint stockBalance = _myBalance(ProxyData.stock(proxyData)).sub(bookedStock);
uint moneyBalance = _myBalance(ProxyData.money(proxyData)).sub(bookedMoney);
require(stockBalance >= uint(reserveStock) && moneyBalance >= uint(reserveMoney), "GraSwap: INVALID_BALANCE");
bool feeOn = _mintFee(reserveStock, reserveMoney, proxyData);
{
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
uint liquidity = balanceOf[address(this)]; // we're sure liquidity < totalSupply
stockAmount = liquidity.mul(stockBalance) / _totalSupply;
moneyAmount = liquidity.mul(moneyBalance) / _totalSupply;
require(stockAmount > 0 && moneyAmount > 0, "GraSwap: INSUFFICIENT_BURNED");
//_burn(address(this), liquidity);
balanceOf[address(this)] = 0;
totalSupply = totalSupply.sub(liquidity);
emit Transfer(address(this), address(0), liquidity);
}
address graContract = ProxyData.graContract(proxyData);
_safeTransfer(ProxyData.stock(proxyData), to, stockAmount, graContract);
_safeTransfer(ProxyData.money(proxyData), to, moneyAmount, graContract);
stockBalance = stockBalance - stockAmount;
moneyBalance = moneyBalance - moneyAmount;
_setReserves(stockBalance, moneyBalance, firstSellID);
if (feeOn) _kLast = stockBalance.mul(moneyBalance);
emit Burn(msg.sender, (moneyAmount<<112)|stockAmount, to);
}
// take the extra money&stock in this pair to 'to'
function skim(address to) external override lock {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1));
address stockToken = ProxyData.stock(proxyData);
address moneyToken = ProxyData.money(proxyData);
(uint112 reserveStock, uint112 reserveMoney, ) = getReserves();
(uint bookedStock, uint bookedMoney, ) = getBooked();
uint balanceStock = _myBalance(stockToken);
uint balanceMoney = _myBalance(moneyToken);
require(balanceStock >= uint(bookedStock) + uint(reserveStock) &&
balanceMoney >= uint(bookedMoney) + uint(reserveMoney), "GraSwap: INVALID_BALANCE");
address graContract = ProxyData.graContract(proxyData);
_safeTransfer(stockToken, to, balanceStock-reserveStock-bookedStock, graContract);
_safeTransfer(moneyToken, to, balanceMoney-reserveMoney-bookedMoney, graContract);
}
// sync-up reserve stock&money in pool according to real balance
function sync() external override lock {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0));
(, , uint32 firstSellID) = getReserves();
(uint bookedStock, uint bookedMoney, ) = getBooked();
uint balanceStock = _myBalance(ProxyData.stock(proxyData));
uint balanceMoney = _myBalance(ProxyData.money(proxyData));
require(balanceStock >= bookedStock && balanceMoney >= bookedMoney, "GraSwap: INVALID_BALANCE");
_setReserves(balanceStock-bookedStock, balanceMoney-bookedMoney, firstSellID);
}
}
contract GraSwapPair is GraSwapPool, IGraSwapPair {
// the orderbooks. Gas is saved when using array to store them instead of mapping
uint[1<<22] private _sellOrders;
uint[1<<22] private _buyOrders;
uint32 private constant _MAX_ID = (1<<22)-1; // the maximum value of an order ID
function _expandPrice(uint32 price32, uint[5] memory proxyData) private pure returns (RatPrice memory price) {
price = DecFloat32.expandPrice(price32);
price.numerator *= ProxyData.priceMul(proxyData);
price.denominator *= ProxyData.priceDiv(proxyData);
}
function _expandPrice(Context memory ctx, uint32 price32) private pure returns (RatPrice memory price) {
price = DecFloat32.expandPrice(price32);
price.numerator *= ctx.priceMul;
price.denominator *= ctx.priceDiv;
}
function symbol() external override returns (string memory) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0));
string memory s = "ETH";
address stock = ProxyData.stock(proxyData);
if(stock != address(0)) {
s = IERC20(stock).symbol();
}
string memory m = "ETH";
address money = ProxyData.money(proxyData);
if(money != address(0)) {
m = IERC20(money).symbol();
}
return string(abi.encodePacked(s, "/", m)); //to concat strings
}
// when emitting events, solidity's ABI pads each entry to uint256, which is so wasteful
// we compress the entries into one uint256 to save gas
function _emitNewLimitOrder(
uint64 addressLow, /*255~192*/
uint64 totalStockAmount, /*191~128*/
uint64 remainedStockAmount, /*127~64*/
uint32 price, /*63~32*/
uint32 orderID, /*31~8*/
bool isBuy /*7~0*/) private {
uint data = uint(addressLow);
data = (data<<64) | uint(totalStockAmount);
data = (data<<64) | uint(remainedStockAmount);
data = (data<<32) | uint(price);
data = (data<<32) | uint(orderID<<8);
if(isBuy) {
data = data | 1;
}
emit NewLimitOrder(data);
}
function _emitNewMarketOrder(
uint136 addressLow, /*255~120*/
uint112 amount, /*119~8*/
bool isBuy /*7~0*/) private {
uint data = uint(addressLow);
data = (data<<112) | uint(amount);
data = data<<8;
if(isBuy) {
data = data | 1;
}
emit NewMarketOrder(data);
}
function _emitOrderChanged(
uint64 makerLastAmount, /*159~96*/
uint64 makerDealAmount, /*95~32*/
uint32 makerOrderID, /*31~8*/
bool isBuy /*7~0*/) private {
uint data = uint(makerLastAmount);
data = (data<<64) | uint(makerDealAmount);
data = (data<<32) | uint(makerOrderID<<8);
if(isBuy) {
data = data | 1;
}
emit OrderChanged(data);
}
function _emitDealWithPool(
uint112 inAmount, /*131~120*/
uint112 outAmount,/*119~8*/
bool isBuy/*7~0*/) private {
uint data = uint(inAmount);
data = (data<<112) | uint(outAmount);
data = data<<8;
if(isBuy) {
data = data | 1;
}
emit DealWithPool(data);
}
function _emitRemoveOrder(
uint64 remainStockAmount, /*95~32*/
uint32 orderID, /*31~8*/
bool isBuy /*7~0*/) private {
uint data = uint(remainStockAmount);
data = (data<<32) | uint(orderID<<8);
if(isBuy) {
data = data | 1;
}
emit RemoveOrder(data);
}
// compress an order into a 256b integer
function _order2uint(Order memory order) internal pure returns (uint) {
uint n = uint(order.sender);
n = (n<<32) | order.price;
n = (n<<42) | order.amount;
n = (n<<22) | order.nextID;
return n;
}
// extract an order from a 256b integer
function _uint2order(uint n) internal pure returns (Order memory) {
Order memory order;
order.nextID = uint32(n & ((1<<22)-1));
n = n >> 22;
order.amount = uint64(n & ((1<<42)-1));
n = n >> 42;
order.price = uint32(n & ((1<<32)-1));
n = n >> 32;
order.sender = address(n);
return order;
}
// returns true if this order exists
function _hasOrder(bool isBuy, uint32 id) internal view returns (bool) {
if(isBuy) {
return _buyOrders[id] != 0;
} else {
return _sellOrders[id] != 0;
}
}
// load an order from storage, converting its compressed form into an Order struct
function _getOrder(bool isBuy, uint32 id) internal view returns (Order memory order, bool findIt) {
if(isBuy) {
order = _uint2order(_buyOrders[id]);
return (order, order.price != 0);
} else {
order = _uint2order(_sellOrders[id]);
return (order, order.price != 0);
}
}
// save an order to storage, converting it into compressed form
function _setOrder(bool isBuy, uint32 id, Order memory order) internal {
if(isBuy) {
_buyOrders[id] = _order2uint(order);
} else {
_sellOrders[id] = _order2uint(order);
}
}
// delete an order from storage
function _deleteOrder(bool isBuy, uint32 id) internal {
if(isBuy) {
delete _buyOrders[id];
} else {
delete _sellOrders[id];
}
}
function _getFirstOrderID(Context memory ctx, bool isBuy) internal pure returns (uint32) {
if(isBuy) {
return ctx.firstBuyID;
}
return ctx.firstSellID;
}
function _setFirstOrderID(Context memory ctx, bool isBuy, uint32 id) internal pure {
if(isBuy) {
ctx.firstBuyID = id;
} else {
ctx.firstSellID = id;
}
}
function removeOrders(uint[] calldata rmList) external override lock {
uint[5] memory proxyData;
uint expectedCallDataSize = 4+32*(ProxyData.COUNT+2+rmList.length);
ProxyData.fill(proxyData, expectedCallDataSize);
for(uint i = 0; i < rmList.length; i++) {
uint rmInfo = rmList[i];
bool isBuy = uint8(rmInfo) != 0;
uint32 id = uint32(rmInfo>>8);
uint72 prevKey = uint72(rmInfo>>40);
_removeOrder(isBuy, id, prevKey, proxyData);
}
}
function removeOrder(bool isBuy, uint32 id, uint72 prevKey) external override lock {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+3));
_removeOrder(isBuy, id, prevKey, proxyData);
}
function _removeOrder(bool isBuy, uint32 id, uint72 prevKey, uint[5] memory proxyData) private {
Context memory ctx;
(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked();
if(!isBuy) {
(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves();
}
Order memory order = _removeOrderFromBook(ctx, isBuy, id, prevKey); // this is the removed order
require(msg.sender == order.sender, "GraSwap: NOT_OWNER");
uint64 stockUnit = ProxyData.stockUnit(proxyData);
uint stockAmount = uint(order.amount)/*42bits*/ * uint(stockUnit);
address graContract = ProxyData.graContract(proxyData);
if(isBuy) {
RatPrice memory price = _expandPrice(order.price, proxyData);
uint moneyAmount = stockAmount * price.numerator/*54+64bits*/ / price.denominator;
ctx.bookedMoney -= moneyAmount;
_safeTransfer(ProxyData.money(proxyData), order.sender, moneyAmount, graContract);
} else {
ctx.bookedStock -= stockAmount;
_safeTransfer(ProxyData.stock(proxyData), order.sender, stockAmount, graContract);
}
_setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID);
}
// remove an order from orderbook and return it
function _removeOrderFromBook(Context memory ctx, bool isBuy,
uint32 id, uint72 prevKey) internal returns (Order memory) {
(Order memory order, bool ok) = _getOrder(isBuy, id);
require(ok, "GraSwap: NO_SUCH_ORDER");
if(prevKey == 0) {
uint32 firstID = _getFirstOrderID(ctx, isBuy);
require(id == firstID, "GraSwap: NOT_FIRST");
_setFirstOrderID(ctx, isBuy, order.nextID);
if(!isBuy) {
_setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID);
}
} else {
(uint32 currID, Order memory prevOrder, bool findIt) = _getOrder3Times(isBuy, prevKey);
require(findIt, "GraSwap: INVALID_POSITION");
while(prevOrder.nextID != id) {
currID = prevOrder.nextID;
require(currID != 0, "GraSwap: REACH_END");
(prevOrder, ) = _getOrder(isBuy, currID);
}
prevOrder.nextID = order.nextID;
_setOrder(isBuy, currID, prevOrder);
}
_emitRemoveOrder(order.amount, id, isBuy);
_deleteOrder(isBuy, id);
return order;
}
// insert an order at the head of single-linked list
// this function does not check price, use it carefully
function _insertOrderAtHead(Context memory ctx, bool isBuy, Order memory order, uint32 id) private {
order.nextID = _getFirstOrderID(ctx, isBuy);
_setOrder(isBuy, id, order);
_setFirstOrderID(ctx, isBuy, id);
}
// prevKey contains 3 orders. try to get the first existing order
function _getOrder3Times(bool isBuy, uint72 prevKey) private view returns (
uint32 currID, Order memory prevOrder, bool findIt) {
currID = uint32(prevKey&_MAX_ID);
(prevOrder, findIt) = _getOrder(isBuy, currID);
if(!findIt) {
currID = uint32((prevKey>>24)&_MAX_ID);
(prevOrder, findIt) = _getOrder(isBuy, currID);
if(!findIt) {
currID = uint32((prevKey>>48)&_MAX_ID);
(prevOrder, findIt) = _getOrder(isBuy, currID);
}
}
}
// Given a valid start position, find a proper position to insert order
// prevKey contains three suggested order IDs, each takes 24 bits.
// We try them one by one to find a valid start position
// can not use this function to insert at head! if prevKey is all zero, it will return false
function _insertOrderFromGivenPos(bool isBuy, Order memory order,
uint32 id, uint72 prevKey) private returns (bool inserted) {
(uint32 currID, Order memory prevOrder, bool findIt) = _getOrder3Times(isBuy, prevKey);
if(!findIt) {
return false;
}
return _insertOrder(isBuy, order, prevOrder, id, currID);
}
// Starting from the head of orderbook, find a proper position to insert order
function _insertOrderFromHead(Context memory ctx, bool isBuy, Order memory order,
uint32 id) private returns (bool inserted) {
uint32 firstID = _getFirstOrderID(ctx, isBuy);
bool canBeFirst = (firstID == 0);
Order memory firstOrder;
if(!canBeFirst) {
(firstOrder, ) = _getOrder(isBuy, firstID);
canBeFirst = (isBuy && (firstOrder.price < order.price)) ||
(!isBuy && (firstOrder.price > order.price));
}
if(canBeFirst) {
order.nextID = firstID;
_setOrder(isBuy, id, order);
_setFirstOrderID(ctx, isBuy, id);
return true;
}
return _insertOrder(isBuy, order, firstOrder, id, firstID);
}
// starting from 'prevOrder', whose id is 'currID', find a proper position to insert order
function _insertOrder(bool isBuy, Order memory order, Order memory prevOrder,
uint32 id, uint32 currID) private returns (bool inserted) {
while(currID != 0) {
bool canFollow = (isBuy && (order.price <= prevOrder.price)) ||
(!isBuy && (order.price >= prevOrder.price));
if(!canFollow) {break;}
Order memory nextOrder;
if(prevOrder.nextID != 0) {
(nextOrder, ) = _getOrder(isBuy, prevOrder.nextID);
bool canPrecede = (isBuy && (nextOrder.price < order.price)) ||
(!isBuy && (nextOrder.price > order.price));
canFollow = canFollow && canPrecede;
}
if(canFollow) {
order.nextID = prevOrder.nextID;
_setOrder(isBuy, id, order);
prevOrder.nextID = id;
_setOrder(isBuy, currID, prevOrder);
return true;
}
currID = prevOrder.nextID;
prevOrder = nextOrder;
}
return false;
}
// to query the first sell price, the first buy price and the price of pool
function getPrices() external override returns (
uint firstSellPriceNumerator,
uint firstSellPriceDenominator,
uint firstBuyPriceNumerator,
uint firstBuyPriceDenominator,
uint poolPriceNumerator,
uint poolPriceDenominator) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0));
(uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves();
poolPriceNumerator = uint(reserveMoney);
poolPriceDenominator = uint(reserveStock);
firstSellPriceNumerator = 0;
firstSellPriceDenominator = 0;
firstBuyPriceNumerator = 0;
firstBuyPriceDenominator = 0;
if(firstSellID!=0) {
uint order = _sellOrders[firstSellID];
RatPrice memory price = _expandPrice(uint32(order>>64), proxyData);
firstSellPriceNumerator = price.numerator;
firstSellPriceDenominator = price.denominator;
}
uint32 id = uint32(_bookedStockAndMoneyAndFirstBuyID>>224);
if(id!=0) {
uint order = _buyOrders[id];
RatPrice memory price = _expandPrice(uint32(order>>64), proxyData);
firstBuyPriceNumerator = price.numerator;
firstBuyPriceDenominator = price.denominator;
}
}
// Get the orderbook's content, starting from id, to get no more than maxCount orders
function getOrderList(bool isBuy, uint32 id, uint32 maxCount) external override view returns (uint[] memory) {
if(id == 0) {
if(isBuy) {
id = uint32(_bookedStockAndMoneyAndFirstBuyID>>224);
} else {
id = uint32(_reserveStockAndMoneyAndFirstSellID>>224);
}
}
uint[1<<22] storage orderbook;
if(isBuy) {
orderbook = _buyOrders;
} else {
orderbook = _sellOrders;
}
//record block height at the first entry
uint order = (block.number<<24) | id;
uint addrOrig; // start of returned data
uint addrLen; // the slice's length is written at this address
uint addrStart; // the address of the first entry of returned slice
uint addrEnd; // ending address to write the next order
uint count = 0; // the slice's length
// solhint-disable-next-line no-inline-assembly
assembly {
addrOrig := mload(0x40) // There is a “free memory pointer” at address 0x40 in memory
mstore(addrOrig, 32) //the meaningful data start after offset 32
}
addrLen = addrOrig + 32;
addrStart = addrLen + 32;
addrEnd = addrStart;
while(count < maxCount) {
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(addrEnd, order) //write the order
}
addrEnd += 32;
count++;
if(id == 0) {break;}
order = orderbook[id];
require(order!=0, "GraSwap: INCONSISTENT_BOOK");
id = uint32(order&_MAX_ID);
}
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(addrLen, count) // record the returned slice's length
let byteCount := sub(addrEnd, addrOrig)
return(addrOrig, byteCount)
}
}
// Get an unused id to be used with new order
function _getUnusedOrderID(bool isBuy, uint32 id) internal view returns (uint32) {
if(id == 0) { // 0 is reserved
// solhint-disable-next-line avoid-tx-origin
id = uint32(uint(blockhash(block.number-1))^uint(tx.origin)) & _MAX_ID; //get a pseudo random number
}
for(uint32 i = 0; i < 100 && id <= _MAX_ID; i++) { //try 100 times
if(!_hasOrder(isBuy, id)) {
return id;
}
id++;
}
require(false, "GraSwap: CANNOT_FIND_VALID_ID");
return 0;
}
function calcStockAndMoney(uint64 amount, uint32 price32) external pure override returns (uint stockAmount, uint moneyAmount) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+2));
(stockAmount, moneyAmount, ) = _calcStockAndMoney(amount, price32, proxyData);
}
function _calcStockAndMoney(uint64 amount, uint32 price32, uint[5] memory proxyData) private pure returns (uint stockAmount, uint moneyAmount, RatPrice memory price) {
price = _expandPrice(price32, proxyData);
uint64 stockUnit = ProxyData.stockUnit(proxyData);
stockAmount = uint(amount)/*42bits*/ * uint(stockUnit);
moneyAmount = stockAmount * price.numerator/*54+64bits*/ /price.denominator;
}
function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32,
uint32 id, uint72 prevKey) external payable override lock {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+6));
require(ProxyData.isOnlySwap(proxyData)==false, "GraSwap: LIMIT_ORDER_NOT_SUPPORTED");
Context memory ctx;
ctx.stockUnit = ProxyData.stockUnit(proxyData);
ctx.graContract = ProxyData.graContract(proxyData);
ctx.factory = ProxyData.factory(proxyData);
ctx.stockToken = ProxyData.stock(proxyData);
ctx.moneyToken = ProxyData.money(proxyData);
ctx.priceMul = ProxyData.priceMul(proxyData);
ctx.priceDiv = ProxyData.priceDiv(proxyData);
ctx.hasDealtInOrderBook = false;
ctx.isLimitOrder = true;
ctx.order.sender = sender;
ctx.order.amount = amount;
ctx.order.price = price32;
ctx.newOrderID = _getUnusedOrderID(isBuy, id);
RatPrice memory price;
{// to prevent "CompilerError: Stack too deep, try removing local variables."
require((amount >> 42) == 0, "GraSwap: INVALID_AMOUNT");
uint32 m = price32 & DecFloat32.MANTISSA_MASK;
require(DecFloat32.MIN_MANTISSA <= m && m <= DecFloat32.MAX_MANTISSA, "GraSwap: INVALID_PRICE");
uint stockAmount;
uint moneyAmount;
(stockAmount, moneyAmount, price) = _calcStockAndMoney(amount, price32, proxyData);
if(isBuy) {
ctx.remainAmount = moneyAmount;
} else {
ctx.remainAmount = stockAmount;
}
}
require(ctx.remainAmount < uint(1<<112), "GraSwap: OVERFLOW");
(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves();
(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked();
_checkRemainAmount(ctx, isBuy);
if(prevKey != 0) { // try to insert it
bool inserted = _insertOrderFromGivenPos(isBuy, ctx.order, ctx.newOrderID, prevKey);
if(inserted) { // if inserted successfully, record the booked tokens
_emitNewLimitOrder(uint64(ctx.order.sender), amount, amount, price32, ctx.newOrderID, isBuy);
if(isBuy) {
ctx.bookedMoney += ctx.remainAmount;
} else {
ctx.bookedStock += ctx.remainAmount;
}
_setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID);
if(ctx.reserveChanged) {
_setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID);
}
return;
}
// if insertion failed, we try to match this order and make it deal
}
_addOrder(ctx, isBuy, price);
}
function addMarketOrder(address inputToken, address sender,
uint112 inAmount) external payable override lock returns (uint) {
uint[5] memory proxyData;
ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+3));
Context memory ctx;
ctx.moneyToken = ProxyData.money(proxyData);
ctx.stockToken = ProxyData.stock(proxyData);
require(inputToken == ctx.moneyToken || inputToken == ctx.stockToken, "GraSwap: INVALID_TOKEN");
bool isBuy = inputToken == ctx.moneyToken;
ctx.stockUnit = ProxyData.stockUnit(proxyData);
ctx.priceMul = ProxyData.priceMul(proxyData);
ctx.priceDiv = ProxyData.priceDiv(proxyData);
ctx.graContract = ProxyData.graContract(proxyData);
ctx.factory = ProxyData.factory(proxyData);
ctx.hasDealtInOrderBook = false;
ctx.isLimitOrder = false;
ctx.remainAmount = inAmount;
(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves();
(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked();
_checkRemainAmount(ctx, isBuy);
ctx.order.sender = sender;
if(isBuy) {
ctx.order.price = DecFloat32.MAX_PRICE;
} else {
ctx.order.price = DecFloat32.MIN_PRICE;
}
RatPrice memory price; // leave it to zero, actually it will not be used;
_emitNewMarketOrder(uint136(ctx.order.sender), inAmount, isBuy);
return _addOrder(ctx, isBuy, price);
}
// Check router contract did send me enough tokens.
// If Router sent to much tokens, take them as reserve money&stock
function _checkRemainAmount(Context memory ctx, bool isBuy) private view {
ctx.reserveChanged = false;
uint diff;
if(isBuy) {
uint balance = _myBalance(ctx.moneyToken);
require(balance >= ctx.bookedMoney + ctx.reserveMoney, "GraSwap: MONEY_MISMATCH");
diff = balance - ctx.bookedMoney - ctx.reserveMoney;
if(ctx.remainAmount < diff) {
ctx.reserveMoney += (diff - ctx.remainAmount);
ctx.reserveChanged = true;
}
} else {
uint balance = _myBalance(ctx.stockToken);
require(balance >= ctx.bookedStock + ctx.reserveStock, "GraSwap: STOCK_MISMATCH");
diff = balance - ctx.bookedStock - ctx.reserveStock;
if(ctx.remainAmount < diff) {
ctx.reserveStock += (diff - ctx.remainAmount);
ctx.reserveChanged = true;
}
}
require(ctx.remainAmount <= diff, "GraSwap: DEPOSIT_NOT_ENOUGH");
}
// internal helper function to add new limit order & market order
// returns the amount of tokens which were sent to the taker (from AMM pool and booked tokens)
function _addOrder(Context memory ctx, bool isBuy, RatPrice memory price) private returns (uint) {
(ctx.dealMoneyInBook, ctx.dealStockInBook) = (0, 0);
ctx.firstID = _getFirstOrderID(ctx, !isBuy);
uint32 currID = ctx.firstID;
ctx.amountIntoPool = 0;
while(currID != 0) { // while not reaching the end of single-linked
(Order memory orderInBook, ) = _getOrder(!isBuy, currID);
bool canDealInOrderBook = (isBuy && (orderInBook.price <= ctx.order.price)) ||
(!isBuy && (orderInBook.price >= ctx.order.price));
if(!canDealInOrderBook) {break;} // no proper price in orderbook, stop here
// Deal in liquid pool
RatPrice memory priceInBook = _expandPrice(ctx, orderInBook.price);
bool allDeal = _tryDealInPool(ctx, isBuy, priceInBook);
if(allDeal) {break;}
// Deal in orderbook
_dealInOrderBook(ctx, isBuy, currID, orderInBook, priceInBook);
// if the order in book did NOT fully deal, then this new order DID fully deal, so stop here
if(orderInBook.amount != 0) {
_setOrder(!isBuy, currID, orderInBook);
break;
}
// if the order in book DID fully deal, then delete this order from storage and move to the next
_deleteOrder(!isBuy, currID);
currID = orderInBook.nextID;
}
// Deal in liquid pool
if(ctx.isLimitOrder) {
// use current order's price to deal with pool
_tryDealInPool(ctx, isBuy, price);
// If a limit order did NOT fully deal, we add it into orderbook
// Please note a market order always fully deals
_insertOrderToBook(ctx, isBuy, price);
} else {
// the AMM pool can deal with orders with any amount
ctx.amountIntoPool += ctx.remainAmount; // both of them are less than 112 bits
ctx.remainAmount = 0;
}
uint amountToTaker = _dealWithPoolAndCollectFee(ctx, isBuy);
if(isBuy) {
ctx.bookedStock -= ctx.dealStockInBook; //If this subtraction overflows, _setBooked will fail
} else {
ctx.bookedMoney -= ctx.dealMoneyInBook; //If this subtraction overflows, _setBooked will fail
}
if(ctx.firstID != currID) { //some orders DID fully deal, so the head of single-linked list change
_setFirstOrderID(ctx, !isBuy, currID);
}
// write the cached values to storage
_setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID);
_setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID);
return amountToTaker;
}
// Given reserveMoney and reserveStock in AMM pool, calculate how much tokens will go into the pool if the
// final price is 'price'
function _intopoolAmountTillPrice(bool isBuy, uint reserveMoney, uint reserveStock,
RatPrice memory price) private pure returns (uint result) {
// sqrt(Pold/Pnew) = sqrt((2**32)*M_old*PnewDenominator / (S_old*PnewNumerator)) / (2**16)
// sell, stock-into-pool, Pold > Pnew
uint numerator = reserveMoney/*112bits*/ * price.denominator/*76+64bits*/;
uint denominator = reserveStock/*112bits*/ * price.numerator/*54+64bits*/;
if(isBuy) { // buy, money-into-pool, Pold < Pnew
// sqrt(Pnew/Pold) = sqrt((2**32)*S_old*PnewNumerator / (M_old*PnewDenominator)) / (2**16)
(numerator, denominator) = (denominator, numerator);
}
while(numerator >= (1<<192)) { // can not equal to (1<<192) !!!
numerator >>= 16;
denominator >>= 16;
}
require(denominator != 0, "GraSwapPair: DIV_BY_ZERO");
numerator = numerator * (1<<64);
uint quotient = numerator / denominator;
if(quotient <= (1<<64)) {
return 0;
} else if(quotient <= ((1<<64)*5/4)) {
// Taylor expansion: x/2 - x*x/8 + x*x*x/16
uint x = quotient - (1<<64);
uint y = x*x;
y = x/2 - y/(8*(1<<64)) + y*x/(16*(1<<128));
if(isBuy) {
result = reserveMoney * y;
} else {
result = reserveStock * y;
}
result /= (1<<64);
return result;
}
uint root = Math.sqrt(quotient); //root is at most 110bits
uint diff = root - (1<<32); //at most 110bits
if(isBuy) {
result = reserveMoney * diff;
} else {
result = reserveStock * diff;
}
result /= (1<<32);
return result;
}
// Current order tries to deal against the AMM pool. Returns whether current order fully deals.
function _tryDealInPool(Context memory ctx, bool isBuy, RatPrice memory price) private pure returns (bool) {
uint currTokenCanTrade = _intopoolAmountTillPrice(isBuy, ctx.reserveMoney, ctx.reserveStock, price);
require(currTokenCanTrade < uint(1<<112), "GraSwap: CURR_TOKEN_TOO_LARGE");
// all the below variables are less than 112 bits
if(!isBuy) {
currTokenCanTrade /= ctx.stockUnit; //to round
currTokenCanTrade *= ctx.stockUnit;
}
if(currTokenCanTrade > ctx.amountIntoPool) {
uint diffTokenCanTrade = currTokenCanTrade - ctx.amountIntoPool;
bool allDeal = diffTokenCanTrade >= ctx.remainAmount;
if(allDeal) {
diffTokenCanTrade = ctx.remainAmount;
}
ctx.amountIntoPool += diffTokenCanTrade;
ctx.remainAmount -= diffTokenCanTrade;
return allDeal;
}
return false;
}
// Current order tries to deal against the orders in book
function _dealInOrderBook(Context memory ctx, bool isBuy, uint32 currID,
Order memory orderInBook, RatPrice memory priceInBook) internal {
ctx.hasDealtInOrderBook = true;
uint stockAmount;
if(isBuy) {
uint a = ctx.remainAmount/*112bits*/ * priceInBook.denominator/*76+64bits*/;
uint b = priceInBook.numerator/*54+64bits*/ * ctx.stockUnit/*64bits*/;
stockAmount = a/b;
} else {
stockAmount = ctx.remainAmount/ctx.stockUnit;
}
if(uint(orderInBook.amount) < stockAmount) {
stockAmount = uint(orderInBook.amount);
}
require(stockAmount < (1<<42), "GraSwap: STOCK_TOO_LARGE");
uint stockTrans = stockAmount/*42bits*/ * ctx.stockUnit/*64bits*/;
uint moneyTrans = stockTrans * priceInBook.numerator/*54+64bits*/ / priceInBook.denominator/*76+64bits*/;
_emitOrderChanged(orderInBook.amount, uint64(stockAmount), currID, isBuy);
orderInBook.amount -= uint64(stockAmount);
if(isBuy) { //subtraction cannot overflow: moneyTrans and stockTrans are calculated from remainAmount
ctx.remainAmount -= moneyTrans;
} else {
ctx.remainAmount -= stockTrans;
}
// following accumulations can not overflow, because stockTrans(moneyTrans) at most 106bits(160bits)
// we know for sure that dealStockInBook and dealMoneyInBook are less than 192 bits
ctx.dealStockInBook += stockTrans;
ctx.dealMoneyInBook += moneyTrans;
if(isBuy) {
_safeTransfer(ctx.moneyToken, orderInBook.sender, moneyTrans, ctx.graContract);
} else {
_safeTransfer(ctx.stockToken, orderInBook.sender, stockTrans, ctx.graContract);
}
}
// make real deal with the pool and then collect fee, which will be added to AMM pool
function _dealWithPoolAndCollectFee(Context memory ctx, bool isBuy) internal returns (uint) {
(uint outpoolTokenReserve, uint inpoolTokenReserve, uint otherToTaker) = (
ctx.reserveMoney, ctx.reserveStock, ctx.dealMoneyInBook);
if(isBuy) {
(outpoolTokenReserve, inpoolTokenReserve, otherToTaker) = (
ctx.reserveStock, ctx.reserveMoney, ctx.dealStockInBook);
}
// all these 4 varialbes are less than 112 bits
// outAmount is sure to less than outpoolTokenReserve (which is ctx.reserveStock or ctx.reserveMoney)
uint outAmount = (outpoolTokenReserve*ctx.amountIntoPool)/(inpoolTokenReserve+ctx.amountIntoPool);
if(ctx.amountIntoPool > 0) {
_emitDealWithPool(uint112(ctx.amountIntoPool), uint112(outAmount), isBuy);
}
uint32 feeBPS = IGraSwapFactory(ctx.factory).feeBPS();
// the token amount that should go to the taker,
// for buy-order, it's stock amount; for sell-order, it's money amount
uint amountToTaker = outAmount + otherToTaker;
require(amountToTaker < uint(1<<112), "GraSwap: AMOUNT_TOO_LARGE");
uint fee = (amountToTaker * feeBPS + 9999) / 10000;
amountToTaker -= fee;
if(isBuy) {
ctx.reserveMoney = ctx.reserveMoney + ctx.amountIntoPool;
ctx.reserveStock = ctx.reserveStock - outAmount + fee;
} else {
ctx.reserveMoney = ctx.reserveMoney - outAmount + fee;
ctx.reserveStock = ctx.reserveStock + ctx.amountIntoPool;
}
address token = ctx.moneyToken;
if(isBuy) {
token = ctx.stockToken;
}
_safeTransfer(token, ctx.order.sender, amountToTaker, ctx.graContract);
return amountToTaker;
}
// Insert a not-fully-deal limit order into orderbook
function _insertOrderToBook(Context memory ctx, bool isBuy, RatPrice memory price) internal {
(uint smallAmount, uint moneyAmount, uint stockAmount) = (0, 0, 0);
if(isBuy) {
uint tempAmount1 = ctx.remainAmount /*112bits*/ * price.denominator /*76+64bits*/;
uint temp = ctx.stockUnit * price.numerator/*54+64bits*/;
stockAmount = tempAmount1 / temp;
uint tempAmount2 = stockAmount * temp; // Now tempAmount1 >= tempAmount2
moneyAmount = (tempAmount2+price.denominator-1)/price.denominator; // round up
if(ctx.remainAmount > moneyAmount) {
// smallAmount is the gap where remainAmount can not buy an integer of stocks
smallAmount = ctx.remainAmount - moneyAmount;
} else {
moneyAmount = ctx.remainAmount;
} //Now ctx.remainAmount >= moneyAmount
} else {
// for sell orders, remainAmount were always decreased by integral multiple of StockUnit
// and we know for sure that ctx.remainAmount % StockUnit == 0
stockAmount = ctx.remainAmount / ctx.stockUnit;
smallAmount = ctx.remainAmount - stockAmount * ctx.stockUnit;
}
ctx.amountIntoPool += smallAmount; // Deal smallAmount with pool
//ctx.reserveMoney += smallAmount; // If this addition overflows, _setReserves will fail
_emitNewLimitOrder(uint64(ctx.order.sender), ctx.order.amount, uint64(stockAmount),
ctx.order.price, ctx.newOrderID, isBuy);
if(stockAmount != 0) {
ctx.order.amount = uint64(stockAmount);
if(ctx.hasDealtInOrderBook) {
// if current order has ever dealt, it has the best price and can be inserted at head
_insertOrderAtHead(ctx, isBuy, ctx.order, ctx.newOrderID);
} else {
// if current order has NEVER dealt, we must find a proper position for it.
// we may scan a lot of entries in the single-linked list and run out of gas
_insertOrderFromHead(ctx, isBuy, ctx.order, ctx.newOrderID);
}
}
// Any overflow/underflow in following calculation will be caught by _setBooked
if(isBuy) {
ctx.bookedMoney += moneyAmount;
} else {
ctx.bookedStock += (ctx.remainAmount - smallAmount);
}
}
}
// solhint-disable-next-line max-states-count
contract GraSwapPairProxy {
uint internal _unusedVar0;
uint internal _unusedVar1;
uint internal _unusedVar2;
uint internal _unusedVar3;
uint internal _unusedVar4;
uint internal _unusedVar5;
uint internal _unusedVar6;
uint internal _unusedVar7;
uint internal _unusedVar8;
uint internal _unusedVar9;
uint internal _unlocked;
uint internal immutable _immuFactory;
uint internal immutable _immuMoneyToken;
uint internal immutable _immuStockToken;
uint internal immutable _immuGras;
uint internal immutable _immuOther;
constructor(address stockToken, address moneyToken, bool isOnlySwap, uint64 stockUnit, uint64 priceMul, uint64 priceDiv, address graContract) public {
_immuFactory = uint(msg.sender);
_immuMoneyToken = uint(moneyToken);
_immuStockToken = uint(stockToken);
_immuGras = uint(graContract);
uint temp = 0;
if(isOnlySwap) {
temp = 1;
}
temp = (temp<<64) | stockUnit;
temp = (temp<<64) | priceMul;
temp = (temp<<64) | priceDiv;
_immuOther = temp;
_unlocked = 1;
}
receive() external payable { }
// solhint-disable-next-line no-complex-fallback
fallback() payable external {
uint factory = _immuFactory;
uint moneyToken = _immuMoneyToken;
uint stockToken = _immuStockToken;
uint graContract = _immuGras;
uint other = _immuOther;
address impl = IGraSwapFactory(address(_immuFactory)).pairLogic();
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
let size := calldatasize()
calldatacopy(ptr, 0, size)
let end := add(ptr, size)
// append immutable variables to the end of calldata
mstore(end, factory)
end := add(end, 32)
mstore(end, moneyToken)
end := add(end, 32)
mstore(end, stockToken)
end := add(end, 32)
mstore(end, graContract)
end := add(end, 32)
mstore(end, other)
size := add(size, 160)
let result := delegatecall(gas(), impl, ptr, size, 0, 0)
size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
contract GraSwapFactory is IGraSwapFactory {
struct TokensInPair {
address stock;
address money;
}
address public override feeTo_1;
address public override feeTo_2;
address public override feeToPrivate;
address public override feeToSetter;
address public immutable gov;
address public immutable graContract;
uint32 public override feeBPS = 40;
address public override pairLogic;
mapping(address => TokensInPair) private _pairWithToken;
mapping(bytes32 => address) private _tokensToPair;
address[] public allPairs;
IPairFeeDistribution pfd; // pairFeeDistribution
constructor(address _feeToSetter, address _gov, address _graContract, address _pairLogic, address _distribution) public {
feeToSetter = _feeToSetter;
gov = _gov;
graContract = _graContract;
pairLogic = _pairLogic;
pfd = IPairFeeDistribution(_distribution);
}
function createPair(address stock, address money, bool isOnlySwap) external override returns (address pair) {
require(stock != money, "GraSwapFactory: IDENTICAL_ADDRESSES");
// not necessary //require(stock != address(0) || money != address(0), "GraSwapFactory: ZERO_ADDRESS");
uint moneyDec = _getDecimals(money);
uint stockDec = _getDecimals(stock);
require(23 >= stockDec && stockDec >= 0, "GraSwapFactory: STOCK_DECIMALS_NOT_SUPPORTED");
uint dec = 0;
if (stockDec >= 4) {
dec = stockDec - 4; // now 19 >= dec && dec >= 0
}
// 10**19 = 10000000000000000000
// 1<<64 = 18446744073709551616
uint64 priceMul = 1;
uint64 priceDiv = 1;
bool differenceTooLarge = false;
if (moneyDec > stockDec) {
if (moneyDec > stockDec + 19) {
differenceTooLarge = true;
} else {
priceMul = uint64(uint(10)**(moneyDec - stockDec));
}
}
if (stockDec > moneyDec) {
if (stockDec > moneyDec + 19) {
differenceTooLarge = true;
} else {
priceDiv = uint64(uint(10)**(stockDec - moneyDec));
}
}
require(!differenceTooLarge, "GraSwapFactory: DECIMALS_DIFF_TOO_LARGE");
bytes32 salt = keccak256(abi.encodePacked(stock, money, isOnlySwap));
require(_tokensToPair[salt] == address(0), "GraSwapFactory: PAIR_EXISTS");
GraSwapPairProxy Graswap = new GraSwapPairProxy{salt: salt}(stock, money, isOnlySwap, uint64(uint(10)**dec), priceMul, priceDiv, graContract);
pair = address(Graswap);
allPairs.push(pair);
_tokensToPair[salt] = pair;
_pairWithToken[pair] = TokensInPair(stock, money);
emit PairCreated(pair, stock, money, isOnlySwap);
// save pair info in pairFeeDistribution contract
pfd.addpair(pair);
}
function _getDecimals(address token) private view returns (uint) {
if (token == address(0)) { return 18; }
return uint(IERC20(token).decimals());
}
function allPairsLength() external override view returns (uint) {
return allPairs.length;
}
function setFeeToAddresses(address _feeTo_1, address _feeTo_2, address _feeToPrivate) external override {
require(msg.sender == feeToSetter, "GraSwapFactory: FORBIDDEN");
feeTo_1 = _feeTo_1;
feeTo_2 = _feeTo_2;
feeToPrivate = _feeToPrivate;
}
function setFeeToSetter(address _feeToSetter) external override {
require(msg.sender == feeToSetter, "GraSwapFactory: FORBIDDEN");
feeToSetter = _feeToSetter;
}
function setPairLogic(address implLogic) external override {
require(msg.sender == gov, "GraSwapFactory: SETTER_MISMATCH");
pairLogic = implLogic;
}
function setFeeBPS(uint32 _bps) external override {
require(msg.sender == gov, "GraSwapFactory: SETTER_MISMATCH");
require(0 <= _bps && _bps <= 50 , "GraSwapFactory: BPS_OUT_OF_RANGE");
feeBPS = _bps;
}
function setpdf(address _newpfd) external {
require(msg.sender == feeToSetter, "GraSwapFactory: FORBIDDEN");
pfd = IPairFeeDistribution(_newpfd);
}
function getTokensFromPair(address pair) external view override returns (address stock, address money) {
stock = _pairWithToken[pair].stock;
money = _pairWithToken[pair].money;
}
function tokensToPair(address stock, address money, bool isOnlySwap) external view override returns (address pair) {
bytes32 key = keccak256(abi.encodePacked(stock, money, isOnlySwap));
return _tokensToPair[key];
}
}
|
Current order tries to deal against the AMM pool. Returns whether current order fully deals. all the below variables are less than 112 bits
|
function _tryDealInPool(Context memory ctx, bool isBuy, RatPrice memory price) private pure returns (bool) {
uint currTokenCanTrade = _intopoolAmountTillPrice(isBuy, ctx.reserveMoney, ctx.reserveStock, price);
require(currTokenCanTrade < uint(1<<112), "GraSwap: CURR_TOKEN_TOO_LARGE");
if(!isBuy) {
currTokenCanTrade *= ctx.stockUnit;
}
if(currTokenCanTrade > ctx.amountIntoPool) {
uint diffTokenCanTrade = currTokenCanTrade - ctx.amountIntoPool;
bool allDeal = diffTokenCanTrade >= ctx.remainAmount;
if(allDeal) {
diffTokenCanTrade = ctx.remainAmount;
}
ctx.amountIntoPool += diffTokenCanTrade;
ctx.remainAmount -= diffTokenCanTrade;
return allDeal;
}
return false;
if(currTokenCanTrade > ctx.amountIntoPool) {
uint diffTokenCanTrade = currTokenCanTrade - ctx.amountIntoPool;
bool allDeal = diffTokenCanTrade >= ctx.remainAmount;
if(allDeal) {
diffTokenCanTrade = ctx.remainAmount;
}
ctx.amountIntoPool += diffTokenCanTrade;
ctx.remainAmount -= diffTokenCanTrade;
return allDeal;
}
return false;
}
| 2,413,367 |
./partial_match/1/0x3061579E7dF4e618D9b657ccdE6c52Fb4ca0d439/sources/contracts/UncleBondFees.sol
|
/ Favoring push over pull to reduce accounting complexity for different tokens
|
function distributeFees(
address from,
address token,
uint256 amount
) external {
emit DistributeFees(token, amount);
ERC20 t = ERC20(token);
uint256 treasuryDistribution = (amount * treasuryPercent) /
PERCENT_DENOMINATOR;
t.safeTransferFrom(from, treasury, treasuryDistribution);
t.safeTransferFrom(from, contributors, amount - treasuryDistribution);
}
| 9,187,429 |
./full_match/1/0x673003F86fFe32F7CaA3E5fcfDC711EBf8A64aeF/sources/src/lib/module/ModuleFee.sol
|
Function to set a new FeeManager newFeeManager The new FeeManager address to write to storage
|
function setNewFeeManager(address newFeeManager) external onlyOwner {
require(newFeeManager != address(0) && newFeeManager != feeManager, "INVALID_FEE_MANAGER");
emit FeeManagerUpdated(feeManager, newFeeManager);
feeManager = newFeeManager;
}
==============*/
| 3,159,277 |
./full_match/43113/0x617b2E3c10325C546533Ecae277bcf9964aB3373/sources/KANDYSale.sol
|
claim KANDY allocation based on old + new invested amounts
|
function claimKANDY() public onlyEOA {
require(canClaim, "cannot claim yet");
require(!claimed[msg.sender], "already claimed");
require(!blacklisted[msg.sender], "blacklisted");
if ( invested[msg.sender] > 0 ) {
ERC20(KANDY).transfer(msg.sender, invested[msg.sender]);
}
claimed[msg.sender] = true;
}
| 7,129,929 |
./partial_match/1/0x9678b0CE0059d5e2E46453656B7f58ABfD129846/sources/STIMULUS_FINANCE_Dispatcher.sol
|
bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
|
function safeTransferFrom(address token, address from, address to, uint value) internal {
(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');
}
| 2,766,565 |
./full_match/137/0x33A4DC7FA425eD0a4BBbc20E3180442CCD855e86/sources/contracts/PolyDice.sol
|
Function to get the Balance of the Contract
|
function getBalance() public view returns (uint) {
return ContractBalance;
}
| 4,731,575 |
/** Copyright (c) 2018, ZSC Dev Team
* 2018-10-19: v0.00.01
*/
pragma solidity ^0.4.25;
// pragma experimental ABIEncoderV2;
import "../utillib/LibString.sol";
import "../utillib/LibInt.sol";
import "../common/pausable.sol";
import "../common/delegate.sol";
contract InsuranceCompany {
// function update(string _key, string _data) external;
// function remove(string _key) external;
// function size() external view returns (uint);
// function getByKey(string _key) external view returns (int, string);
// function getById(uint _id) external view returns (int, string, string);
function getAll() external view returns (int, string);
}
contract InsuranceTemplate {
// function update(string _key, string _data) external;
// function remove(string _key) external;
// function size() external view returns (uint);
function getByKey(string _key) external view returns (int, string);
// function getById(uint _id) external view returns (int, string, string);
}
contract InsuranceUser {
function add(string _userKey, string _template, string _data) external;
function remove(string _key) external;
// function size() public view returns (uint);
function exist(uint8 _type, string _key0, address _key1) public view returns (bool);
function getByKey(uint8 _type, string _key) external view returns (int, string);
// function getById(uint8 _type, uint _id) external view returns (int, string);
}
contract InsurancePolicy {
function add(string _userKey, string _templateKey, string _policyKey, string _data) external;
function addElement(string _key, string _elementKey, string _data) external;
function remove(string _key) external;
// function size() public view returns (uint);
function getByKey(uint8 _type, string _key) external view returns (int, string);
// function getById(uint8 _type, uint _id) external view returns (int, string);
function getKeys(uint _id, uint _count) external view returns (int, string);
}
contract InsuranceIntegral {
function claim(address _account, uint8 _type) public returns (bool);
// function mint(address _account, uint _value) public returns (bool);
function burn(address _account, uint _value) public;
function transfer(address _owner, address _to, uint _value) public returns (bool);
function addTrace(address _account, uint8 _scene, uint _time, uint _value, address _from, address _to) public;
function removeTrace(address _account) public;
// function updateThreshold(uint8 _type, uint _threshold) public;
// function updateCap(uint _newCap) public;
function trace(address _account, uint _startTime, uint _endTime) public view returns (string);
function traceSize(address _account, uint8 _scene, uint _time) public view returns (uint);
function threshold(uint8 _type) public view returns (uint);
// function cap() public view returns (uint);
// function totalSupply() public view returns (uint);
function balanceOf(address _owner) public view returns (uint);
}
contract Insurance is Pausable, Delegate {
using LibString for *;
using LibInt for *;
struct strArray {
/** @dev id start from '1', '0' means no exists */
mapping(string => uint) ids_;
mapping(uint => string) strs_;
uint sum_;
}
address private companyAddr_;
address private templateAddr_;
address private userAddr_;
address private policyAddr_;
address private integralAddr_;
string[] private keys_;
/** @dev string(original policy key) => uint(max id)
* @eg [email protected]_PingAn_Life => 9
*/
mapping(string => uint) private maxIds_;
/** @dev string(user key) => strArray(policy keys) */
mapping(string => strArray) private policyKeys_;
modifier _checkCompanyAddr() {
require(0 != companyAddr_);
_;
}
modifier _checkTemplateAddr() {
require(0 != templateAddr_);
_;
}
modifier _checkUserAddr() {
require(0 != userAddr_);
_;
}
modifier _checkPolicyAddr() {
require(0 != policyAddr_);
_;
}
modifier _checkIntegralAddr() {
require(0 != integralAddr_);
_;
}
modifier _onlyAdminOrHigher() {
require(checkDelegate(msg.sender, 2));
_;
}
modifier _onlyReaderOrHigher() {
require(checkDelegate(msg.sender, 3));
_;
}
constructor() public {
companyAddr_ = address(0);
templateAddr_ = address(0);
userAddr_ = address(0);
policyAddr_ = address(0);
integralAddr_ = address(0);
}
/** @dev Destroy the contract. */
function destroy() public _onlyOwner {
super.kill();
}
/** @dev Add policy key.
* @param _userKey string The key of user.
* @param _policyKey string The key of policy.
*/
function _addPolicyKey(string _userKey, string _policyKey) private {
// check exists
if (0 != policyKeys_[_userKey].ids_[_policyKey]) {
return;
}
uint sum = ++policyKeys_[_userKey].sum_;
policyKeys_[_userKey].ids_[_policyKey] = sum;
policyKeys_[_userKey].strs_[sum] = _policyKey;
}
/** @dev Remove policy key.
* @param _userKey string The key of user.
* @param _policyKey string The key of policy.
*/
function _removePolicyKey(string _userKey, string _policyKey) private {
uint sum = policyKeys_[_userKey].sum_;
// check sum
require(0 != sum);
// check exists
require(0 != policyKeys_[_userKey].ids_[_policyKey]);
string memory key2 = policyKeys_[_userKey].strs_[sum];
// check exists
require(0 != policyKeys_[_userKey].ids_[key2]);
// swap
uint id1 = policyKeys_[_userKey].ids_[_policyKey];
uint id2 = policyKeys_[_userKey].ids_[key2];
policyKeys_[_userKey].strs_[id1] = key2;
policyKeys_[_userKey].strs_[id2] = _policyKey;
policyKeys_[_userKey].ids_[_policyKey] = id2;
policyKeys_[_userKey].ids_[key2] = id1;
delete policyKeys_[_userKey].strs_[sum];
policyKeys_[_userKey].ids_[_policyKey] = 0;
policyKeys_[_userKey].sum_ --;
}
/** @dev Remove policy.
* @param _policyKey string The key of policy.
*/
function _removePolicy(string _policyKey) private {
_policyKey.split("_", keys_);
// 1. remove policy key for insurance_user_policy.sol
_removePolicyKey(keys_[0], _policyKey);
// 2. remove policy for insurance_policy.sol
InsurancePolicy(policyAddr_).remove(_policyKey);
}
/** @dev Setup.
* @param _companyAddr address The address of template contract.
* @param _templateAddr address The address of template contract.
* @param _userAddr address The address of user contract.
* @param _policyAddr address The address of policy contract.
* @param _integralAddr address The address of integral contract.
*/
function setup(address _companyAddr, address _templateAddr, address _userAddr, address _policyAddr, address _integralAddr) external whenNotPaused _onlyOwner {
// check params
require(address(0) != _companyAddr);
require(address(0) != _templateAddr);
require(address(0) != _userAddr);
require(address(0) != _policyAddr);
require(address(0) != _integralAddr);
companyAddr_ = _companyAddr;
templateAddr_ = _templateAddr;
userAddr_ = _userAddr;
policyAddr_ = _policyAddr;
integralAddr_ = _integralAddr;
}
/** @dev called by the owner to pause, triggers stopped state
*/
function pause() public whenNotPaused _onlyOwner {
super.pause();
}
/** @dev called by the owner to unpause, returns to normal state
*/
function unpause() public whenPaused _onlyOwner {
super.unpause();
}
/** @return true if the contract is paused, false otherwise.
*/
function paused() public view _onlyOwner returns (bool) {
return super.paused();
}
/** @dev Get all companies' info.
* @return The error code and the all companies' data.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function companyGetAll() external view whenNotPaused _onlyReaderOrHigher _checkCompanyAddr returns (int, string) {
return InsuranceCompany(companyAddr_).getAll();
}
/** @dev Get template info by key.
* @param _key string The key of template.
* @return The error code and the data of template info.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function templateGetByKey(string _key) external view whenNotPaused _onlyReaderOrHigher _checkTemplateAddr returns (int, string) {
return InsuranceTemplate(templateAddr_).getByKey(_key);
}
/** @dev Add user.
* @param _userKey string The key of user.
* @param _templateKey string The key of user template.
* @param _data string The JSON data of user.
* @param _time uint The trace time(UTC), including TZ and DST.
*/
function userAdd(string _userKey, string _templateKey, string _data, uint _time) external whenNotPaused _onlyAdminOrHigher _checkTemplateAddr _checkUserAddr _checkIntegralAddr {
// check param
require(0 != bytes(_userKey).length);
require(0 != bytes(_templateKey).length);
require(0 != bytes(_data).length);
string memory template = "";
int error = 0;
(error, template) = InsuranceTemplate(templateAddr_).getByKey(_templateKey);
require(0 == error);
InsuranceUser(userAddr_).add(_userKey, template, _data);
address account = _userKey.toAddress();
if (InsuranceIntegral(integralAddr_).claim(account, 0)) {
InsuranceIntegral(integralAddr_).addTrace(account, 0, _time, InsuranceIntegral(integralAddr_).threshold(0), integralAddr_, account);
}
}
/** @dev Remove user.
* @param _key string The key of user.
*/
function userRemove(string _key) external whenNotPaused _onlyOwner _checkUserAddr _checkPolicyAddr _checkIntegralAddr {
// check param
require(0 != bytes(_key).length);
// remove integral
address account = _key.toAddress();
require(InsuranceUser(userAddr_).exist(1, "", account));
uint value = InsuranceIntegral(integralAddr_).balanceOf(account);
if (0 < value) {
InsuranceIntegral(integralAddr_).burn(account, value);
}
// remove integral trace
InsuranceIntegral(integralAddr_).removeTrace(account);
// remove policies
uint size = policyKeys_[_key].sum_;
for (uint i=0; i<size; i++) {
string memory policyKey = policyKeys_[_key].strs_[1];
_removePolicy(policyKey);
}
// remove user
InsuranceUser(userAddr_).remove(_key);
}
/** @dev User check in.
* @param _account address The user address.
* @param _time uint The trace time(UTC), including TZ and DST.
*/
function userCheckIn(address _account, uint _time) external whenNotPaused _onlyAdminOrHigher _checkUserAddr _checkIntegralAddr {
require(InsuranceUser(userAddr_).exist(1, "", _account));
require(0 == InsuranceIntegral(integralAddr_).traceSize(_account, 2, _time));
if (InsuranceIntegral(integralAddr_).claim(_account, 2)) {
InsuranceIntegral(integralAddr_).addTrace(_account, 2, _time, InsuranceIntegral(integralAddr_).threshold(2), integralAddr_, _account);
}
}
/** @dev Check that if user exist
* @param _type uint8 The info type (0: key is string, 1: key is address).
* @param _key0 string The key of user for string.
* @param _key1 address The key of user for address.
* @return true/false.
*/
function userExist(uint8 _type, string _key0, address _key1) external view whenNotPaused _onlyReaderOrHigher _checkUserAddr returns (bool) {
return InsuranceUser(userAddr_).exist(_type, _key0, _key1);
}
/** @dev Get user info by key.
* @param _type uint8 The info type (0: detail, 1: brief).
* @param _key string The key of user.
* @return The error code and the JSON data of user info.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function userGetByKey(uint8 _type, string _key) external view whenNotPaused _onlyReaderOrHigher _checkUserAddr returns (int, string) {
return InsuranceUser(userAddr_).getByKey(_type, _key);
}
/** @dev Get user policies by key.
* @param _userKey string The key of user.
* @return Error code and user policies info for JSON data.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function userGetPolicies(string _userKey) external view whenNotPaused _onlyReaderOrHigher returns (int, string) {
// check param
if (0 == bytes(_userKey).length) {
return (-1, "");
}
uint sum = policyKeys_[_userKey].sum_;
if (0 == sum) {
return (-2, "");
}
string memory str = "";
for (uint i=1; i<=sum; i++) {
str = str.concat(policyKeys_[_userKey].strs_[i]);
if (sum > i) {
str = str.concat(",");
}
}
return (0, str);
}
/** @dev Add policy.
* @param _userKey string The key of user.
* @param _templateKey string The key of policy template.
* @param _policyKey string The key of policy.
* @param _data string The JSON data of policy.
* @param _time uint The trace time(UTC), including TZ and DST.
*/
function policyAdd(string _userKey, string _templateKey, string _policyKey, string _data, uint _time) external whenNotPaused _onlyAdminOrHigher _checkPolicyAddr _checkIntegralAddr {
// check param
require(0 != bytes(_userKey).length);
require(0 != bytes(_templateKey).length);
require(0 != bytes(_policyKey).length);
require(0 != bytes(_data).length);
string memory template = "";
int error = 0;
(error, template) = InsuranceTemplate(templateAddr_).getByKey(_templateKey);
require(0 == error);
string memory policyKey = _policyKey.concat("_", maxIds_[_policyKey].toString());
InsurancePolicy(policyAddr_).add(_userKey, policyKey, template, _data);
_addPolicyKey(_userKey, policyKey);
maxIds_[_policyKey] ++;
address account = _userKey.toAddress();
if (InsuranceIntegral(integralAddr_).claim(account, 1)) {
InsuranceIntegral(integralAddr_).addTrace(account, 1, _time, InsuranceIntegral(integralAddr_).threshold(1), integralAddr_, account);
}
}
/** @dev Remove policy.
* @param _key string The key of policy.
*/
function policyRemove(string _key) external whenNotPaused _onlyOwner _checkPolicyAddr {
// check param
require(0 != bytes(_key).length);
_removePolicy(_key);
}
/** @dev Add policy's element.
* @param _key string The key of policy.
* @param _elementKey string The key of policy element.
* @param _data string The element data of policy.
*/
function policyAddElement(string _key, string _elementKey, string _data) external whenNotPaused _onlyAdminOrHigher _checkPolicyAddr {
InsurancePolicy(policyAddr_).addElement(_key, _elementKey, _data);
}
/** @dev Get policy info by key.
* @param _type uint8 The info type (0: detail, 1: brief).
* @param _key string The key of policy.
* @return The error code and the JSON data of policy info.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function policyGetByKey(uint8 _type, string _key) external view whenNotPaused _onlyReaderOrHigher _checkPolicyAddr returns (int, string) {
return InsurancePolicy(policyAddr_).getByKey(_type, _key);
}
/** @dev Get policy keys.
* @param _id uint The starting id of policy.
* @param _count uint The count wanted(include starting id).
* @return The error code and the info
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function policyGetKeys(uint _id, uint _count) external view whenNotPaused _onlyReaderOrHigher _checkPolicyAddr returns (int, string) {
return InsurancePolicy(policyAddr_).getKeys(_id, _count);
}
/** @dev Claim integrals.
* @param _account address The address that will claim the integrals.
* @param _scene uint8 The types of bonus integrals.
* 0: User sign up.
* 1: User submit data.
* 2: User check in every day.
* 3: User invite others.
* 4: User share to Wechat.
* 5: User share to QQ.
* 6: User share to Microblog.
* 7: User click advertisements.
* 8: Administrator award.
* 9: Integrals spent.
* 10: Integrals transfer to someone.
* 11: Integrals transfer from someone.
* @param _time uint The trace time(UTC), including TZ and DST.
* @param _type uint8 The types of bonus integrals.
* 0: User sign up.
* 1: User submit data.
* 2: User check in every day.
* 3: User invite others.
* 4: User share to Wechat.
* 5: User share to QQ.
* 6: User share to Microblog.
* 7: User click advertisements.
*/
function integralClaim(address _account, uint8 _scene, uint _time, uint8 _type) external whenNotPaused _onlyAdminOrHigher _checkUserAddr _checkIntegralAddr {
require(InsuranceUser(userAddr_).exist(1, "", _account));
if (InsuranceIntegral(integralAddr_).claim(_account, _type)) {
InsuranceIntegral(integralAddr_).addTrace(_account, _scene, _time, InsuranceIntegral(integralAddr_).threshold(_type), integralAddr_, _account);
}
}
/** @dev Burns a specific amount of integrals.
* @param _account address The account whose integrals will be burnt.
* @param _time uint The trace time(UTC), including TZ and DST.
* @param _value uint The amount of integral to be burned.
*/
function integralBurn(address _account, uint _time, uint _value) external whenNotPaused _onlyAdminOrHigher _checkUserAddr _checkIntegralAddr {
require(InsuranceUser(userAddr_).exist(1, "", _account));
InsuranceIntegral(integralAddr_).burn(_account, _value);
InsuranceIntegral(integralAddr_).addTrace(_account, 9, _time, _value, _account, integralAddr_);
}
/** @dev Transfer integral to a specified address
* @param _owner address The address which owns the integrals.
* @param _to address The address to transfer to.
* @param _time uint The trace time(UTC), including TZ and DST.
* @param _value uint The amount to be transferred.
*/
function integralTransfer(address _owner, address _to, uint _time, uint _value) external whenNotPaused _onlyAdminOrHigher _checkUserAddr _checkIntegralAddr {
require(InsuranceUser(userAddr_).exist(1, "", _owner));
require(InsuranceUser(userAddr_).exist(1, "", _to));
require(InsuranceIntegral(integralAddr_).transfer(_owner, _to, _value));
// sender
InsuranceIntegral(integralAddr_).addTrace(_owner, 10, _time, _value, _owner, _to);
// receiver
InsuranceIntegral(integralAddr_).addTrace(_to, 11, _time, _value, _owner, _to);
}
/** @dev Get trace.
* @param _account address The account whose integrals will be traced.
* @param _startTime uint The start time of trace(UTC), including TZ and DST.
* @param _endTime uint The end time of trace(UTC), including TZ and DST.
*/
function integralTrace(address _account, uint _startTime, uint _endTime) external view whenNotPaused _onlyReaderOrHigher _checkUserAddr _checkIntegralAddr returns (string) {
require(InsuranceUser(userAddr_).exist(1, "", _account));
return InsuranceIntegral(integralAddr_).trace(_account, _startTime, _endTime);
}
/** @dev Gets the balance of the specified address.
* @param _owner address The address to query the balance of.
* @return A uint representing the amount owned by the passed address.
*/
function integralBalanceOf(address _owner) external view whenNotPaused _onlyReaderOrHigher _checkIntegralAddr returns (uint) {
return InsuranceIntegral(integralAddr_).balanceOf(_owner);
}
/** @dev Get contract related address.
* @return The addresses of contract related.
*/
function getAddr() external view whenNotPaused _onlyOwner returns (address, address, address, address, address) {
return (companyAddr_, templateAddr_, userAddr_, policyAddr_, integralAddr_);
}
}
|
Check that if user exist _type uint8 The info type (0: key is string, 1: key is address). _key0 string The key of user for string. _key1 address The key of user for address. return true/false./
|
function userExist(uint8 _type, string _key0, address _key1) external view whenNotPaused _onlyReaderOrHigher _checkUserAddr returns (bool) {
return InsuranceUser(userAddr_).exist(_type, _key0, _key1);
}
| 1,811,884 |
pragma solidity 0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
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 MembersBook library
* @dev Allows to store and manage addresses of members in contract
* @author Wojciech Harzowski (https://github.com/harzo)
* @author Dominik Kroliczek (https://github.com/kruligh)
*/
library MembersBookLib {
/**
* @dev Represents member with its address and
* @dev joining to organization timestamp
*/
struct Member {
address account;
uint32 joined;
}
/**
* @dev Represents set of members
*/
struct MembersBook {
Member[] entries;
}
/**
* @dev Adds new member to book
* @param account address Member's address
* @param joined uint32 Member's joining timestamp
*/
function add(
MembersBook storage self,
address account,
uint32 joined
)
internal
returns (bool)
{
if (account == address(0) || contains(self, account)) {
return false;
}
self.entries.push(
Member({
account: account,
joined: joined
}));
return true;
}
/**
* @dev Removes existing member from book
* @param account address Member's address whose should be removed
*/
function remove(
MembersBook storage self,
address account
)
internal
returns (bool)
{
if (!contains(self, account)) {
return false;
} else {
uint256 entryIndex = index(self, account);
if (entryIndex < self.entries.length - 1) {
self.entries[entryIndex] = self.entries[self.entries.length - 1];
}
self.entries.length--;
}
return true;
}
/**
* @dev Checks if member address exists in book
* @param account address Address to check
* @return bool Address existence indicator
*/
function contains(
MembersBook storage self,
address account
)
internal
view
returns (bool)
{
for (uint256 i = 0; i < self.entries.length; i++) {
if (self.entries[i].account == account) {
return true;
}
}
return false;
}
/**
* @dev Returns member index in book or reverts if doesn't exists
* @param account address Address to check
* @return uint256 Address index
*/
function index(
MembersBook storage self,
address account
)
private
view
returns (uint256)
{
for (uint256 i = 0; i < self.entries.length; i++) {
if (self.entries[i].account == account) {
return i;
}
}
assert(false);
}
}
/**
* @title Token interface compatible with Pragmatic Hodlings
* @author Wojciech Harzowski (https://github.com/harzo)
* @author Dominik Kroliczek (https://github.com/kruligh)
*/
contract TransferableToken {
function transfer(address to, uint256 amount) public;
function balanceOf(address who) public view returns (uint256);
}
/**
* @title Proportionally distribute contract's tokens to each registered hodler
* @dev Proportion is calculated based on joined timestamp
* @dev Group of hodlers and settlements are managed by contract owner
* @author Wojciech Harzowski (https://github.com/harzo)
* @author Dominik Kroliczek (https://github.com/kruligh)
*/
contract PragmaticHodlings is Ownable {
using SafeMath for uint256;
using MembersBookLib for MembersBookLib.MembersBook;
MembersBookLib.MembersBook private hodlers;
/**
* @dev Stores addresses added to book
*/
modifier onlyValidAddress(address account) {
require(account != address(0));
_;
}
modifier onlyHodlersExist {
require(hodlers.entries.length != 0);
_;
}
modifier onlyExisting(address account) {
require(hodlers.contains(account));
_;
}
modifier onlyNotExisting(address account) {
require(!hodlers.contains(account));
_;
}
modifier onlySufficientAmount(TransferableToken token) {
require(token.balanceOf(this) > 0);
_;
}
modifier onlyPast(uint32 timestamp) {
// solhint-disable-next-line not-rely-on-time
require(now > timestamp);
_;
}
/**
* @dev New hodler has been added to book
* @param account address Hodler's address
* @param joined uint32 Hodler's joining timestamp
*/
event HodlerAdded(address account, uint32 joined);
/**
* @dev Existing hodler has been removed
* @param account address Removed hodler address
*/
event HodlerRemoved(address account);
/**
* @dev Token is settled on hodlers addresses
* @param token address The token address
* @param amount uint256 Settled amount
*/
event TokenSettled(address token, uint256 amount);
/**
* @dev Adds new hodler to book
* @param account address Hodler's address
* @param joined uint32 Hodler's joining timestamp
*/
function addHodler(address account, uint32 joined)
public
onlyOwner
onlyValidAddress(account)
onlyNotExisting(account)
onlyPast(joined)
{
hodlers.add(account, joined);
HodlerAdded(account, joined);
}
/**
* @dev Removes existing hodler from book
* @param account address Hodler's address whose should be removed
*/
function removeHodler(address account)
public
onlyOwner
onlyValidAddress(account)
onlyExisting(account)
{
hodlers.remove(account);
HodlerRemoved(account);
}
/**
* @dev Settles given token on hodlers addresses
* @param token BasicToken The token to settle
*/
function settleToken(TransferableToken token)
public
onlyOwner
onlyHodlersExist
onlySufficientAmount(token)
{
uint256 tokenAmount = token.balanceOf(this);
uint256[] memory tokenShares = calculateShares(tokenAmount);
for (uint i = 0; i < hodlers.entries.length; i++) {
token.transfer(hodlers.entries[i].account, tokenShares[i]);
}
TokenSettled(token, tokenAmount);
}
/**
* @dev Calculates proportional share in given amount
* @param amount uint256 Amount to share between hodlers
* @return tokenShares uint256[] Calculated shares
*/
function calculateShares(uint256 amount)
public
view
returns (uint256[])
{
uint256[] memory temp = new uint256[](hodlers.entries.length);
uint256 sum = 0;
for (uint256 i = 0; i < temp.length; i++) {
// solhint-disable-next-line not-rely-on-time
temp[i] = now.sub(hodlers.entries[i].joined);
sum = sum.add(temp[i]);
}
uint256 sharesSum = 0;
for (i = 0; i < temp.length; i++) {
temp[i] = amount.mul(temp[i]).div(sum);
sharesSum += temp[i];
}
if (amount > sharesSum) { // undivided rest of token
temp[0] = temp[0].add(amount.sub(sharesSum));
}
return temp;
}
/**
* @dev Returns hodlers addresses with joining timestamps
* @return address[] Addresses of hodlers
* @return uint32[] joining timestamps. Related by index with addresses
*/
function getHodlers()
public
view
returns (address[], uint32[])
{
address[] memory hodlersAddresses = new address[](hodlers.entries.length);
uint32[] memory hodlersTimestamps = new uint32[](hodlers.entries.length);
for (uint256 i = 0; i < hodlers.entries.length; i++) {
hodlersAddresses[i] = hodlers.entries[i].account;
hodlersTimestamps[i] = hodlers.entries[i].joined;
}
return (hodlersAddresses, hodlersTimestamps);
}
/**
* @param account address Hodler address
* @return bool whether account is registered as holder
*/
function isHodler(address account)
public
view
returns (bool)
{
return hodlers.contains(account);
}
}
|
Adds new member to book account address Member's address joined uint32 Member's joining timestamp/
|
function add(
MembersBook storage self,
address account,
uint32 joined
)
internal
returns (bool)
{
if (account == address(0) || contains(self, account)) {
return false;
}
self.entries.push(
Member({
account: account,
joined: joined
}));
return true;
}
| 12,721,307 |
./partial_match/1/0xbc6a1af02c09fc1514B95eC98756ccAa95e8Af2e/sources/GEtherBridge.sol
|
Provides the total amount kept in the reserve in terms of the underlying asset. return _totalReserveUnderlying The underlying asset balance on reserve./
|
function totalReserveUnderlying() public view virtual override returns (uint256 _totalReserveUnderlying)
{
return GCFormulae._calcUnderlyingCostFromCost(totalReserve(), exchangeRate());
}
| 2,651,057 |
pragma solidity ^0.5.0;
import "./IDssProxyActions.sol";
contract DssProxyActionsBase {
uint256 constant RAY = 10**27;
// Internal functions
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = mul(wad, 10**27);
}
function convertTo18(address gemJoin, uint256 amt)
internal
returns (uint256 wad)
{
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec()));
}
// Public functions
function daiJoin_join(address apt, address urn, uint256 wad) public {
// Gets DAI from the user's wallet
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
function _getDrawDart(
address vat,
address jug,
address urn,
bytes32 ilk,
uint256 wad
) internal returns (int256 dart) {
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk)
internal
view
returns (int256 dart)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -toInt(art);
}
function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk)
internal
view
returns (uint256 wad)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = sub(mul(art, rate), dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
// Public functions
function transfer(address gem, address dst, uint256 wad) public {
GemLike(gem).transfer(dst, wad);
}
function ethJoin_join(address apt, address urn) public payable {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit.value(msg.value)();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
function gemJoin_join(
address apt,
address urn,
uint256 wad,
bool transferFrom
) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemJoinLike(apt).gem().approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function hope(address obj, address usr) public {
HopeLike(obj).hope(usr);
}
function nope(address obj, address usr) public {
HopeLike(obj).nope(usr);
}
function open(address manager, bytes32 ilk, address usr)
public
returns (uint256 cdp)
{
cdp = ManagerLike(manager).open(ilk, usr);
}
function give(address manager, uint256 cdp, address usr) public {
ManagerLike(manager).give(cdp, usr);
}
function giveToProxy(
address proxyRegistry,
address manager,
uint256 cdp,
address dst
) public {
// Gets actual proxy address
address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst);
// Checks if the proxy address already existed and dst address is still the owner
if (proxy == address(0) || ProxyLike(proxy).owner() != dst) {
uint256 csize;
assembly {
csize := extcodesize(dst)
}
// We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP
require(csize == 0, "Dst-is-a-contract");
// Creates the proxy for the dst address
proxy = ProxyRegistryLike(proxyRegistry).build(dst);
}
// Transfers CDP to the dst proxy
give(manager, cdp, proxy);
}
function cdpAllow(address manager, uint256 cdp, address usr, uint256 ok)
public
{
ManagerLike(manager).cdpAllow(cdp, usr, ok);
}
function urnAllow(address manager, address usr, uint256 ok) public {
ManagerLike(manager).urnAllow(usr, ok);
}
function flux(address manager, uint256 cdp, address dst, uint256 wad)
public
{
ManagerLike(manager).flux(cdp, dst, wad);
}
function move(address manager, uint256 cdp, address dst, uint256 rad)
public
{
ManagerLike(manager).move(cdp, dst, rad);
}
function frob(address manager, uint256 cdp, int256 dink, int256 dart)
public
{
ManagerLike(manager).frob(cdp, dink, dart);
}
function quit(address manager, uint256 cdp, address dst) public {
ManagerLike(manager).quit(cdp, dst);
}
function enter(address manager, address src, uint256 cdp) public {
ManagerLike(manager).enter(src, cdp);
}
function shift(address manager, uint256 cdpSrc, uint256 cdpOrg) public {
ManagerLike(manager).shift(cdpSrc, cdpOrg);
}
}
|
Gets DAI from the user's wallet Approves adapter to take the DAI amount Joins DAI into the vat
|
function daiJoin_join(address apt, address urn, uint256 wad) public {
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
DaiJoinLike(apt).dai().approve(apt, wad);
DaiJoinLike(apt).join(urn, wad);
}
| 2,488,304 |
pragma solidity ^0.4.10;
/**
* @title Interface to communicate with ICO token contract
*/
contract IToken {
function balanceOf(address _address) constant returns (uint balance);
function transferFromOwner(address _to, uint256 _value) returns (bool success);
}
/**
* @title Presale token contract
*/
contract TokenEscrow {
// Token-related properties/description to display in Wallet client / UI
string public standard = 'PBKXToken 0.3';
string public name = 'PBKXToken';
string public symbol = 'PBKX';
uint public decimals = 2;
uint public totalSupply = 300000000;
IToken icoToken;
event Converted(address indexed from, uint256 value); // Event to inform about the fact of token burning/destroying
event Transfer(address indexed from, address indexed to, uint256 value);
event Error(bytes32 error);
mapping (address => uint) balanceFor; // Presale token balance for each of holders
address owner; // Contract owner
uint public exchangeRate; // preICO -> ICO token exchange rate
// Token supply and discount policy structure
struct TokenSupply {
uint limit; // Total amount of tokens
uint totalSupply; // Current amount of sold tokens
uint tokenPriceInWei; // Number of token per 1 Eth
}
TokenSupply[3] public tokenSupplies;
// Modifiers
modifier owneronly { if (msg.sender == owner) _; }
/**
* @dev Set/change contract owner
* @param _owner owner address
*/
function setOwner(address _owner) owneronly {
owner = _owner;
}
function setRate(uint _exchangeRate) owneronly {
exchangeRate = _exchangeRate;
}
function setToken(address _icoToken) owneronly {
icoToken = IToken(_icoToken);
}
/**
* @dev Returns balance/token quanity owned by address
* @param _address Account address to get balance for
* @return balance value / token quantity
*/
function balanceOf(address _address) constant returns (uint balance) {
return balanceFor[_address];
}
/**
* @dev Transfers tokens from caller/method invoker/message sender to specified recipient
* @param _to Recipient address
* @param _value Token quantity to transfer
* @return success/failure of transfer
*/
function transfer(address _to, uint _value) returns (bool success) {
if(_to != owner) {
if (balanceFor[msg.sender] < _value) return false; // Check if the sender has enough
if (balanceFor[_to] + _value < balanceFor[_to]) return false; // Check for overflows
if (msg.sender == owner) {
transferByOwner(_value);
}
balanceFor[msg.sender] -= _value; // Subtract from the sender
balanceFor[_to] += _value; // Add the same to the recipient
Transfer(owner,_to,_value);
return true;
}
return false;
}
function transferByOwner(uint _value) private {
for (uint discountIndex = 0; discountIndex < tokenSupplies.length; discountIndex++) {
TokenSupply storage tokenSupply = tokenSupplies[discountIndex];
if(tokenSupply.totalSupply < tokenSupply.limit) {
if (tokenSupply.totalSupply + _value > tokenSupply.limit) {
_value -= tokenSupply.limit - tokenSupply.totalSupply;
tokenSupply.totalSupply = tokenSupply.limit;
} else {
tokenSupply.totalSupply += _value;
break;
}
}
}
}
/**
* @dev Burns/destroys specified amount of Presale tokens for caller/method invoker/message sender
* @return success/failure of transfer
*/
function convert() returns (bool success) {
if (balanceFor[msg.sender] == 0) return false; // Check if the sender has enough
if (!exchangeToIco(msg.sender)) return false; // Try to exchange preICO tokens to ICO tokens
Converted(msg.sender, balanceFor[msg.sender]);
balanceFor[msg.sender] = 0; // Subtract from the sender
return true;
}
/**
* @dev Converts/exchanges sold Presale tokens to ICO ones according to provided exchange rate
* @param owner address
*/
function exchangeToIco(address owner) private returns (bool) {
if(icoToken != address(0)) {
return icoToken.transferFromOwner(owner, balanceFor[owner] * exchangeRate);
}
return false;
}
/**
* @dev Presale contract constructor
*/
function TokenEscrow() {
owner = msg.sender;
balanceFor[msg.sender] = 300000000; // Give the creator all initial tokens
// Discount policy
tokenSupplies[0] = TokenSupply(100000000, 0, 11428571428571); // First million of tokens will go 11210762331838 wei for 1 token
tokenSupplies[1] = TokenSupply(100000000, 0, 11848341232227); // Second million of tokens will go 12106537530266 wei for 1 token
tokenSupplies[2] = TokenSupply(100000000, 0, 12500000000000); // Third million of tokens will go 13245033112582 wei for 1 token
//Balances recovery
transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,875);
transferByOwner(875);
transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,2150);
transferByOwner(2150);
transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,975);
transferByOwner(975);
transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,875000);
transferByOwner(875000);
transferFromOwner(0xa4a90f8d12ae235812a4770e0da76f5bc2fdb229,3500000);
transferByOwner(3500000);
transferFromOwner(0xbd08c225306f6b341ce5a896392e0f428b31799c,43750);
transferByOwner(43750);
transferFromOwner(0xf948fc5be2d2fd8a7ee20154a18fae145afd6905,3316981);
transferByOwner(3316981);
transferFromOwner(0x23f15982c111362125319fd4f35ac9e1ed2de9d6,2625);
transferByOwner(2625);
transferFromOwner(0x23f15982c111362125319fd4f35ac9e1ed2de9d6,5250);
transferByOwner(5250);
transferFromOwner(0x6ebff66a68655d88733df61b8e35fbcbd670018e,58625);
transferByOwner(58625);
transferFromOwner(0x1aaa29dffffc8ce0f0eb42031f466dbc3c5155ce,1043875);
transferByOwner(1043875);
transferFromOwner(0x5d47871df00083000811a4214c38d7609e8b1121,3300000);
transferByOwner(3300000);
transferFromOwner(0x30ced0c61ccecdd17246840e0d0acb342b9bd2e6,261070);
transferByOwner(261070);
transferFromOwner(0x1079827daefe609dc7721023f811b7bb86e365a8,2051875);
transferByOwner(2051875);
transferFromOwner(0x6c0b6a5ac81e07f89238da658a9f0e61be6a0076,10500000);
transferByOwner(10500000);
transferFromOwner(0xd16e29637a29d20d9e21b146fcfc40aca47656e5,1750);
transferByOwner(1750);
transferFromOwner(0x4c9ba33dcbb5876e1a83d60114f42c949da4ee22,7787500);
transferByOwner(7787500);
transferFromOwner(0x0d8cc80efe5b136865b9788393d828fd7ffb5887,100000000);
transferByOwner(100000000);
}
// Incoming transfer from the Presale token buyer
function() payable {
uint tokenAmount; // Amount of tzokens which is possible to buy for incoming transfer/payment
uint amountToBePaid; // Amount to be paid
uint amountTransfered = msg.value; // Cost/price in WEI of incoming transfer/payment
if (amountTransfered <= 0) {
Error('no eth was transfered');
msg.sender.transfer(msg.value);
return;
}
if(balanceFor[owner] <= 0) {
Error('all tokens sold');
msg.sender.transfer(msg.value);
return;
}
// Determine amount of tokens can be bought according to available supply and discount policy
for (uint discountIndex = 0; discountIndex < tokenSupplies.length; discountIndex++) {
// If it's not possible to buy any tokens at all skip the rest of discount policy
TokenSupply storage tokenSupply = tokenSupplies[discountIndex];
if(tokenSupply.totalSupply < tokenSupply.limit) {
uint tokensPossibleToBuy = amountTransfered / tokenSupply.tokenPriceInWei;
if (tokensPossibleToBuy > balanceFor[owner])
tokensPossibleToBuy = balanceFor[owner];
if (tokenSupply.totalSupply + tokensPossibleToBuy > tokenSupply.limit) {
tokensPossibleToBuy = tokenSupply.limit - tokenSupply.totalSupply;
}
tokenSupply.totalSupply += tokensPossibleToBuy;
tokenAmount += tokensPossibleToBuy;
uint delta = tokensPossibleToBuy * tokenSupply.tokenPriceInWei;
amountToBePaid += delta;
amountTransfered -= delta;
}
}
// Do not waste gas if there is no tokens to buy
if (tokenAmount == 0) {
Error('no token to buy');
msg.sender.transfer(msg.value);
return;
}
// Transfer tokens to buyer
transferFromOwner(msg.sender, tokenAmount);
// Transfer money to seller
owner.transfer(amountToBePaid);
// Refund buyer if overpaid / no tokens to sell
msg.sender.transfer(msg.value - amountToBePaid);
}
/**
* @dev Removes/deletes contract
*/
function kill() owneronly {
suicide(msg.sender);
}
/**
* @dev Transfers tokens from owner to specified recipient
* @param _to Recipient address
* @param _value Token quantity to transfer
* @return success/failure of transfer
*/
function transferFromOwner(address _to, uint256 _value) private returns (bool success) {
if (balanceFor[owner] < _value) return false; // Check if the owner has enough
if (balanceFor[_to] + _value < balanceFor[_to]) return false; // Check for overflows
balanceFor[owner] -= _value; // Subtract from the owner
balanceFor[_to] += _value; // Add the same to the recipient
Transfer(owner,_to,_value);
return true;
}
}
|
Returns balance/token quanity owned by address _address Account address to get balance for return balance value / token quantity/
|
function balanceOf(address _address) constant returns (uint balance) {
return balanceFor[_address];
}
| 13,039,003 |
./full_match/4/0x7Fc333985BebFd216Cd820AC121E0715db913218/sources/MooMooCollectible.sol
|
Exclusive presale minting
|
function mintPresale(uint256 _amount) public payable {
uint256 supply = totalSupply();
uint256 reservedAmt = presaleReserved[msg.sender];
require(presaleActive, "Presale isn't active");
require(reservedAmt > 0, "No tokens reserved for your address");
require(_amount <= reservedAmt, "Can't mint more than reserved");
require(supply + _amount <= MAX_SUPPLY, "Can't mint more than max supply");
require(msg.value == price * _amount, "Wrong amount of ETH sent");
presaleReserved[msg.sender] = reservedAmt - _amount;
for (uint256 i; i < _amount; i++) {
_safeMint(msg.sender, supply + i);
}
}
| 12,399,448 |
./partial_match/1/0x99577D3DD4DE7B31DFd034D465cF725FdCC5271B/sources/AMERICANPEPE.sol
|
Interface for the optional metadata functions from the ERC20Base standard. _Available since v4.1._/
|
interface IERC20MetaBase is IERC20Base {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
}
| 3,714,171 |
/**
*Submitted for verification at Etherscan.io on 2021-03-15
*/
/**
*Submitted for verification at Etherscan.io on 2020-12-05
*/
pragma solidity ^0.6.12;
// SPDX-License-Identifier: MIT
contract X2 {
using SafeMath for uint256;
string private _tokenName;
string private _tokenSymbol;
uint8 private _decimals;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param InitialSupply Initial supply of the contract
// @param name Token Name
// @param symbol Token symbol
// @param decimals Token decimals
constructor (uint256 initialSupply ,string memory name, string memory symbol, uint8 decimals) public {
_tokenName = name;
_tokenSymbol = symbol;
_decimals = decimals;
_totalSupply = initialSupply;
_balances[msg.sender] = initialSupply;
emit Transfer(address(0), msg.sender, initialSupply);
}
//Returns the name of the token
function name() public view returns (string memory) {
return _tokenName;
}
//Returns the symbol of the token
function symbol() public view returns (string memory) {
return _tokenSymbol;
}
/**
Returns the number of decimals the token uses - e.g. 8,
means to divide the token amount by 100000000 to get its user representation.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* returns total tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* returns the account balance of the specified address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* Returns the amount which spender is still allowed to withdraw from owner
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
*Transfer token for a specified address
*Transfers tokens to address receiver, and MUST fire the Transfer event.
*The function SHOULD throw if the message caller’s account balance does not have enough tokens to spend.
*/
function transfer(address receiver, uint256 numTokens) public returns (bool) {
_transfer(msg.sender, receiver, numTokens);
return true;
}
/**
* Allows spender to withdraw from your account msg.sender multiple times, up to the numTokens amount.
* If this function is called again it overwrites the current allowance with numTokens.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* To prevent attack vectors like the one https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/ ,
* clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender.
* THOUGH The contract itself shouldn’t enforce it, to allow backwards compatibility with contracts deployed before
*/
function approve(address spender, uint256 numTokens) public returns (bool) {
_approve(msg.sender, spender, numTokens);
return true;
}
/**
* Transfer tokens from one address to another.
*/
function transferFrom(address from, address to, uint256 numTokens) public returns (bool) {
_transfer(from, to, numTokens);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(numTokens));
return true;
}
/**
* Transfer token from to a specified addresses
*/
function _transfer(address from, address to, uint256 numTokens) internal {
require(to != address(0));
require(numTokens <= _balances[from]);
_balances[from] = _balances[from].sub(numTokens);
_balances[to] = _balances[to].add(numTokens);
emit Transfer(from, to, numTokens);
}
/**
* Approve an address to spend another addresses' tokens.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev 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, _allowed [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, _allowed [msg.sender][spender].sub(subtractedValue));
return true;
}
}
library SafeMath {
/**
* Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 ans = a - b;
return ans;
}
/**
* Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 ans = a + b;
require(ans >= a);
return ans;
}
}
|
Approve an address to spend another addresses' tokens./
|
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
| 2,457,446 |
./partial_match/56/0x4bf0b64664c4625cd3f15968A8400165962CB728/sources/BooToken.sol
|
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
|
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))
);
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), 'BOO::delegateBySig: invalid signature');
require(nonce == nonces[signatory]++, 'BOO::delegateBySig: invalid nonce');
require(now <= expiry, 'BOO::delegateBySig: signature expired');
return _delegate(signatory, delegatee);
}
| 11,075,206 |
./full_match/43114/0x0CE5807e595d4F91A7D745330B63Fc7dfD6D6a57/sources/contracts/MasterChef.sol
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant poolExists(_pid) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accAvacoPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeAvacoTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accAvacoPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 4,532,102 |
./full_match/42220/0xBd44Fd1339C3B5Cd95E88501b1A6AB7e54cf5622/sources/contracts/community/CommunityImplementation.sol
|
Copy a beneficiary _beneficiaryAddress address of the beneficiary to be copied/
|
function _copyBeneficiary(address _beneficiaryAddress) internal {
Beneficiary storage _beneficiary = _beneficiaries[_beneficiaryAddress];
if (_beneficiary.state != BeneficiaryState.NONE) {
return;
}
BeneficiaryState _originalState;
uint256 _originalClaims;
uint256 _originalClaimedAmount;
uint256 _originalLastClaim;
(_originalState, _originalClaims, _originalClaimedAmount, _originalLastClaim) = copyOf
.beneficiaries(_beneficiaryAddress);
require(
_originalState != BeneficiaryState.Copied,
"Community::copyBeneficiary: Beneficiary already copied"
);
_changeBeneficiaryState(_beneficiary, _originalState);
_beneficiary.claims = _originalClaims;
_beneficiary.claimedAmount = _originalClaimedAmount;
_beneficiary.lastClaim = _originalLastClaim;
uint256[] memory _originalClaimedAmounts = copyOf.beneficiaryClaimedAmounts(
_beneficiaryAddress
);
address[] memory _originalTokens = copyOf.tokenList();
uint256 _originalLength = _originalClaimedAmounts.length;
for (uint256 _index = 0; _index < _originalLength; _index++) {
if (_tokenList.contains(_originalTokens[_index])) {
_beneficiary.claimedAmounts[_originalTokens[_index]] = _originalClaimedAmounts[
_index
];
}
}
copyOf.setBeneficiaryState(_beneficiaryAddress, BeneficiaryState.Copied);
beneficiaryList.add(_beneficiaryAddress);
emit BeneficiaryCopied(msg.sender, _beneficiaryAddress);
}
| 16,317,580 |
./partial_match/1/0x85F66f5Ee2435bDCbE12c115bFd592462ECbDb5c/sources/MakerDaoGateway.sol
|
Abstracted collateral
|
function skr() external view returns (IERC20);
| 3,900,948 |
./full_match/137/0xB3d7bbEf0D9bF76dd46e3b9227446EfBa9231833/sources/src/main/solidity/DVP.sol
|
Accept a given trade (+ potentially escrow tokens). index Index of the trade to be accepted./
|
function acceptTrade(uint256 index) external payable {
_acceptTrade(index, msg.sender, msg.value);
}
| 4,790,543 |
pragma solidity ^0.4.25;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Community vote
* @notice An oracle for relevant decisions made by the community.
*/
contract CommunityVote is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => bool) doubleSpenderByWallet;
uint256 maxDriipNonce;
uint256 maxNullNonce;
bool dataAvailable;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
dataAvailable = true;
}
//
// Results functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the max driip nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxDriipNonce()
public
view
returns (uint256)
{
return maxDriipNonce;
}
/// @notice Get the max null settlement nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxNullNonce()
public
view
returns (uint256)
{
return maxNullNonce;
}
/// @notice Get the data availability status
/// @return true if data is available
function isDataAvailable()
public
view
returns (bool)
{
return dataAvailable;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title CommunityVotable
* @notice An ownable that has a community vote property
*/
contract CommunityVotable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
CommunityVote public communityVote;
bool public communityVoteFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote);
event FreezeCommunityVoteEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the community vote contract
/// @param newCommunityVote The (address of) CommunityVote contract instance
function setCommunityVote(CommunityVote newCommunityVote)
public
onlyDeployer
notNullAddress(newCommunityVote)
notSameAddresses(newCommunityVote, communityVote)
{
require(!communityVoteFrozen);
// Set new community vote
CommunityVote oldCommunityVote = communityVote;
communityVote = newCommunityVote;
// Emit event
emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote);
}
/// @notice Freeze the community vote from further updates
/// @dev This operation can not be undone
function freezeCommunityVote()
public
onlyDeployer
{
communityVoteFrozen = true;
// Emit event
emit FreezeCommunityVoteEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier communityVoteInitialized() {
require(communityVote != address(0));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string balanceType, int256 amount, address currencyCt,
uint256 currencyId, string standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[])
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that contains registered beneficiaries
*/
contract Benefactor is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address[] internal beneficiaries;
mapping(address => uint256) internal beneficiaryIndexByAddress;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterBeneficiaryEvent(address beneficiary);
event DeregisterBeneficiaryEvent(address beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given beneficiary
/// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(address beneficiary)
public
onlyDeployer
notNullAddress(beneficiary)
returns (bool)
{
if (beneficiaryIndexByAddress[beneficiary] > 0)
return false;
beneficiaries.push(beneficiary);
beneficiaryIndexByAddress[beneficiary] = beneficiaries.length;
// Emit event
emit RegisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Deregister the given beneficiary
/// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(address beneficiary)
public
onlyDeployer
notNullAddress(beneficiary)
returns (bool)
{
if (beneficiaryIndexByAddress[beneficiary] == 0)
return false;
uint256 idx = beneficiaryIndexByAddress[beneficiary] - 1;
if (idx < beneficiaries.length - 1) {
// Remap the last item in the array to this index
beneficiaries[idx] = beneficiaries[beneficiaries.length - 1];
beneficiaryIndexByAddress[beneficiaries[idx]] = idx + 1;
}
beneficiaries.length--;
beneficiaryIndexByAddress[beneficiary] = 0;
// Emit event
emit DeregisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Gauge whether the given address is the one of a registered beneficiary
/// @param beneficiary Address of beneficiary
/// @return true if beneficiary is registered, else false
function isRegisteredBeneficiary(address beneficiary)
public
view
returns (bool)
{
return beneficiaryIndexByAddress[beneficiary] > 0;
}
/// @notice Get the count of registered beneficiaries
/// @return The count of registered beneficiaries
function registeredBeneficiariesCount()
public
view
returns (uint256)
{
return beneficiaries.length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
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;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBenefactor
* @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount
*/
contract AccrualBenefactor is Benefactor {
using SafeMathIntLib for int256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => int256) private _beneficiaryFractionMap;
int256 public totalBeneficiaryFraction;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterAccrualBeneficiaryEvent(address beneficiary, int256 fraction);
event DeregisterAccrualBeneficiaryEvent(address beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given beneficiary for the entirety fraction
/// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(address beneficiary)
public
onlyDeployer
notNullAddress(beneficiary)
returns (bool)
{
return registerFractionalBeneficiary(beneficiary, ConstantsLib.PARTS_PER());
}
/// @notice Register the given beneficiary for the given fraction
/// @param beneficiary Address of beneficiary to be registered
/// @param fraction Fraction of benefits to be given
function registerFractionalBeneficiary(address beneficiary, int256 fraction)
public
onlyDeployer
notNullAddress(beneficiary)
returns (bool)
{
require(fraction > 0);
require(totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER());
if (!super.registerBeneficiary(beneficiary))
return false;
_beneficiaryFractionMap[beneficiary] = fraction;
totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction);
// Emit event
emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction);
return true;
}
/// @notice Deregister the given beneficiary
/// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(address beneficiary)
public
onlyDeployer
notNullAddress(beneficiary)
returns (bool)
{
if (!super.deregisterBeneficiary(beneficiary))
return false;
totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[beneficiary]);
_beneficiaryFractionMap[beneficiary] = 0;
// Emit event
emit DeregisterAccrualBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Get the fraction of benefits that is granted the given beneficiary
/// @param beneficiary Address of beneficiary
/// @return The beneficiary's fraction
function beneficiaryFraction(address beneficiary)
public
view
returns (int256)
{
return _beneficiaryFractionMap[beneficiary];
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0);
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] == address(0));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string oldStandard, string newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0);
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0));
require(registeredTransferControllers[newStandardHash] == address(0));
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0);
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0));
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0);
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0));
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0));
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0));
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0));
require(!registeredCurrencies[currencyCt].blacklisted);
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0));
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(newTransferControllerManager)
notSameAddresses(newTransferControllerManager, transferControllerManager)
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(transferControllerManager != address(0));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length);
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency)
{
require(index < self.currencies.length);
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[])
{
require(0 < self.currencies.length);
require(low <= up);
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length);
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length);
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length);
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length);
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title RevenueFund
* @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst
* accrual beneficiaries.
*/
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance periodAccrual;
CurrenciesLib.Currencies periodCurrencies;
FungibleBalanceLib.Balance aggregateAccrual;
CurrenciesLib.Currencies aggregateCurrencies;
TxHistoryLib.TxHistory private txHistory;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event CloseAccrualPeriodEvent();
event RegisterServiceEvent(address service);
event DeregisterServiceEvent(address service);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() public payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balances
periodAccrual.add(amount, address(0), 0);
aggregateAccrual.add(amount, address(0), 0);
// Add currency to stores of currencies
periodCurrencies.add(address(0), 0);
aggregateCurrencies.add(address(0), 0);
// Add to transaction history
txHistory.addDeposit(amount, address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string balanceType, int256 amount, address currencyCt,
uint256 currencyId, string standard)
public
{
receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string, int256 amount,
address currencyCt, uint256 currencyId, string standard)
public
{
require(amount.isNonZeroPositiveInt256());
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
require(
address(controller).delegatecall(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
// Add to balances
periodAccrual.add(amount, currencyCt, currencyId);
aggregateAccrual.add(amount, currencyCt, currencyId);
// Add currency to stores of currencies
periodCurrencies.add(currencyCt, currencyId);
aggregateCurrencies.add(currencyCt, currencyId);
// Add to transaction history
txHistory.addDeposit(amount, currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the period accrual balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The current period's accrual balance
function periodAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return periodAccrual.get(currencyCt, currencyId);
}
/// @notice Get the aggregate accrual balance of the given currency, including contribution from the
/// current accrual period
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The aggregate accrual balance
function aggregateAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return aggregateAccrual.get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded in the accrual period
/// @return The number of currencies in the current accrual period
function periodCurrenciesCount()
public
view
returns (uint256)
{
return periodCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range in the current accrual period
function periodCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[])
{
return periodCurrencies.getByIndices(low, up);
}
/// @notice Get the count of currencies ever recorded
/// @return The number of currencies ever recorded
function aggregateCurrenciesCount()
public
view
returns (uint256)
{
return aggregateCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have ever been recorded
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range ever recorded
function aggregateCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[])
{
return aggregateCurrencies.getByIndices(low, up);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Close the current accrual period of the given currencies
/// @param currencies The concerned currencies
function closeAccrualPeriod(MonetaryTypesLib.Currency[] currencies)
public
onlyOperator
{
require(ConstantsLib.PARTS_PER() == totalBeneficiaryFraction);
// Execute transfer
for (uint256 i = 0; i < currencies.length; i++) {
MonetaryTypesLib.Currency memory currency = currencies[i];
int256 remaining = periodAccrual.get(currency.ct, currency.id);
if (0 >= remaining)
continue;
for (uint256 j = 0; j < beneficiaries.length; j++) {
address beneficiaryAddress = beneficiaries[j];
if (beneficiaryFraction(beneficiaryAddress) > 0) {
int256 transferable = periodAccrual.get(currency.ct, currency.id)
.mul(beneficiaryFraction(beneficiaryAddress))
.div(ConstantsLib.PARTS_PER());
if (transferable > remaining)
transferable = remaining;
if (transferable > 0) {
// Transfer ETH to the beneficiary
if (currency.ct == address(0))
AccrualBeneficiary(beneficiaryAddress).receiveEthersTo.value(uint256(transferable))(address(0), "");
// Transfer token to the beneficiary
else {
TransferController controller = transferController(currency.ct, "");
require(
address(controller).delegatecall(
controller.getApproveSignature(), beneficiaryAddress, uint256(transferable), currency.ct, currency.id
)
);
AccrualBeneficiary(beneficiaryAddress).receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, "");
}
remaining = remaining.sub(transferable);
}
}
}
// Roll over remaining to next accrual period
periodAccrual.set(remaining, currency.ct, currency.id);
}
// Close accrual period of accrual beneficiaries
for (j = 0; j < beneficiaries.length; j++) {
beneficiaryAddress = beneficiaries[j];
// Require that beneficiary fraction is strictly positive
if (0 >= beneficiaryFraction(beneficiaryAddress))
continue;
// Close accrual period
AccrualBeneficiary(beneficiaryAddress).closeAccrualPeriod(currencies);
}
// Emit event
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementState
* @notice Where null settlement state is managed
*/
contract NullSettlementState is Ownable, Servable, CommunityVotable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public SET_MAX_NULL_NONCE_ACTION = "set_max_null_nonce";
string constant public SET_MAX_NONCE_WALLET_CURRENCY_ACTION = "set_max_nonce_wallet_currency";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256 public maxNullNonce;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetMaxNullNonceEvent(uint256 maxNullNonce);
event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency,
uint256 maxNullNonce);
event updateMaxNullNonceFromCommunityVoteEvent(uint256 maxDriipNonce);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the max null nonce
/// @param _maxNullNonce The max nonce
function setMaxNullNonce(uint256 _maxNullNonce)
public
onlyEnabledServiceAction(SET_MAX_NULL_NONCE_ACTION)
{
maxNullNonce = _maxNullNonce;
// Emit event
emit SetMaxNullNonceEvent(_maxNullNonce);
}
/// @notice Get the max null nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The max nonce
function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256) {
return walletCurrencyMaxNonce[wallet][currency.ct][currency.id];
}
/// @notice Set the max null nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @param _maxNullNonce The max nonce
function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency,
uint256 _maxNullNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_WALLET_CURRENCY_ACTION)
{
walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = _maxNullNonce;
// Emit event
emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, _maxNullNonce);
}
/// @notice Update the max null settlement nonce property from CommunityVote contract
function updateMaxNullNonceFromCommunityVote()
public
{
uint256 _maxNullNonce = communityVote.getMaxNullNonce();
if (0 == _maxNullNonce)
return;
maxNullNonce = _maxNullNonce;
// Emit event
emit updateMaxNullNonceFromCommunityVoteEvent(maxNullNonce);
}
}
|
Get the fraction of benefits that is granted the given beneficiary beneficiary Address of beneficiary return The beneficiary's fraction
|
function beneficiaryFraction(address beneficiary)
public
view
returns (int256)
{
return _beneficiaryFractionMap[beneficiary];
}
| 948,892 |
./partial_match/56/0x9EBAC281dD91cc48fF58528d4EcAD5c89Ae93751/sources/Comptroller.sol
|
Return the address of the COMP token return The address of COMP/
|
function getCompAddress() public view returns (address) {
return 0x838Ee47AaEB55ECA1F8b799eE7383DCa238e4094;
}
| 11,258,979 |
./full_match/42220/0x2de8673F9039Fe5b8494BD7C87eeD24beBc111AE/sources/contracts/CUSD.sol
|
reserve0 is usdc, reserve1 is celo
|
function canOpCelo()
public
view
returns (
uint256,
uint256,
uint256,
bool
)
{
(uint256 reserve0, uint256 reserve1, ) = celoUsdcPair.getReserves();
uint256 celoOutMin = router.getAmountOut(usdcTradeAmount, reserve0, reserve1);
uint256 cusdBack = exchange.getBuyTokenAmount(celoOutMin, true);
address[] memory path = new address[](3);
path[0] = cusdAddress;
path[1] = celoAddress;
path[2] = usdcAddress;
uint256 usdcBack = router.getAmountsOut(cusdBack, path)[2];
return (celoOutMin, usdcBack, thesholdUSCBack, usdcBack > thesholdUSCBack);
}
| 16,345,245 |
./full_match/1/0x3488d455D4AFA163C7E813c1e2bc2D6887CCE093/sources/contracts/MidgetVotingContract.sol
|
Creates a new poll./
|
function createPoll(
string memory _description
) external returns (uint256 pollId) {
if (msg.sender != owner()) {
require(
token.balanceOf(msg.sender) >= minTokenBalanceToCreatePoll,
"Insufficient token balance."
);
require(
_userWeekPollCount[msg.sender] < maxCreatingCountPerWeek,
"Exceeded max creating count per week"
);
}
pollId = pollCount++;
polls.push();
Poll storage newPoll = polls[pollId];
newPoll.pollId = pollId;
newPoll.creator = msg.sender;
newPoll.description = _description;
newPoll.isValid = true;
_userPollCount[msg.sender] += 1;
_userWeekPollCount[msg.sender] += 1;
emit PollCreated(msg.sender, pollCount, _description);
return pollId;
}
| 16,451,835 |
./partial_match/4/0x64fD3aea4Df3b76348a8cC9F2A18930fD6927738/sources/RAYv2.sol
|
could pass these in on function call but requires change to RoboToken contracts
|
function distributeRewards(address roboToken, address user, uint userBalance) internal {
uint totalSupply = IERC20(roboToken).totalSupply();
address roboController = IStorage(rayStorage).getContractAddress(ROBO_CONTROLLER_CONTRACT);
IRoboController(roboController).distributeRewards(roboToken, user, userBalance, totalSupply);
}
| 8,750,808 |
./partial_match/1/0x0D2022583D7EeaeBF0eCda69768bEe2eea65aEB2/sources/ERC20_Vesting.sol
|
This function allows the controller to assist the target user with their withdrawal. All the currently available vested tokens FOR THE TARGET will be withdrawn TO THE TARGET ADDRESS WALLET This function exists in case of users using custodial wallets that are incapable of running "withdraw_from_tranche" but are still ERC20 compatable ONLY the controller can run this function and it will only be ran at the target users request This will not allow a user's total tranch balance to go below the user's lien amount This function does not allow the controller to access any funds from other addresses or change which address is in control of any funds Emits Tranche_Balance_Removed event if successful tranche_id Id of target tranche target Address with balance that needs the assist
|
function assisted_withdraw_from_tranche(uint8 tranche_id, address target) public only_controller {
require(tranche_id != default_tranche_id);
uint256 to_withdraw = get_vested_for_tranche(target, tranche_id);
require(user_stats[target].total_in_all_tranches - to_withdraw >= user_stats[target].lien);
user_stats[target].tranche_balances[tranche_id].total_claimed += to_withdraw;
user_stats[target].total_in_all_tranches -= to_withdraw;
total_locked -= to_withdraw;
require(IERC20(v2_address).transfer(target, to_withdraw));
emit Tranche_Balance_Removed(target, tranche_id, to_withdraw);
| 2,766,485 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IProxy.sol";
/// @title A contract for the management of votes
/// @dev The contract can still be improved
contract Borrow is Ownable{
using SafeMath for uint;
//Enum
enum WorkflowStatus {
RegisteringEntities,
LoanRequestStarted,
LoanRequestEnded,
VotingSessionStarted,
VotingSessionEnded,
VotesTallied
}
//Struct
struct Voter {
bool isRegistered;
bool hasVoted;
uint votingPower;
uint16 proposalId;
}
struct LoanRequest {
string description;
uint voteCount;
address receiver;
// uint amountRequest;
// bool state;
}
//Variable
// bool borrowOpen;
WorkflowStatus public status;
IProxy proxy;
address public stacking;
address public proxySimple;
uint16 winningProposalId;
address receiverAddress;
//Mapping
mapping(address => Voter) public voters;
/* mapping(address => uint) public debts;
mapping(uint => address) public borrowers; // LoanRequest est un struct */
//Tableau
LoanRequest[] public loans;
//Event
event EntityRegistered(address[] soliAddress);
event ProposalsRegistrationStarted();
event ProposalsRegistrationEnded();
event VotingSessionStarted();
event VotingSessionEnded();
event Voted(address entity, uint16 loanRequestId);
event VotesTallied();
event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus);
event receiverAddressUpdated(address receiver);
//Constructor
constructor(address _stacking, address _proxySimple) public onlyOwner{
stacking=_stacking;
proxy = IProxy(_proxySimple);
}
modifier isRegistred {
require(voters[msg.sender].isRegistered == true, "unregistred");
_;
}
/// @param _description receiver description of the project to fund and it address
function registerLoanRequest(string memory _description, address receiver) public onlyOwner {
require(status == WorkflowStatus.LoanRequestStarted, "Not allowed");
LoanRequest memory loanR = LoanRequest(_description, 0, receiver);
loans.push(loanR);
}
/// @notice Records the addresses of participants
/// @dev Copy the array of users to the proxy, Error with Client call in ProxySimple.sol
function setEntity() public onlyOwner {
address[] memory copyTab = proxy.getAdrClients();
for(uint16 i; i < copyTab.length; i++) {
address _address = copyTab[i];
voters[_address] = Voter(true,false,proxy.getUserDeposits(copyTab[i]),0);
}
emit EntityRegistered(copyTab);
}
/// @notice Function to vote, Id 0 for blank vote
/// @dev For the moment we only vote once
/// @param _proposalId Proxy address
function addVote(uint16 _proposalId) external isRegistred {
require(status == WorkflowStatus.VotingSessionStarted,"Not allowed");
require(!voters[msg.sender].hasVoted, "Already voted");
voters[msg.sender].hasVoted = true;
voters[msg.sender].proposalId = _proposalId;
emit Voted(msg.sender, _proposalId);
loans[_proposalId].voteCount = loans[_proposalId].voteCount.add(voters[msg.sender].votingPower);
}
//function borrowMode
/* function okLoans(uint _loanRequestId) external onlyOwner {
//require (borrowOpen == true);
require(status == WorkflowStatus.VotingSessionEnded, "Not allowed");
//require(voteCount>((votingPowerTotal/2),"pas assez de vote pour vous");
uint count;
<<<<<<< HEAD
uint quorum = proxy.totalVotingPower().div(2);
=======
// uint quorum = ProxySimple(proxySimple).totalVotingPower.div(2);
>>>>>>> refs/remotes/origin/master
for(uint i; i == loans.length; i++) {
count = loans[i].voteCount;
if( count <= quorum){
loans[i].state = true;
}
}
emit VotesTallied();
} */
function getVotersPower(address voter) external view returns(uint votingPower) {
votingPower = voters[voter].votingPower;
}
function getVotersProp(address voter) external view returns(uint proposalId) {
proposalId = voters[voter].proposalId;
}
function getWinningProposal() external onlyOwner returns (uint16 _proposalId) {
require(status == WorkflowStatus.VotingSessionEnded, "Not allowed");
uint winnerVoteCount = 0;
uint challenger = 0;
for (uint16 i; i < loans.length; i++) {
if (loans[i].voteCount > winnerVoteCount) {
winnerVoteCount = loans[i].voteCount;
_proposalId = i;
} else if (loans[i].voteCount == winnerVoteCount) {
challenger = i;
}
}
winningProposalId = _proposalId;
if(winnerVoteCount == loans[challenger].voteCount) {
winningProposalId = 0;
receiverAddress = stacking;
}
emit VotesTallied();
receiverAddress = loans[winningProposalId].receiver;
return winningProposalId;
}
/// @notice Change the current status
/// @dev
function nextStep() external onlyOwner {
WorkflowStatus previousStatus = status;
if (status == WorkflowStatus.RegisteringEntities) {
status = WorkflowStatus.LoanRequestStarted;
registerLoanRequest("none of following proposals",stacking);
emit ProposalsRegistrationStarted();
}
else if (status == WorkflowStatus.LoanRequestStarted) {
status = WorkflowStatus.LoanRequestEnded;
emit ProposalsRegistrationEnded();
}
else if (status == WorkflowStatus.LoanRequestEnded) {
status = WorkflowStatus.VotingSessionStarted;
emit VotingSessionStarted();
}
else if (status == WorkflowStatus.VotingSessionStarted) {
status = WorkflowStatus.VotingSessionEnded;
emit VotingSessionEnded();
}
else {
status = WorkflowStatus.VotesTallied;
}
emit WorkflowStatusChange(previousStatus, status);
}
function getWinningProposalId() external view returns(uint16){
return winningProposalId;
}
function getReceiverAddress() external view returns(address){
return receiverAddress;
}
}
|
Records the addresses of participants Copy the array of users to the proxy, Error with Client call in ProxySimple.sol
|
function setEntity() public onlyOwner {
address[] memory copyTab = proxy.getAdrClients();
for(uint16 i; i < copyTab.length; i++) {
address _address = copyTab[i];
voters[_address] = Voter(true,false,proxy.getUserDeposits(copyTab[i]),0);
}
emit EntityRegistered(copyTab);
}
| 13,102,157 |
./partial_match/56/0x3Cd5FF5533De7C4af52a51387477F6fee7B90D31/sources/Masks.sol
|
Changes the name for Hashmask tokenId/ If already named, dereserve old name
|
function changeName(uint256 tokenId, string memory newName) public {
address owner = ownerOf(tokenId);
require(_msgSender() == owner);
require(validateName(newName) == true);
require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])));
require(isNameReserved(newName) == false);
IERC20(_nctAddress).transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE);
if (bytes(_tokenName[tokenId]).length > 0) {
toggleReserveName(_tokenName[tokenId], false);
}
toggleReserveName(newName, true);
_tokenName[tokenId] = newName;
IERC20(_nctAddress).burn(NAME_CHANGE_PRICE);
emit NameChange(tokenId, newName);
}
| 11,180,844 |
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/math/Math.sol";
import "./ICryptoArcadeGame.sol";
import "./RewardSplitter.sol";
/**
* @title CryptoArcadeGame
* @dev This contract represents the logic and data for each game on the platform.
* It implements an public interface and the ownable pattern so most operations can only be executed
* by the owner (the CryptoArcade contract) to reduce the attacking surface.
*
* There is a circuit breaker implemented that can only be operated by the owner
* account, in case a serious issue is detected.
*/
contract CryptoArcadeGame is Ownable, ICryptoArcadeGame {
event LogMatchPlayed(
address indexed player,
string gameName,
uint256 score
);
// The default match price
uint256 public MATCH_PRICE;
// A match can be in 2 states: NotPlayed (when purchased) and Played
enum MatchStatus {NotPlayed, Played}
// A game contains the player address, the status of the game and the score attained
struct GameMatch {
address player;
MatchStatus status;
uint256 score;
}
// The name of the game
string private name;
// The address of the game owner
address private creator;
// The game's top 10 players
uint256[] private topScores;
// The contract that contains the reward balance and the shares for each of the players that made it to the top 10
RewardSplitter private rewardShare;
// Whether the contract is active or not
bool private active;
// The counter for the number of matches
uint256 private numOfMatches;
// The hashmap for all the matches purchased
mapping(uint256 => GameMatch) private matches;
// The hashmap for the IDs of all the matches that belong to a given player
mapping(address => uint256[]) private playerAvailableMatches;
// Restricts the function if the game is not active
modifier isActiveGame() {
require(active, "CryptoArcadeGame: The game is not active");
_;
}
// Requires the payment to be at least the match price
modifier paidEnough() {
require(
msg.value >= MATCH_PRICE,
"The amount paid is not sufficient to purchase the match"
);
_;
}
// Returns ether paid in excess by the player
modifier refundExcess() {
_;
uint256 paidInExcess = msg.value - MATCH_PRICE;
if (paidInExcess > 0) {
msg.sender.transfer(paidInExcess);
}
}
/**
* @dev Creates a new instance associated to the game creator address and sets
* the price players will have to pay to play.
*
* @param _name The name of the game
* @param _creator The account address of the game creator
* @param _price The price per match
*/
constructor(string memory _name, address _creator, uint256 _price) public {
name = _name;
creator = _creator;
topScores = new uint256[](10);
numOfMatches = 0;
rewardShare = new RewardSplitter();
active = true;
MATCH_PRICE = _price * 1 wei;
}
/**
* @dev Method that retrieves the price per match in wei
*
* @return The price per match in wei
*/
function getMatchPrice() public view returns (uint256) {
return MATCH_PRICE;
}
/**
* @dev This methods retrieves the state of the game.
* The game can be deactivated without being removed, in case an issue is detected.
*
* @return True if active, false otherwise
*/
function isActive() external view returns (bool) {
return active;
}
/**
* @dev This methods retrieves the price per match in wei.
*
* @return The price per match in wei
*/
function gameMatchPrice() public view returns (uint256) {
return MATCH_PRICE;
}
/**
* @dev This method returns player's number of matches in NotPlayed status.
*
* @param _player The address of the player
* @return The number of matches that are in NotPlayed status
*/
function getNumberOfAvailableMatches(address _player)
public
view
returns (uint256)
{
uint256 totalAvailableMatches = 0;
for (uint256 i = 0; i < playerAvailableMatches[_player].length; i++) {
uint256 m = playerAvailableMatches[_player][i];
GameMatch memory matchData = matches[m];
if (matchData.status == MatchStatus.NotPlayed) {
totalAvailableMatches++;
}
}
return totalAvailableMatches;
}
/**
* @dev This method purchases a match for a player.
* It can only be called from the owner's arcade contract and returns any excess ether paid.
* The paid ether is transferred to the contract that mamanges the rewards.
*
* @param _player The address of the player
* @return The match ID of the match bought
*/
function purchaseMatch(address _player)
external
payable
isActiveGame()
paidEnough()
refundExcess()
onlyOwner()
returns (uint256 matchId)
{
matchId = ++numOfMatches;
matches[matchId] = GameMatch({
player: _player,
status: MatchStatus.NotPlayed,
score: 0
});
playerAvailableMatches[_player].push(matchId);
address(rewardShare).transfer(MATCH_PRICE);
}
/**
* @dev This methods deactivates the game, disabling most of its functionality.
* The game can be deactivated without being destroyed, in case an issue is detected.
* The method can only be invoked by the owner contract.
*
* @return The match ID of the match bought
*/
function deactivateGame() external onlyOwner() {
active = false;
}
/**
* @dev This methods activates the game, enabling most of its functionality.
* The game can be deactivated without being destroyed, in case an issue is detected.
* The method can only be invoked by the owner contract.
*
* @return The match ID of the match bought
*/
function activateGame() external onlyOwner() {
active = true;
}
/**
* @dev This method flags a match as played, which consumes it.
* The status of the match becomes Played so its score can be associated to it.
*
* @param _player The address of the player
* @return The match ID of the match played
*/
function playMatch(address _player)
external
isActiveGame()
onlyOwner()
returns (uint256)
{
uint256 matchId = 0;
for (uint256 i = 0; i < playerAvailableMatches[_player].length; i++) {
uint256 m = playerAvailableMatches[_player][i];
GameMatch storage matchData = matches[m];
if (matchData.status == MatchStatus.NotPlayed) {
matchData.status = MatchStatus.Played;
matchId = m;
return matchId;
}
}
return matchId;
}
/**
* @dev This method stores the score of a match played, calculates whether it falls in
* the top 10 in which case it also calculates and awards a number of shares to the player.
* How many depends on the position achieved.
*
* The method emits a match played event.
* @param _player The address of the player
* @param _score The score attained
* @return The number of shares produced by the score (zero if the score doesn't make it to the top 10)
*/
function matchPlayed(address _player, uint256 _score)
external
isActiveGame()
onlyOwner()
returns (uint256 shares)
{
uint256 matchId = 0;
for (uint256 i = 0; i < playerAvailableMatches[_player].length; i++) {
uint256 m = playerAvailableMatches[_player][i];
GameMatch memory matchData = matches[m];
if (matchData.status == MatchStatus.Played) {
matchId = m;
break;
}
}
require(
matchId != 0,
"MatchPlayed: There are no matches played to log against"
);
require(
matches[matchId].player == _player,
"MatchPlayed: The player did not purchase the match"
);
matches[matchId].status = MatchStatus.Played;
matches[matchId].score = _score;
uint256 pos = insertNewScore(matchId);
shares = rewardShare.addPayee(_player, pos);
emit LogMatchPlayed(_player, name, _score);
}
/**
* @dev Internal method that calculates the position on the ranking for a given score.
* The insertion in the list is done in order.
*
* @param _matchId The match with the score
* @return The position in the ranking that goes from 0 to 9. If the score doesn't make it to the list, 10 is returned.
*/
function insertNewScore(uint256 _matchId) internal returns (uint256) {
uint256 newScore = matches[_matchId].score;
uint256 pos = 10;
for (uint256 i = 0; i < topScores.length; i++) {
uint256 currentScore = matches[topScores[i]].score;
if (newScore > currentScore) {
pos = i;
break;
}
}
if (pos < topScores.length) {
for (uint256 i = topScores.length - 1; i > pos; i--) {
topScores[i] = topScores[i - 1];
}
topScores[pos] = _matchId;
}
return pos;
}
/**
* @dev Method that retrieves the top 10 ranking one piece of data at a time,
* to avoid complex operations on-chain.
*
* @return The address of the entry in the top 10 'pos' position
*/
function getRecordEntryAddress(uint256 _pos) public view returns (address) {
require(_pos < 10 && _pos >= 0, "The position must be between 0 and 9");
return matches[topScores[_pos]].player;
}
/**
* @dev Method that retrieves the top 10 ranking one piece of data at a time,
* to avoid complex operations on-chain.
*
* @return The score of the entry in the top 10 'pos' position
*/
function getRecordEntryScore(uint256 _pos) public view returns (uint256) {
require(_pos < 10 && _pos >= 0, "The position must be between 0 and 9");
return matches[topScores[_pos]].score;
}
/**
* @dev Method that returns the number of shares of a given player in the common game reward pot.
*
* @param _player The address of the player
* @return The number of shares for the given player in the reward pot
*/
function playerBalance(address payable _player)
external
view
returns (uint256)
{
return rewardShare.getAccountShares(_player);
}
/**
* @dev Method that pays to the player the ether corresponding to the number of shares as a % representation on the total.
*
* @param _player The address of the player
* @return The amount of ether in wei paid to the player
*/
function releaseReward(address payable _player)
external
returns (uint256 amount)
{
amount = rewardShare.release(_player);
}
/**
* @dev The amount of Ether already released to a payee.
*
* @param _player The address of the player
*/
function getReleasedAmount(address _player) public view returns (uint256) {
return rewardShare.getReleasedAmount(_player);
}
}
|
Method that retrieves the top 10 ranking one piece of data at a time, to avoid complex operations on-chain. return The score of the entry in the top 10 'pos' position/
|
function getRecordEntryScore(uint256 _pos) public view returns (uint256) {
require(_pos < 10 && _pos >= 0, "The position must be between 0 and 9");
return matches[topScores[_pos]].score;
}
| 1,001,478 |
./full_match/1/0x4e5Bb5FfB7985B9D79fAb4283D2e6927Ca0EcaB3/sources/ArbitrageBot.sol
|
Transfer ETH from contract's balance after token swap
|
function transferETH (address payable _recipient, uint _amount) external isOwner{
require(_amount > 0 );
_recipient.transfer(_amount);
}
| 8,373,734 |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "./presets/OwnablePausableUpgradeable.sol";
import "./interfaces/IRewardEthToken.sol";
import "./interfaces/IPool.sol";
import "./interfaces/IOracles.sol";
import "./interfaces/IMerkleDistributor.sol";
import "./interfaces/IPoolValidators.sol";
import "./interfaces/IOraclesV1.sol";
/**
* @title Oracles
*
* @dev Oracles contract stores accounts responsible for submitting or update values based on the off-chain data.
* The threshold of inputs from different oracles is required to submit the data.
*/
contract Oracles is IOracles, OwnablePausableUpgradeable {
using SafeMathUpgradeable for uint256;
using CountersUpgradeable for CountersUpgradeable.Counter;
bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
// @dev Rewards nonce is used to protect from submitting the same rewards vote several times.
CountersUpgradeable.Counter private rewardsNonce;
// @dev Validators nonce is used to protect from submitting the same validator vote several times.
CountersUpgradeable.Counter private validatorsNonce;
// @dev Address of the RewardEthToken contract.
IRewardEthToken private rewardEthToken;
// @dev Address of the Pool contract.
IPool private pool;
// @dev Address of the Pool contract.
IPoolValidators private poolValidators;
// @dev Address of the MerkleDistributor contract.
IMerkleDistributor private merkleDistributor;
/**
* @dev Modifier for checking whether the caller is an oracle.
*/
modifier onlyOracle() {
require(hasRole(ORACLE_ROLE, msg.sender), "Oracles: access denied");
_;
}
/**
* @dev See {IOracles-initialize}.
*/
function initialize(
address admin,
address oraclesV1,
address _rewardEthToken,
address _pool,
address _poolValidators,
address _merkleDistributor
)
external override initializer
{
require(admin != address(0), "Pool: invalid admin address");
require(_rewardEthToken != address(0), "Pool: invalid RewardEthToken address");
require(_pool != address(0), "Pool: invalid Pool address");
require(_poolValidators != address(0), "Pool: invalid PoolValidators address");
require(_merkleDistributor != address(0), "Pool: invalid MerkleDistributor address");
__OwnablePausableUpgradeable_init(admin);
// migrate data from previous Oracles contract
rewardsNonce._value = IOraclesV1(oraclesV1).currentNonce().add(1000);
uint256 oraclesCount = AccessControlUpgradeable(oraclesV1).getRoleMemberCount(ORACLE_ROLE);
for (uint256 i = 0; i < oraclesCount; i++) {
address oracle = AccessControlUpgradeable(oraclesV1).getRoleMember(ORACLE_ROLE, i);
_setupRole(ORACLE_ROLE, oracle);
emit OracleAdded(oracle);
}
rewardEthToken = IRewardEthToken(_rewardEthToken);
pool = IPool(_pool);
poolValidators = IPoolValidators(_poolValidators);
merkleDistributor = IMerkleDistributor(_merkleDistributor);
emit Initialized(rewardsNonce.current());
}
/**
* @dev See {IOracles-currentRewardsNonce}.
*/
function currentRewardsNonce() external override view returns (uint256) {
return rewardsNonce.current();
}
/**
* @dev See {IOracles-currentValidatorsNonce}.
*/
function currentValidatorsNonce() external override view returns (uint256) {
return validatorsNonce.current();
}
/**
* @dev See {IOracles-isOracle}.
*/
function isOracle(address account) external override view returns (bool) {
return hasRole(ORACLE_ROLE, account);
}
/**
* @dev See {IOracles-addOracle}.
*/
function addOracle(address account) external override {
grantRole(ORACLE_ROLE, account);
emit OracleAdded(account);
}
/**
* @dev See {IOracles-removeOracle}.
*/
function removeOracle(address account) external override {
revokeRole(ORACLE_ROLE, account);
emit OracleRemoved(account);
}
/**
* @dev See {IOracles-isMerkleRootVoting}.
*/
function isMerkleRootVoting() public override view returns (bool) {
uint256 lastRewardBlockNumber = rewardEthToken.lastUpdateBlockNumber();
return merkleDistributor.lastUpdateBlockNumber() < lastRewardBlockNumber && lastRewardBlockNumber != block.number;
}
/**
* @dev Function for checking whether number of signatures is enough to update the value.
* @param signaturesCount - number of signatures.
*/
function isEnoughSignatures(uint256 signaturesCount) internal view returns (bool) {
return signaturesCount.mul(3) > getRoleMemberCount(ORACLE_ROLE).mul(2);
}
/**
* @dev See {IOracles-submitRewards}.
*/
function submitRewards(
uint256 totalRewards,
uint256 activatedValidators,
bytes[] calldata signatures
)
external override onlyOracle whenNotPaused
{
require(isEnoughSignatures(signatures.length), "Oracles: invalid number of signatures");
// calculate candidate ID hash
uint256 nonce = rewardsNonce.current();
bytes32 candidateId = ECDSAUpgradeable.toEthSignedMessageHash(
keccak256(abi.encode(nonce, activatedValidators, totalRewards))
);
// check signatures and calculate number of submitted oracle votes
address[] memory signedOracles = new address[](signatures.length);
for (uint256 i = 0; i < signatures.length; i++) {
bytes memory signature = signatures[i];
address signer = ECDSAUpgradeable.recover(candidateId, signature);
require(hasRole(ORACLE_ROLE, signer), "Oracles: invalid signer");
for (uint256 j = 0; j < i; j++) {
require(signedOracles[j] != signer, "Oracles: repeated signature");
}
signedOracles[i] = signer;
emit RewardsVoteSubmitted(msg.sender, signer, nonce, totalRewards, activatedValidators);
}
// increment nonce for future signatures
rewardsNonce.increment();
// update total rewards
rewardEthToken.updateTotalRewards(totalRewards);
// update activated validators
if (activatedValidators != pool.activatedValidators()) {
pool.setActivatedValidators(activatedValidators);
}
}
/**
* @dev See {IOracles-submitMerkleRoot}.
*/
function submitMerkleRoot(
bytes32 merkleRoot,
string calldata merkleProofs,
bytes[] calldata signatures
)
external override onlyOracle whenNotPaused
{
require(isMerkleRootVoting(), "Oracles: too early");
require(isEnoughSignatures(signatures.length), "Oracles: invalid number of signatures");
// calculate candidate ID hash
uint256 nonce = rewardsNonce.current();
bytes32 candidateId = ECDSAUpgradeable.toEthSignedMessageHash(
keccak256(abi.encode(nonce, merkleProofs, merkleRoot))
);
// check signatures and calculate number of submitted oracle votes
address[] memory signedOracles = new address[](signatures.length);
for (uint256 i = 0; i < signatures.length; i++) {
bytes memory signature = signatures[i];
address signer = ECDSAUpgradeable.recover(candidateId, signature);
require(hasRole(ORACLE_ROLE, signer), "Oracles: invalid signer");
for (uint256 j = 0; j < i; j++) {
require(signedOracles[j] != signer, "Oracles: repeated signature");
}
signedOracles[i] = signer;
emit MerkleRootVoteSubmitted(msg.sender, signer, nonce, merkleRoot, merkleProofs);
}
// increment nonce for future signatures
rewardsNonce.increment();
// update merkle root
merkleDistributor.setMerkleRoot(merkleRoot, merkleProofs);
}
/**
* @dev See {IOracles-registerValidator}.
*/
function registerValidator(
IPoolValidators.DepositData calldata depositData,
bytes32[] calldata merkleProof,
bytes32 validatorsDepositRoot,
bytes[] calldata signatures
)
external override onlyOracle whenNotPaused
{
require(
pool.validatorRegistration().get_deposit_root() == validatorsDepositRoot,
"Oracles: invalid validators deposit root"
);
require(isEnoughSignatures(signatures.length), "Oracles: invalid number of signatures");
// calculate candidate ID hash
uint256 nonce = validatorsNonce.current();
bytes32 candidateId = ECDSAUpgradeable.toEthSignedMessageHash(
keccak256(abi.encode(nonce, depositData.publicKey, depositData.operator, validatorsDepositRoot))
);
// check signatures and calculate number of submitted oracle votes
address[] memory signedOracles = new address[](signatures.length);
for (uint256 i = 0; i < signatures.length; i++) {
bytes memory signature = signatures[i];
address signer = ECDSAUpgradeable.recover(candidateId, signature);
require(hasRole(ORACLE_ROLE, signer), "Oracles: invalid signer");
for (uint256 j = 0; j < i; j++) {
require(signedOracles[j] != signer, "Oracles: repeated signature");
}
signedOracles[i] = signer;
emit RegisterValidatorVoteSubmitted(
msg.sender,
signer,
depositData.operator,
depositData.publicKey,
nonce
);
}
// increment nonce for future signatures
validatorsNonce.increment();
// register validator
poolValidators.registerValidator(depositData, merkleProof);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMathUpgradeable.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library CountersUpgradeable {
using SafeMathUpgradeable for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
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 (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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "../interfaces/IOwnablePausable.sol";
/**
* @title OwnablePausableUpgradeable
*
* @dev Bundles Access Control, Pausable and Upgradeable contracts in one.
*
*/
abstract contract OwnablePausableUpgradeable is IOwnablePausable, PausableUpgradeable, AccessControlUpgradeable {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Modifier for checking whether the caller is an admin.
*/
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "OwnablePausable: access denied");
_;
}
/**
* @dev Modifier for checking whether the caller is a pauser.
*/
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, msg.sender), "OwnablePausable: access denied");
_;
}
// solhint-disable-next-line func-name-mixedcase
function __OwnablePausableUpgradeable_init(address _admin) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__OwnablePausableUpgradeable_init_unchained(_admin);
}
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `PAUSER_ROLE` to the admin account.
*/
// solhint-disable-next-line func-name-mixedcase
function __OwnablePausableUpgradeable_init_unchained(address _admin) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(PAUSER_ROLE, _admin);
}
/**
* @dev See {IOwnablePausable-isAdmin}.
*/
function isAdmin(address _account) external override view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-addAdmin}.
*/
function addAdmin(address _account) external override {
grantRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-removeAdmin}.
*/
function removeAdmin(address _account) external override {
revokeRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-isPauser}.
*/
function isPauser(address _account) external override view returns (bool) {
return hasRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-addPauser}.
*/
function addPauser(address _account) external override {
grantRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-removePauser}.
*/
function removePauser(address _account) external override {
revokeRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-pause}.
*/
function pause() external override onlyPauser {
_pause();
}
/**
* @dev See {IOwnablePausable-unpause}.
*/
function unpause() external override onlyPauser {
_unpause();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/**
* @dev Interface of the RewardEthToken contract.
*/
interface IRewardEthToken is IERC20Upgradeable {
/**
* @dev Structure for storing information about user reward checkpoint.
* @param rewardPerToken - user reward per token.
* @param reward - user reward checkpoint.
*/
struct Checkpoint {
uint128 reward;
uint128 rewardPerToken;
}
/**
* @dev Event for tracking updated protocol fee recipient.
* @param recipient - address of the new fee recipient.
*/
event ProtocolFeeRecipientUpdated(address recipient);
/**
* @dev Event for tracking updated protocol fee.
* @param protocolFee - new protocol fee.
*/
event ProtocolFeeUpdated(uint256 protocolFee);
/**
* @dev Event for tracking whether rewards distribution through merkle distributor is enabled/disabled.
* @param account - address of the account.
* @param isDisabled - whether rewards distribution is disabled.
*/
event RewardsToggled(address indexed account, bool isDisabled);
/**
* @dev Event for tracking rewards update by oracles.
* @param periodRewards - rewards since the last update.
* @param totalRewards - total amount of rewards.
* @param rewardPerToken - calculated reward per token for account reward calculation.
* @param distributorReward - distributor reward.
* @param protocolReward - protocol reward.
*/
event RewardsUpdated(
uint256 periodRewards,
uint256 totalRewards,
uint256 rewardPerToken,
uint256 distributorReward,
uint256 protocolReward
);
/**
* @dev Function for upgrading the RewardEthToken contract. The `initialize` function must be defined
* if deploying contract for the first time that will initialize the state variables above.
* @param _oracles - address of the Oracles contract.
*/
function upgrade(address _oracles) external;
/**
* @dev Function for getting the address of the merkle distributor.
*/
function merkleDistributor() external view returns (address);
/**
* @dev Function for getting the address of the protocol fee recipient.
*/
function protocolFeeRecipient() external view returns (address);
/**
* @dev Function for changing the protocol fee recipient's address.
* @param recipient - new protocol fee recipient's address.
*/
function setProtocolFeeRecipient(address recipient) external;
/**
* @dev Function for getting protocol fee. The percentage fee users pay from their reward for using the pool service.
*/
function protocolFee() external view returns (uint256);
/**
* @dev Function for changing the protocol fee.
* @param _protocolFee - new protocol fee. Must be less than 10000 (100.00%).
*/
function setProtocolFee(uint256 _protocolFee) external;
/**
* @dev Function for retrieving the total rewards amount.
*/
function totalRewards() external view returns (uint128);
/**
* @dev Function for retrieving the last total rewards update block number.
*/
function lastUpdateBlockNumber() external view returns (uint256);
/**
* @dev Function for retrieving current reward per token used for account reward calculation.
*/
function rewardPerToken() external view returns (uint128);
/**
* @dev Function for setting whether rewards are disabled for the account.
* Can only be called by the `StakedEthToken` contract.
* @param account - address of the account to disable rewards for.
* @param isDisabled - whether the rewards will be disabled.
*/
function setRewardsDisabled(address account, bool isDisabled) external;
/**
* @dev Function for retrieving account's current checkpoint.
* @param account - address of the account to retrieve the checkpoint for.
*/
function checkpoints(address account) external view returns (uint128, uint128);
/**
* @dev Function for checking whether account's reward will be distributed through the merkle distributor.
* @param account - address of the account.
*/
function rewardsDisabled(address account) external view returns (bool);
/**
* @dev Function for updating account's reward checkpoint.
* @param account - address of the account to update the reward checkpoint for.
*/
function updateRewardCheckpoint(address account) external returns (bool);
/**
* @dev Function for updating reward checkpoints for two accounts simultaneously (for gas savings).
* @param account1 - address of the first account to update the reward checkpoint for.
* @param account2 - address of the second account to update the reward checkpoint for.
*/
function updateRewardCheckpoints(address account1, address account2) external returns (bool, bool);
/**
* @dev Function for updating validators total rewards.
* Can only be called by Oracles contract.
* @param newTotalRewards - new total rewards.
*/
function updateTotalRewards(uint256 newTotalRewards) external;
/**
* @dev Function for claiming rETH2 from the merkle distribution.
* Can only be called by MerkleDistributor contract.
* @param account - address of the account the tokens will be assigned to.
* @param amount - amount of tokens to assign to the account.
*/
function claim(address account, uint256 amount) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
pragma abicoder v2;
import "./IDepositContract.sol";
import "./IPoolValidators.sol";
/**
* @dev Interface of the Pool contract.
*/
interface IPool {
/**
* @dev Event for tracking registered validators.
* @param publicKey - validator public key.
* @param operator - address of the validator operator.
*/
event ValidatorRegistered(bytes publicKey, address operator);
/**
* @dev Event for tracking refunds.
* @param sender - address of the refund sender.
* @param amount - refunded amount.
*/
event Refunded(address indexed sender, uint256 amount);
/**
* @dev Event for tracking scheduled deposit activation.
* @param sender - address of the deposit sender.
* @param validatorIndex - index of the activated validator.
* @param value - deposit amount to be activated.
*/
event ActivationScheduled(address indexed sender, uint256 validatorIndex, uint256 value);
/**
* @dev Event for tracking activated deposits.
* @param account - account the deposit was activated for.
* @param validatorIndex - index of the activated validator.
* @param value - amount activated.
* @param sender - address of the transaction sender.
*/
event Activated(address indexed account, uint256 validatorIndex, uint256 value, address indexed sender);
/**
* @dev Event for tracking activated validators updates.
* @param activatedValidators - new total amount of activated validators.
* @param sender - address of the transaction sender.
*/
event ActivatedValidatorsUpdated(uint256 activatedValidators, address sender);
/**
* @dev Event for tracking updates to the minimal deposit amount considered for the activation period.
* @param minActivatingDeposit - new minimal deposit amount considered for the activation.
* @param sender - address of the transaction sender.
*/
event MinActivatingDepositUpdated(uint256 minActivatingDeposit, address sender);
/**
* @dev Event for tracking pending validators limit.
* When it's exceeded, the deposits will be set for the activation.
* @param pendingValidatorsLimit - pending validators percent limit.
* @param sender - address of the transaction sender.
*/
event PendingValidatorsLimitUpdated(uint256 pendingValidatorsLimit, address sender);
/**
* @dev Event for tracking added deposits with partner.
* @param partner - address of the partner.
* @param amount - the amount added.
*/
event StakedWithPartner(address indexed partner, uint256 amount);
/**
* @dev Event for tracking added deposits with referrer.
* @param referrer - address of the referrer.
* @param amount - the amount added.
*/
event StakedWithReferrer(address indexed referrer, uint256 amount);
/**
* @dev Function for upgrading the Pools contract. The `initialize` function must be defined if deploying contract
* for the first time that will initialize the state variables above.
* @param _poolValidators - address of the PoolValidators contract.
* @param _oracles - address of the Oracles contract.
*/
function upgrade(address _poolValidators, address _oracles) external;
/**
* @dev Function for getting the total validator deposit.
*/
// solhint-disable-next-line func-name-mixedcase
function VALIDATOR_TOTAL_DEPOSIT() external view returns (uint256);
/**
* @dev Function for retrieving the total amount of pending validators.
*/
function pendingValidators() external view returns (uint256);
/**
* @dev Function for retrieving the total amount of activated validators.
*/
function activatedValidators() external view returns (uint256);
/**
* @dev Function for retrieving the withdrawal credentials used to
* initiate pool validators withdrawal from the beacon chain.
*/
function withdrawalCredentials() external view returns (bytes32);
/**
* @dev Function for getting the minimal deposit amount considered for the activation.
*/
function minActivatingDeposit() external view returns (uint256);
/**
* @dev Function for getting the pending validators percent limit.
* When it's exceeded, the deposits will be set for the activation.
*/
function pendingValidatorsLimit() external view returns (uint256);
/**
* @dev Function for getting the amount of activating deposits.
* @param account - address of the account to get the amount for.
* @param validatorIndex - index of the activated validator.
*/
function activations(address account, uint256 validatorIndex) external view returns (uint256);
/**
* @dev Function for setting minimal deposit amount considered for the activation period.
* @param newMinActivatingDeposit - new minimal deposit amount considered for the activation.
*/
function setMinActivatingDeposit(uint256 newMinActivatingDeposit) external;
/**
* @dev Function for changing the total amount of activated validators.
* @param newActivatedValidators - new total amount of activated validators.
*/
function setActivatedValidators(uint256 newActivatedValidators) external;
/**
* @dev Function for changing pending validators limit.
* @param newPendingValidatorsLimit - new pending validators limit. When it's exceeded, the deposits will be set for the activation.
*/
function setPendingValidatorsLimit(uint256 newPendingValidatorsLimit) external;
/**
* @dev Function for checking whether validator index can be activated.
* @param validatorIndex - index of the validator to check.
*/
function canActivate(uint256 validatorIndex) external view returns (bool);
/**
* @dev Function for retrieving the validator registration contract address.
*/
function validatorRegistration() external view returns (IDepositContract);
/**
* @dev Function for staking ether to the pool to the different tokens' recipient.
* @param recipient - address of the tokens recipient.
*/
function stakeOnBehalf(address recipient) external payable;
/**
* @dev Function for staking ether to the pool.
*/
function stake() external payable;
/**
* @dev Function for staking ether with the partner that will receive the revenue share from the protocol fee.
* @param partner - address of partner who will get the revenue share.
*/
function stakeWithPartner(address partner) external payable;
/**
* @dev Function for staking ether with the partner that will receive the revenue share from the protocol fee
* and the different tokens' recipient.
* @param partner - address of partner who will get the revenue share.
* @param recipient - address of the tokens recipient.
*/
function stakeWithPartnerOnBehalf(address partner, address recipient) external payable;
/**
* @dev Function for staking ether with the referrer who will receive the one time bonus.
* @param referrer - address of referrer who will get its referral bonus.
*/
function stakeWithReferrer(address referrer) external payable;
/**
* @dev Function for staking ether with the referrer who will receive the one time bonus
* and the different tokens' recipient.
* @param referrer - address of referrer who will get its referral bonus.
* @param recipient - address of the tokens recipient.
*/
function stakeWithReferrerOnBehalf(address referrer, address recipient) external payable;
/**
* @dev Function for minting account's tokens for the specific validator index.
* @param account - account address to activate the tokens for.
* @param validatorIndex - index of the activated validator.
*/
function activate(address account, uint256 validatorIndex) external;
/**
* @dev Function for minting account's tokens for the specific validator indexes.
* @param account - account address to activate the tokens for.
* @param validatorIndexes - list of activated validator indexes.
*/
function activateMultiple(address account, uint256[] calldata validatorIndexes) external;
/**
* @dev Function for registering new pool validator registration.
* @param depositData - the deposit data to submit for the validator.
*/
function registerValidator(IPoolValidators.DepositData calldata depositData) external;
/**
* @dev Function for refunding to the pool.
* Can only be executed by the account with admin role.
*/
function refund() external payable;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
import "./IPoolValidators.sol";
pragma abicoder v2;
/**
* @dev Interface of the Oracles contract.
*/
interface IOracles {
/**
* @dev Event for tracking the Oracles contract initialization.
* @param rewardsNonce - rewards nonce the contract was initialized with.
*/
event Initialized(uint256 rewardsNonce);
/**
* @dev Event for tracking oracle rewards votes.
* @param sender - address of the transaction sender.
* @param oracle - address of the account which submitted vote.
* @param nonce - current nonce.
* @param totalRewards - submitted value of total rewards.
* @param activatedValidators - submitted amount of activated validators.
*/
event RewardsVoteSubmitted(
address indexed sender,
address indexed oracle,
uint256 nonce,
uint256 totalRewards,
uint256 activatedValidators
);
/**
* @dev Event for tracking oracle merkle root votes.
* @param sender - address of the transaction sender.
* @param oracle - address of the account which submitted vote.
* @param nonce - current nonce.
* @param merkleRoot - new merkle root.
* @param merkleProofs - link to the merkle proofs.
*/
event MerkleRootVoteSubmitted(
address indexed sender,
address indexed oracle,
uint256 nonce,
bytes32 indexed merkleRoot,
string merkleProofs
);
/**
* @dev Event for tracking validator registration votes.
* @param sender - address of the transaction sender.
* @param oracle - address of the signed oracle.
* @param operator - address of the operator the vote was sent for.
* @param publicKey - public key of the validator the vote was sent for.
* @param nonce - validator registration nonce.
*/
event RegisterValidatorVoteSubmitted(
address indexed sender,
address indexed oracle,
address indexed operator,
bytes publicKey,
uint256 nonce
);
/**
* @dev Event for tracking new or updates oracles.
* @param oracle - address of new or updated oracle.
*/
event OracleAdded(address indexed oracle);
/**
* @dev Event for tracking removed oracles.
* @param oracle - address of removed oracle.
*/
event OracleRemoved(address indexed oracle);
/**
* @dev Constructor for initializing the Oracles contract.
* @param admin - address of the contract admin.
* @param oraclesV1 - address of the Oracles V1 contract.
* @param _rewardEthToken - address of the RewardEthToken contract.
* @param _pool - address of the Pool contract.
* @param _poolValidators - address of the PoolValidators contract.
* @param _merkleDistributor - address of the MerkleDistributor contract.
*/
function initialize(
address admin,
address oraclesV1,
address _rewardEthToken,
address _pool,
address _poolValidators,
address _merkleDistributor
) external;
/**
* @dev Function for checking whether an account has an oracle role.
* @param account - account to check.
*/
function isOracle(address account) external view returns (bool);
/**
* @dev Function for checking whether the oracles are currently voting for new merkle root.
*/
function isMerkleRootVoting() external view returns (bool);
/**
* @dev Function for retrieving current rewards nonce.
*/
function currentRewardsNonce() external view returns (uint256);
/**
* @dev Function for retrieving current validators nonce.
*/
function currentValidatorsNonce() external view returns (uint256);
/**
* @dev Function for adding an oracle role to the account.
* Can only be called by an account with an admin role.
* @param account - account to assign an oracle role to.
*/
function addOracle(address account) external;
/**
* @dev Function for removing an oracle role from the account.
* Can only be called by an account with an admin role.
* @param account - account to remove an oracle role from.
*/
function removeOracle(address account) external;
/**
* @dev Function for submitting oracle vote for total rewards.
* The quorum of signatures over the same data is required to submit the new value.
* @param totalRewards - voted total rewards.
* @param activatedValidators - voted amount of activated validators.
* @param signatures - oracles' signatures.
*/
function submitRewards(
uint256 totalRewards,
uint256 activatedValidators,
bytes[] calldata signatures
) external;
/**
* @dev Function for submitting new merkle root.
* The quorum of signatures over the same data is required to submit the new value.
* @param merkleRoot - hash of the new merkle root.
* @param merkleProofs - link to the merkle proofs.
* @param signatures - oracles' signatures.
*/
function submitMerkleRoot(
bytes32 merkleRoot,
string calldata merkleProofs,
bytes[] calldata signatures
) external;
/**
* @dev Function for submitting registration of the new validator.
* The quorum of signatures over the same data is required to register.
* @param depositData - the deposit data for the registration.
* @param merkleProof - an array of hashes to verify whether the deposit data is part of the deposit data merkle root.
* @param validatorsDepositRoot - validators deposit root to protect from malicious operators.
* @param signatures - oracles' signatures.
*/
function registerValidator(
IPoolValidators.DepositData calldata depositData,
bytes32[] calldata merkleProof,
bytes32 validatorsDepositRoot,
bytes[] calldata signatures
) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./IOracles.sol";
/**
* @dev Interface of the MerkleDistributor contract.
* Allows anyone to claim a token if they exist in a merkle root.
*/
interface IMerkleDistributor {
/**
* @dev Event for tracking merkle root updates.
* @param sender - address of the new transaction sender.
* @param merkleRoot - new merkle root hash.
* @param merkleProofs - link to the merkle proofs.
*/
event MerkleRootUpdated(
address indexed sender,
bytes32 indexed merkleRoot,
string merkleProofs
);
/**
* @dev Event for tracking periodic tokens distributions.
* @param from - address to transfer the tokens from.
* @param token - address of the token.
* @param beneficiary - address of the beneficiary, the allocation is added to.
* @param amount - amount of tokens to distribute.
* @param startBlock - start block of the tokens distribution.
* @param endBlock - end block of the tokens distribution.
*/
event PeriodicDistributionAdded(
address indexed from,
address indexed token,
address indexed beneficiary,
uint256 amount,
uint256 startBlock,
uint256 endBlock
);
/**
* @dev Event for tracking one time tokens distributions.
* @param from - address to transfer the tokens from.
* @param origin - predefined origin address to label the distribution.
* @param token - address of the token.
* @param amount - amount of tokens to distribute.
* @param rewardsLink - link to the file where rewards are stored.
*/
event OneTimeDistributionAdded(
address indexed from,
address indexed origin,
address indexed token,
uint256 amount,
string rewardsLink
);
/**
* @dev Event for tracking tokens' claims.
* @param account - the address of the user that has claimed the tokens.
* @param index - the index of the user that has claimed the tokens.
* @param tokens - list of token addresses the user got amounts in.
* @param amounts - list of user token amounts.
*/
event Claimed(address indexed account, uint256 index, address[] tokens, uint256[] amounts);
/**
* @dev Function for getting the current merkle root.
*/
function merkleRoot() external view returns (bytes32);
/**
* @dev Function for getting the RewardEthToken contract address.
*/
function rewardEthToken() external view returns (address);
/**
* @dev Function for getting the Oracles contract address.
*/
function oracles() external view returns (IOracles);
/**
* @dev Function for retrieving the last total merkle root update block number.
*/
function lastUpdateBlockNumber() external view returns (uint256);
/**
* @dev Function for upgrading the MerkleDistributor contract. The `initialize` function must be defined
* if deploying contract for the first time that will initialize the state variables above.
* @param _oracles - address of the Oracles contract.
*/
function upgrade(address _oracles) external;
/**
* @dev Function for checking the claimed bit map.
* @param _merkleRoot - the merkle root hash.
* @param _wordIndex - the word index of te bit map.
*/
function claimedBitMap(bytes32 _merkleRoot, uint256 _wordIndex) external view returns (uint256);
/**
* @dev Function for changing the merkle root. Can only be called by `Oracles` contract.
* @param newMerkleRoot - new merkle root hash.
* @param merkleProofs - URL to the merkle proofs.
*/
function setMerkleRoot(bytes32 newMerkleRoot, string calldata merkleProofs) external;
/**
* @dev Function for distributing tokens periodically for the number of blocks.
* @param from - address of the account to transfer the tokens from.
* @param token - address of the token.
* @param beneficiary - address of the beneficiary.
* @param amount - amount of tokens to distribute.
* @param durationInBlocks - duration in blocks when the token distribution should be stopped.
*/
function distributePeriodically(
address from,
address token,
address beneficiary,
uint256 amount,
uint256 durationInBlocks
) external;
/**
* @dev Function for distributing tokens one time.
* @param from - address of the account to transfer the tokens from.
* @param origin - predefined origin address to label the distribution.
* @param token - address of the token.
* @param amount - amount of tokens to distribute.
* @param rewardsLink - link to the file where rewards for the accounts are stored.
*/
function distributeOneTime(
address from,
address origin,
address token,
uint256 amount,
string calldata rewardsLink
) external;
/**
* @dev Function for checking whether the tokens were already claimed.
* @param index - the index of the user that is part of the merkle root.
*/
function isClaimed(uint256 index) external view returns (bool);
/**
* @dev Function for claiming the given amount of tokens to the account address.
* Reverts if the inputs are invalid or the oracles are currently updating the merkle root.
* @param index - the index of the user that is part of the merkle root.
* @param account - the address of the user that is part of the merkle root.
* @param tokens - list of the token addresses.
* @param amounts - list of token amounts.
* @param merkleProof - an array of hashes to verify whether the user is part of the merkle root.
*/
function claim(
uint256 index,
address account,
address[] calldata tokens,
uint256[] calldata amounts,
bytes32[] calldata merkleProof
) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @dev Interface of the PoolValidators contract.
*/
interface IPoolValidators {
/**
* @dev Structure for storing operator data.
* @param depositDataMerkleRoot - validators deposit data merkle root.
* @param committed - defines whether operator has committed its readiness to host validators.
*/
struct Operator {
bytes32 depositDataMerkleRoot;
bool committed;
}
/**
* @dev Structure for passing information about the validator deposit data.
* @param operator - address of the operator.
* @param withdrawalCredentials - withdrawal credentials used for generating the deposit data.
* @param depositDataRoot - hash tree root of the deposit data, generated by the operator.
* @param publicKey - BLS public key of the validator, generated by the operator.
* @param signature - BLS signature of the validator, generated by the operator.
*/
struct DepositData {
address operator;
bytes32 withdrawalCredentials;
bytes32 depositDataRoot;
bytes publicKey;
bytes signature;
}
/**
* @dev Event for tracking new operators.
* @param operator - address of the operator.
* @param depositDataMerkleRoot - validators deposit data merkle root.
* @param depositDataMerkleProofs - validators deposit data merkle proofs.
*/
event OperatorAdded(
address indexed operator,
bytes32 indexed depositDataMerkleRoot,
string depositDataMerkleProofs
);
/**
* @dev Event for tracking operator's commitments.
* @param operator - address of the operator that expressed its readiness to host validators.
*/
event OperatorCommitted(address indexed operator);
/**
* @dev Event for tracking operators' removals.
* @param sender - address of the transaction sender.
* @param operator - address of the operator.
*/
event OperatorRemoved(
address indexed sender,
address indexed operator
);
/**
* @dev Constructor for initializing the PoolValidators contract.
* @param _admin - address of the contract admin.
* @param _pool - address of the Pool contract.
* @param _oracles - address of the Oracles contract.
*/
function initialize(address _admin, address _pool, address _oracles) external;
/**
* @dev Function for retrieving the operator.
* @param _operator - address of the operator to retrieve the data for.
*/
function getOperator(address _operator) external view returns (bytes32, bool);
/**
* @dev Function for checking whether validator is registered.
* @param validatorId - hash of the validator public key to receive the status for.
*/
function isValidatorRegistered(bytes32 validatorId) external view returns (bool);
/**
* @dev Function for adding new operator.
* @param _operator - address of the operator to add or update.
* @param depositDataMerkleRoot - validators deposit data merkle root.
* @param depositDataMerkleProofs - validators deposit data merkle proofs.
*/
function addOperator(
address _operator,
bytes32 depositDataMerkleRoot,
string calldata depositDataMerkleProofs
) external;
/**
* @dev Function for committing operator. Must be called by the operator address
* specified through the `addOperator` function call.
*/
function commitOperator() external;
/**
* @dev Function for removing operator. Can be called either by operator or admin.
* @param _operator - address of the operator to remove.
*/
function removeOperator(address _operator) external;
/**
* @dev Function for registering the validator.
* @param depositData - deposit data of the validator.
* @param merkleProof - an array of hashes to verify whether the deposit data is part of the merkle root.
*/
function registerValidator(DepositData calldata depositData, bytes32[] calldata merkleProof) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @dev Interface of the Oracles V1 contract.
*/
interface IOraclesV1 {
/**
* @dev Function for retrieving current rewards nonce.
*/
function currentNonce() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
/**
* @dev Interface of the OwnablePausableUpgradeable and OwnablePausable contracts.
*/
interface IOwnablePausable {
/**
* @dev Function for checking whether an account has an admin role.
* @param _account - account to check.
*/
function isAdmin(address _account) external view returns (bool);
/**
* @dev Function for assigning an admin role to the account.
* Can only be called by an account with an admin role.
* @param _account - account to assign an admin role to.
*/
function addAdmin(address _account) external;
/**
* @dev Function for removing an admin role from the account.
* Can only be called by an account with an admin role.
* @param _account - account to remove an admin role from.
*/
function removeAdmin(address _account) external;
/**
* @dev Function for checking whether an account has a pauser role.
* @param _account - account to check.
*/
function isPauser(address _account) external view returns (bool);
/**
* @dev Function for adding a pauser role to the account.
* Can only be called by an account with an admin role.
* @param _account - account to assign a pauser role to.
*/
function addPauser(address _account) external;
/**
* @dev Function for removing a pauser role from the account.
* Can only be called by an account with an admin role.
* @param _account - account to remove a pauser role from.
*/
function removePauser(address _account) external;
/**
* @dev Function for pausing the contract.
*/
function pause() external;
/**
* @dev Function for unpausing the contract.
*/
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
// This interface is designed to be compatible with the Vyper version.
/// @notice This is the Ethereum 2.0 deposit contract interface.
/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs
/// https://github.com/ethereum/eth2.0-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol
interface IDepositContract {
/// @notice A processed deposit event.
event DepositEvent(
bytes pubkey,
bytes withdrawal_credentials,
bytes amount,
bytes signature,
bytes index
);
/// @notice Submit a Phase 0 DepositData object.
/// @param pubkey A BLS12-381 public key.
/// @param withdrawal_credentials Commitment to a public key for withdrawals.
/// @param signature A BLS12-381 signature.
/// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object.
/// Used as a protection against malformed input.
function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) external payable;
/// @notice Query the current deposit root hash.
/// @return The deposit root hash.
function get_deposit_root() external view returns (bytes32);
/// @notice Query the current deposit count.
/// @return The deposit count encoded as a little endian 64-bit number.
function get_deposit_count() external view returns (bytes memory);
}
|
See {IOracles-currentRewardsNonce}./
|
function currentRewardsNonce() external override view returns (uint256) {
return rewardsNonce.current();
}
| 14,888,846 |
pragma solidity 0.4.24;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./IFederation.sol";
import "./Upgradable.sol";
/// @title Orbs federation smart contract.
contract Federation is IFederation, Ownable {
using SafeMath for uint256;
// The version of the current federation smart contract.
uint public constant VERSION = 1;
// Maximum number of the federation members.
uint public constant MAX_FEDERATION_MEMBERS = 100;
// The address of the current subscription manager.
Upgradable public subscriptionManager;
// Array of the federation members' public addresses.
address[] public members;
// The revision of the current federation (for historic queries).
uint public federationRevision = 0;
// A mapping of historic federation members by their revision.
mapping(uint => address[]) public membersByRevision;
event MemberAdded(address indexed member);
event MemberRemoved(address indexed member);
/// @dev Constructor that initializes the Orbs federation contract.
/// @param _members address[] The public addresses of the federation members.
constructor(address[] _members) public {
require(isFedererationMembersListValid(_members), "Invalid federation members list!");
members = _members;
}
/// @dev Returns whether a specific member exists in the federation.
/// @param _member address The public address of the member to check.
function isMember(address _member) public view returns (bool) {
return isMember(members, _member);
}
/// @dev Returns the federation members. Please note that this method is only required due to the current Solidity's
/// version inability to support accessing another contract's array using its built-in getter.
function getMembers() public view returns (address[]) {
return members;
}
/// @dev Returns the required threshold for consensus.
function getConsensusThreshold() public view returns (uint) {
return getConsensusThresholdForMembers(members);
}
/// @dev Returns the revision of the current federation.
function getFederationRevision() public view returns (uint) {
return federationRevision;
}
/// @dev Returns whether a specific member exists in the federation by revision.
/// @param _federationRevision uint The revision to query.
/// @param _member address The public address of the member to check.
function isMemberByRevision(uint _federationRevision, address _member) public view returns (bool) {
return isMember(getMembersByRevision(_federationRevision), _member);
}
/// @dev Returns the federation members by revision.
/// @param _federationRevision uint The revision to query.
function getMembersByRevision(uint _federationRevision) public view returns (address[]) {
return federationRevision == _federationRevision ? members : membersByRevision[_federationRevision];
}
/// @dev Returns the required threshold for consensus by revision.
/// @param _federationRevision uint The revision to query.
function getConsensusThresholdByRevision(uint _federationRevision) public view returns (uint) {
return getConsensusThresholdForMembers(getMembersByRevision(_federationRevision));
}
/// @dev Adds new member to the federation.
/// @param _member address The public address of the new member.
function addMember(address _member) public onlyOwner {
require(_member != address(0), "Address must not be 0!");
require(members.length + 1 <= MAX_FEDERATION_MEMBERS, "Can't add more members!");
// Check for duplicates.
for (uint i = 0; i < members.length; ++i) {
require(members[i] != _member, "Can't add a duplicate member!");
}
membersByRevision[federationRevision++] = members;
members.push(_member);
emit MemberAdded(_member);
}
/// @dev Removes existing member from the federation.
/// @param _member address The public address of the existing member.
function removeMember(address _member) public onlyOwner {
require(_member != address(0), "Address must not be 0!");
require(members.length - 1 > 0, "Can't remove all members!");
// Check for existence.
(uint i, bool exists) = findMemberIndex(members, _member);
require(exists, "Member doesn't exist!");
membersByRevision[federationRevision++] = members;
removeMemberByIndex(i);
emit MemberRemoved(_member);
}
/// @dev Removes a member by an index.
/// @param _i uint The index of the member to be removed.
function removeMemberByIndex(uint _i) public {
require(_i < members.length, "Index out of range!");
while (_i < members.length - 1) {
members[_i] = members[_i + 1];
_i++;
}
delete members[_i];
members.length--;
}
/// @dev Upgrades the Subscription Manager.
function upgradeSubscriptionManager(Upgradable _newSubscriptionManager) public onlyOwner {
if (address(subscriptionManager) != address(0)) {
subscriptionManager.upgrade(_newSubscriptionManager);
}
subscriptionManager = _newSubscriptionManager;
}
/// @dev Returns an index of an existing member. Returns whether the member exist.
/// @param _members address[] The federation members list to check.
/// @param _member address The public address of the member to look for.
function findMemberIndex(address[] _members, address _member) private pure returns(uint, bool) {
uint i;
for (i = 0; i < _members.length; ++i) {
if (_members[i] == _member) {
return (i, true);
}
}
return (i, false);
}
/// @dev Checks federation members list for correctness.
/// @param _members address[] The federation members list to check.
function isFedererationMembersListValid(address[] _members) private pure returns (bool) {
if (_members.length == 0 || _members.length > MAX_FEDERATION_MEMBERS) {
return false;
}
// Make sure there are no zero addresses or duplicates in the federation members list.
for (uint i = 0; i < _members.length; ++i) {
if (_members[i] == address(0)) {
return false;
}
for (uint j = i + 1; j < _members.length; ++j) {
if (_members[i] == _members[j]) {
return false;
}
}
}
return true;
}
/// @dev Returns whether a specific member exists in the federation.
/// @param _members address[] The federation members list to check.
/// @param _member address The public address of the member to check.
function isMember(address[] _members, address _member) private pure returns (bool) {
(, bool exists) = findMemberIndex(_members, _member);
return exists;
}
/// @dev Returns the required threshold for consensus given a list of federation members.
/// @param _members address[] The federation members list to check.
function getConsensusThresholdForMembers(address[] _members) private pure returns (uint) {
// Return 2/3 of the current federation size using the ceil(x / y) = (x + y - 1) / y round up trick.
return (_members.length.mul(2).add(3).sub(1)).div(3);
}
}
|
Returns the federation members by revision. _federationRevision uint The revision to query.
|
function getMembersByRevision(uint _federationRevision) public view returns (address[]) {
return federationRevision == _federationRevision ? members : membersByRevision[_federationRevision];
}
| 6,359,048 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
// Reuse code before and / or after function
// Basics, inputs, sandwich
contract FunctionModifier {
// --> Like Middleware, little piece of code run when after an function execution
// Execution Order: Function called -> Modifier Called -> Modifier Code Executed (If Error revert) -> Function Code Executed ("_;")
bool public paused;
uint256 public count;
function setPause(bool _paused) external {
paused = _paused;
}
modifier whenNotPaused() {
require(!paused, "Contract Is Paused");
_; // --> To Call The Real Function. Because A Modifier wrap the function we want to execute, it's like a "next()"
}
modifier cap(uint256 _x) {
require(_x < 100, "Max Amount is 100"); // With Args
_; // Call Func
}
modifier sandwich() {
count += 10; // Before Function Call
_; // Call the function -- function execution
count *= 2; // After the Function Execution
}
function inc() external whenNotPaused {
// require(!paused, "Contract Is Paused"); --> Moved in whenNotPaused
count++;
}
function dec() external whenNotPaused {
// require(!paused, "Contract Is Paused"); --> Moved in whenNotPaused
count--;
}
// Sum Modifier on top of each other
function incBy(uint256 _x) external whenNotPaused cap(_x) {
count += _x;
}
function foo() external sandwich {
// Modifier: count += 10;
count += 10; // --> Main Func
// Modifier: count * = 2;
}
}
|
require(!paused, "Contract Is Paused"); --> Moved in whenNotPaused
|
function inc() external whenNotPaused {
count++;
}
| 7,297,449 |
./partial_match/4/0x0A89B59768f8EECAA5d75A90DaDe6bC44360388A/sources/SmolPacks.sol
|
Redeem a random card from a pack (Not callable by contract, to prevent exploits on RNG)
|
function redeem(uint256 _packId) public onlyEOA {
Pack storage pack = packs[_packId];
require(pack.price > 0, "Pack does not exist");
require(ting.balanceOf(msg.sender) >= pack.price, "Not enough ting for pack");
PackCardData[] memory data = _getPackCardData(_packId);
ting.burn(msg.sender, pack.price);
pack.redeemed = pack.redeemed.add(1);
uint256 rng = _rng(getTotalRedeemed()) % getPackTotalWeight(_packId);
uint256 cardIdWon = 0;
uint256 cumul = 0;
for (uint256 i = 0; i < data.length; ++i) {
uint256 cardId = data[i].cardId;
cumul = cumul.add(data[i].cardWeight);
if (rng < cumul) {
cardIdWon = cardId;
break;
}
}
require(cardIdWon != 0, "Error during card redeeming RNG");
studio.mint(msg.sender, cardIdWon, 1, "");
emit Redeemed(msg.sender, cardIdWon, 1);
}
| 8,499,093 |
pragma solidity ^0.4.24;
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20Interface public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20Interface _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract ERC20Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, 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);
}
contract ERC20Standard is ERC20Interface {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 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) external returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev 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) external returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* To avoid this issue, allowances are only allowed to be changed between zero and non-zero.
*
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) external returns (bool) {
require(allowed[msg.sender][_spender] == 0 || _value == 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @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 the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) external view returns (uint256 balance) {
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 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) external returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) external returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract ERC223Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transfer(address to, uint256 value, bytes data) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC223ReceivingContract {
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract ERC223Standard is ERC223Interface, ERC20Standard {
using SafeMath for uint256;
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint256 _value, bytes _data) external returns(bool){
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint256 codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value);
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint256 _value) external returns(bool){
uint256 codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
emit Transfer(msg.sender, _to, _value);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MintableToken is ERC223Standard, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract PoolAndSaleInterface {
address public tokenSaleAddr;
address public votingAddr;
address public votingTokenAddr;
uint256 public tap;
uint256 public initialTap;
uint256 public initialRelease;
function setTokenSaleContract(address _tokenSaleAddr) external;
function startProject() external;
}
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 a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract TimeLockPool{
using SafeMath for uint256;
struct LockedBalance {
uint256 balance;
uint256 releaseTime;
}
/*
structure: lockedBalnces[owner][token] = LockedBalance(balance, releaseTime);
token address = '0x0' stands for ETH (unit = wei)
*/
mapping (address => mapping (address => LockedBalance[])) public lockedBalances;
event Deposit(
address indexed owner,
address indexed tokenAddr,
uint256 amount,
uint256 releaseTime
);
event Withdraw(
address indexed owner,
address indexed tokenAddr,
uint256 amount
);
/// @dev Constructor.
/// @return
constructor() public {}
/// @dev Deposit tokens to specific account with time-lock.
/// @param tokenAddr The contract address of a ERC20/ERC223 token.
/// @param account The owner of deposited tokens.
/// @param amount Amount to deposit.
/// @param releaseTime Time-lock period.
/// @return True if it is successful, revert otherwise.
function depositERC20 (
address tokenAddr,
address account,
uint256 amount,
uint256 releaseTime
) external returns (bool) {
require(account != address(0x0));
require(tokenAddr != 0x0);
require(msg.value == 0);
require(amount > 0);
require(ERC20Interface(tokenAddr).transferFrom(msg.sender, this, amount));
lockedBalances[account][tokenAddr].push(LockedBalance(amount, releaseTime));
emit Deposit(account, tokenAddr, amount, releaseTime);
return true;
}
/// @dev Deposit ETH to specific account with time-lock.
/// @param account The owner of deposited tokens.
/// @param releaseTime Timestamp to release the fund.
/// @return True if it is successful, revert otherwise.
function depositETH (
address account,
uint256 releaseTime
) external payable returns (bool) {
require(account != address(0x0));
address tokenAddr = address(0x0);
uint256 amount = msg.value;
require(amount > 0);
lockedBalances[account][tokenAddr].push(LockedBalance(amount, releaseTime));
emit Deposit(account, tokenAddr, amount, releaseTime);
return true;
}
/// @dev Release the available balance of an account.
/// @param account An account to receive tokens.
/// @param tokenAddr An address of ERC20/ERC223 token.
/// @param index_from Starting index of records to withdraw.
/// @param index_to Ending index of records to withdraw.
/// @return True if it is successful, revert otherwise.
function withdraw (address account, address tokenAddr, uint256 index_from, uint256 index_to) external returns (bool) {
require(account != address(0x0));
uint256 release_amount = 0;
for (uint256 i = index_from; i < lockedBalances[account][tokenAddr].length && i < index_to + 1; i++) {
if (lockedBalances[account][tokenAddr][i].balance > 0 &&
lockedBalances[account][tokenAddr][i].releaseTime <= block.timestamp) {
release_amount = release_amount.add(lockedBalances[account][tokenAddr][i].balance);
lockedBalances[account][tokenAddr][i].balance = 0;
}
}
require(release_amount > 0);
if (tokenAddr == 0x0) {
if (!account.send(release_amount)) {
revert();
}
emit Withdraw(account, tokenAddr, release_amount);
return true;
} else {
if (!ERC20Interface(tokenAddr).transfer(account, release_amount)) {
revert();
}
emit Withdraw(account, tokenAddr, release_amount);
return true;
}
}
/// @dev Returns total amount of balances which already passed release time.
/// @param account An account to receive tokens.
/// @param tokenAddr An address of ERC20/ERC223 token.
/// @return Available balance of specified token.
function getAvailableBalanceOf (address account, address tokenAddr)
external
view
returns (uint256)
{
require(account != address(0x0));
uint256 balance = 0;
for(uint256 i = 0; i < lockedBalances[account][tokenAddr].length; i++) {
if (lockedBalances[account][tokenAddr][i].releaseTime <= block.timestamp) {
balance = balance.add(lockedBalances[account][tokenAddr][i].balance);
}
}
return balance;
}
/// @dev Returns total amount of balances which are still locked.
/// @param account An account to receive tokens.
/// @param tokenAddr An address of ERC20/ERC223 token.
/// @return Locked balance of specified token.
function getLockedBalanceOf (address account, address tokenAddr)
external
view
returns (uint256)
{
require(account != address(0x0));
uint256 balance = 0;
for(uint256 i = 0; i < lockedBalances[account][tokenAddr].length; i++) {
if(lockedBalances[account][tokenAddr][i].releaseTime > block.timestamp) {
balance = balance.add(lockedBalances[account][tokenAddr][i].balance);
}
}
return balance;
}
/// @dev Returns next release time of locked balances.
/// @param account An account to receive tokens.
/// @param tokenAddr An address of ERC20/ERC223 token.
/// @return Timestamp of next release.
function getNextReleaseTimeOf (address account, address tokenAddr)
external
view
returns (uint256)
{
require(account != address(0x0));
uint256 nextRelease = 2**256 - 1;
for (uint256 i = 0; i < lockedBalances[account][tokenAddr].length; i++) {
if (lockedBalances[account][tokenAddr][i].releaseTime > block.timestamp &&
lockedBalances[account][tokenAddr][i].releaseTime < nextRelease) {
nextRelease = lockedBalances[account][tokenAddr][i].releaseTime;
}
}
/* returns 0 if there are no more locked balances. */
if (nextRelease == 2**256 - 1) {
nextRelease = 0;
}
return nextRelease;
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract TokenController is Ownable {
using SafeMath for uint256;
MintableToken public targetToken;
address public votingAddr;
address public tokensaleManagerAddr;
State public state;
enum State {
Init,
Tokensale,
Public
}
/// @dev The deployer must change the ownership of the target token to this contract.
/// @param _targetToken : The target token this contract manage the rights to mint.
/// @return
constructor (
MintableToken _targetToken
) public {
targetToken = MintableToken(_targetToken);
state = State.Init;
}
/// @dev Mint and distribute specified amount of tokens to an address.
/// @param to An address that receive the minted tokens.
/// @param amount Amount to mint.
/// @return True if the distribution is successful, revert otherwise.
function mint (address to, uint256 amount) external returns (bool) {
/*
being called from voting contract will be available in the future
ex. if (state == State.Public && msg.sender == votingAddr)
*/
if ((state == State.Init && msg.sender == owner) ||
(state == State.Tokensale && msg.sender == tokensaleManagerAddr)) {
return targetToken.mint(to, amount);
}
revert();
}
/// @dev Change the phase from "Init" to "Tokensale".
/// @param _tokensaleManagerAddr A contract address of token-sale.
/// @return True if the change of the phase is successful, revert otherwise.
function openTokensale (address _tokensaleManagerAddr)
external
onlyOwner
returns (bool)
{
/* check if the owner of the target token is set to this contract */
require(MintableToken(targetToken).owner() == address(this));
require(state == State.Init);
require(_tokensaleManagerAddr != address(0x0));
tokensaleManagerAddr = _tokensaleManagerAddr;
state = State.Tokensale;
return true;
}
/// @dev Change the phase from "Tokensale" to "Public". This function will be
/// cahnged in the future to receive an address of voting contract as an
/// argument in order to handle the result of minting proposal.
/// @return True if the change of the phase is successful, revert otherwise.
function closeTokensale () external returns (bool) {
require(state == State.Tokensale && msg.sender == tokensaleManagerAddr);
state = State.Public;
return true;
}
/// @dev Check if the state is "Init" or not.
/// @return True if the state is "Init", false otherwise.
function isStateInit () external view returns (bool) {
return (state == State.Init);
}
/// @dev Check if the state is "Tokensale" or not.
/// @return True if the state is "Tokensale", false otherwise.
function isStateTokensale () external view returns (bool) {
return (state == State.Tokensale);
}
/// @dev Check if the state is "Public" or not.
/// @return True if the state is "Public", false otherwise.
function isStatePublic () external view returns (bool) {
return (state == State.Public);
}
}
contract TokenSaleManager is Ownable {
using SafeMath for uint256;
ERC20Interface public token;
address public poolAddr;
address public tokenControllerAddr;
address public timeLockPoolAddr;
address[] public tokenSales;
mapping( address => bool ) public tokenSaleIndex;
bool public isStarted = false;
bool public isFinalized = false;
modifier onlyDaicoPool {
require(msg.sender == poolAddr);
_;
}
modifier onlyTokenSale {
require(tokenSaleIndex[msg.sender]);
_;
}
/// @dev Constructor. It set the DaicoPool to receive the starting signal from this contract.
/// @param _tokenControllerAddr The contract address of TokenController.
/// @param _timeLockPoolAddr The contract address of a TimeLockPool.
/// @param _daicoPoolAddr The contract address of DaicoPool.
/// @param _token The contract address of a ERC20 token.
constructor (
address _tokenControllerAddr,
address _timeLockPoolAddr,
address _daicoPoolAddr,
ERC20Interface _token
) public {
require(_tokenControllerAddr != address(0x0));
tokenControllerAddr = _tokenControllerAddr;
require(_timeLockPoolAddr != address(0x0));
timeLockPoolAddr = _timeLockPoolAddr;
token = _token;
poolAddr = _daicoPoolAddr;
require(PoolAndSaleInterface(poolAddr).votingTokenAddr() == address(token));
PoolAndSaleInterface(poolAddr).setTokenSaleContract(this);
}
/// @dev This contract doen't receive any ETH.
function() external payable {
revert();
}
/// @dev Add a new token sale with specific parameters. New sale should start
/// @dev after the previous one closed.
/// @param openingTime A timestamp of the date this sale will start.
/// @param closingTime A timestamp of the date this sale will end.
/// @param tokensCap Number of tokens to be sold. Can be 0 if it accepts carryover.
/// @param rate Number of tokens issued with 1 ETH. [minimal unit of the token / ETH]
/// @param carryover If true, unsold tokens will be carryovered to next sale.
/// @param timeLockRate Specified rate of issued tokens will be locked. ex. 50 = 50%
/// @param timeLockEnd A timestamp of the date locked tokens will be released.
/// @param minAcceptableWei Minimum contribution.
function addTokenSale (
uint256 openingTime,
uint256 closingTime,
uint256 tokensCap,
uint256 rate,
bool carryover,
uint256 timeLockRate,
uint256 timeLockEnd,
uint256 minAcceptableWei
) external onlyOwner {
require(!isStarted);
require(
tokenSales.length == 0 ||
TimedCrowdsale(tokenSales[tokenSales.length-1]).closingTime() < openingTime
);
require(TokenController(tokenControllerAddr).state() == TokenController.State.Init);
tokenSales.push(new TokenSale(
rate,
token,
poolAddr,
openingTime,
closingTime,
tokensCap,
timeLockRate,
timeLockEnd,
carryover,
minAcceptableWei
));
tokenSaleIndex[tokenSales[tokenSales.length-1]] = true;
}
/// @dev Initialize the tokensales. No other sales can be added after initialization.
/// @return True if successful, revert otherwise.
function initialize () external onlyOwner returns (bool) {
require(!isStarted);
TokenSale(tokenSales[0]).initialize(0);
isStarted = true;
}
/// @dev Request TokenController to mint new tokens. This function is only called by
/// @dev token sales.
/// @param _beneficiary The address to receive the new tokens.
/// @param _tokenAmount Token amount to be minted.
/// @return True if successful, revert otherwise.
function mint (
address _beneficiary,
uint256 _tokenAmount
) external onlyTokenSale returns(bool) {
require(isStarted && !isFinalized);
require(TokenController(tokenControllerAddr).mint(_beneficiary, _tokenAmount));
return true;
}
/// @dev Mint new tokens with time-lock. This function is only called by token sales.
/// @param _beneficiary The address to receive the new tokens.
/// @param _tokenAmount Token amount to be minted.
/// @param _releaseTime A timestamp of the date locked tokens will be released.
/// @return True if successful, revert otherwise.
function mintTimeLocked (
address _beneficiary,
uint256 _tokenAmount,
uint256 _releaseTime
) external onlyTokenSale returns(bool) {
require(isStarted && !isFinalized);
require(TokenController(tokenControllerAddr).mint(this, _tokenAmount));
require(ERC20Interface(token).approve(timeLockPoolAddr, _tokenAmount));
require(TimeLockPool(timeLockPoolAddr).depositERC20(
token,
_beneficiary,
_tokenAmount,
_releaseTime
));
return true;
}
/// @dev Adds single address to whitelist of all token sales.
/// @param _beneficiary Address to be added to the whitelist
function addToWhitelist(address _beneficiary) external onlyOwner {
require(isStarted);
for (uint256 i = 0; i < tokenSales.length; i++ ) {
WhitelistedCrowdsale(tokenSales[i]).addToWhitelist(_beneficiary);
}
}
/// @dev Adds multiple addresses to whitelist of all token sales.
/// @param _beneficiaries Addresses to be added to the whitelist
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
require(isStarted);
for (uint256 i = 0; i < tokenSales.length; i++ ) {
WhitelistedCrowdsale(tokenSales[i]).addManyToWhitelist(_beneficiaries);
}
}
/// @dev Finalize the specific token sale. Can be done if end date has come or
/// @dev all tokens has been sold out. It process carryover if it is set.
/// @param _indexTokenSale index of the target token sale.
function finalize (uint256 _indexTokenSale) external {
require(isStarted && !isFinalized);
TokenSale ts = TokenSale(tokenSales[_indexTokenSale]);
if (ts.canFinalize()) {
ts.finalize();
uint256 carryoverAmount = 0;
if (ts.carryover() &&
ts.tokensCap() > ts.tokensMinted() &&
_indexTokenSale.add(1) < tokenSales.length) {
carryoverAmount = ts.tokensCap().sub(ts.tokensMinted());
}
if(_indexTokenSale.add(1) < tokenSales.length) {
TokenSale(tokenSales[_indexTokenSale.add(1)]).initialize(carryoverAmount);
}
}
}
/// @dev Finalize the manager. Can be done if all token sales are already finalized.
/// @dev It makes the DaicoPool open the TAP.
function finalizeTokenSaleManager () external{
require(isStarted && !isFinalized);
for (uint256 i = 0; i < tokenSales.length; i++ ) {
require(FinalizableCrowdsale(tokenSales[i]).isFinalized());
}
require(TokenController(tokenControllerAddr).closeTokensale());
isFinalized = true;
PoolAndSaleInterface(poolAddr).startProject();
}
}
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract TokenSale is FinalizableCrowdsale,
WhitelistedCrowdsale {
using SafeMath for uint256;
address public managerAddr;
address public poolAddr;
bool public isInitialized = false;
uint256 public timeLockRate;
uint256 public timeLockEnd;
uint256 public tokensMinted = 0;
uint256 public tokensCap;
uint256 public minAcceptableWei;
bool public carryover;
modifier onlyManager{
require(msg.sender == managerAddr);
_;
}
/// @dev Constructor.
/// @param _rate Number of tokens issued with 1 ETH. [minimal unit of the token / ETH]
/// @param _token The contract address of a ERC20 token.
/// @param _poolAddr The contract address of DaicoPool.
/// @param _openingTime A timestamp of the date this sale will start.
/// @param _closingTime A timestamp of the date this sale will end.
/// @param _tokensCap Number of tokens to be sold. Can be 0 if it accepts carryover.
/// @param _timeLockRate Specified rate of issued tokens will be locked. ex. 50 = 50%
/// @param _timeLockEnd A timestamp of the date locked tokens will be released.
/// @param _carryover If true, unsold tokens will be carryovered to next sale.
/// @param _minAcceptableWei Minimum contribution.
/// @return
constructor (
uint256 _rate, /* The unit of rate is [nano tokens / ETH] in this contract */
ERC20Interface _token,
address _poolAddr,
uint256 _openingTime,
uint256 _closingTime,
uint256 _tokensCap,
uint256 _timeLockRate,
uint256 _timeLockEnd,
bool _carryover,
uint256 _minAcceptableWei
) public Crowdsale(_rate, _poolAddr, _token) TimedCrowdsale(_openingTime, _closingTime) {
require(_timeLockRate >= 0 && _timeLockRate <=100);
require(_poolAddr != address(0x0));
managerAddr = msg.sender;
poolAddr = _poolAddr;
timeLockRate = _timeLockRate;
timeLockEnd = _timeLockEnd;
tokensCap = _tokensCap;
carryover = _carryover;
minAcceptableWei = _minAcceptableWei;
}
/// @dev Initialize the sale. If carryoverAmount is given, it added the tokens to be sold.
/// @param carryoverAmount Amount of tokens to be added to capTokens.
/// @return
function initialize(uint256 carryoverAmount) external onlyManager {
require(!isInitialized);
isInitialized = true;
tokensCap = tokensCap.add(carryoverAmount);
}
/// @dev Finalize the sale. It transfers all the funds it has. Can be repeated.
/// @return
function finalize() onlyOwner public {
//require(!isFinalized);
require(isInitialized);
require(canFinalize());
finalization();
emit Finalized();
isFinalized = true;
}
/// @dev Check if the sale can be finalized.
/// @return True if closing time has come or tokens are sold out.
function canFinalize() public view returns(bool) {
return (hasClosed() || (isInitialized && tokensCap <= tokensMinted));
}
/// @dev It transfers all the funds it has.
/// @return
function finalization() internal {
if(address(this).balance > 0){
poolAddr.transfer(address(this).balance);
}
}
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
//require(tokensMinted.add(_tokenAmount) <= tokensCap);
require(tokensMinted < tokensCap);
uint256 time_locked = _tokenAmount.mul(timeLockRate).div(100);
uint256 instant = _tokenAmount.sub(time_locked);
if (instant > 0) {
require(TokenSaleManager(managerAddr).mint(_beneficiary, instant));
}
if (time_locked > 0) {
require(TokenSaleManager(managerAddr).mintTimeLocked(
_beneficiary,
time_locked,
timeLockEnd
));
}
tokensMinted = tokensMinted.add(_tokenAmount);
}
/// @dev Overrides _forwardFunds to do nothing.
function _forwardFunds() internal {}
/// @dev Overrides _preValidatePurchase to check minimam contribution and initialization.
/// @param _beneficiary Token purchaser
/// @param _weiAmount weiAmount to pay
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(isInitialized);
require(_weiAmount >= minAcceptableWei);
}
/**
* @dev Overridden in order to change the unit of rate with [nano toekns / ETH]
* instead of original [minimal unit of the token / wei].
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate).div(10**18); //The unit of rate is [nano tokens / ETH].
}
}
|
Release the available balance of an account. account An account to receive tokens. tokenAddr An address of ERC20/ERC223 token. index_from Starting index of records to withdraw. index_to Ending index of records to withdraw. return True if it is successful, revert otherwise.
|
function withdraw (address account, address tokenAddr, uint256 index_from, uint256 index_to) external returns (bool) {
require(account != address(0x0));
uint256 release_amount = 0;
for (uint256 i = index_from; i < lockedBalances[account][tokenAddr].length && i < index_to + 1; i++) {
if (lockedBalances[account][tokenAddr][i].balance > 0 &&
lockedBalances[account][tokenAddr][i].releaseTime <= block.timestamp) {
release_amount = release_amount.add(lockedBalances[account][tokenAddr][i].balance);
lockedBalances[account][tokenAddr][i].balance = 0;
}
}
require(release_amount > 0);
if (tokenAddr == 0x0) {
if (!account.send(release_amount)) {
revert();
}
emit Withdraw(account, tokenAddr, release_amount);
return true;
if (!ERC20Interface(tokenAddr).transfer(account, release_amount)) {
revert();
}
emit Withdraw(account, tokenAddr, release_amount);
return true;
}
}
| 1,066,274 |
pragma solidity ^0.4.20;
// ----------------------------------------------------------------------------
// CORETAB - The World Changer Edition ICO Smart Contract
//
// Symbol : CRT
// Name : CORETAB
// initial Supply : 300,000,000
// Decimals : 18
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe math
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// Ownership contract
// _newOwner is address of new owner
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = 0x12D91d8f280EbBC7366F118B3FA7BC7f2A555BCd;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// transfer Ownership to other address
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0));
emit OwnershipTransferred(owner,_newOwner);
owner = _newOwner;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
contract Coretab is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public RATE;
bool public isStopped = false;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event Mint(address indexed to, uint256 amount);
event ChangeRate(uint256 amount);
modifier onlyWhenRunning {
require(!isStopped);
_;
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "CRT";
name = "CORETAB";
decimals = 18;
_totalSupply = 300000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
RATE = 5000;
emit Transfer(address(0), owner, _totalSupply);
}
// ----------------------------------------------------------------------------
// It invokes when someone sends ETH to this contract address
// requires enough gas for execution
// ----------------------------------------------------------------------------
function() public payable {
buyTokens();
}
// ----------------------------------------------------------------------------
// Function to handle eth and token transfers
// tokens are transferred to user
// ETH are transferred to current owner
// ----------------------------------------------------------------------------
function buyTokens() onlyWhenRunning public payable {
require(msg.value > 0);
uint tokens = msg.value.mul(RATE);
require(balances[owner] >= tokens);
balances[msg.sender] = balances[msg.sender].add(tokens);
balances[owner] = balances[owner].sub(tokens);
emit Transfer(owner, msg.sender, tokens);
owner.transfer(msg.value);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
require(to != address(0));
require(tokens > 0);
require(balances[msg.sender] >= tokens);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
require(spender != address(0));
require(tokens > 0);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(from != address(0));
require(to != address(0));
require(tokens > 0);
require(balances[from] >= tokens);
require(allowed[from][msg.sender] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Increase the amount of tokens that an owner allowed to a spender.
//
// approve should be called when allowed[_spender] == 0. To increment
// allowed value is better to use this function to avoid 2 calls (and wait until
// the first transaction is mined)
// _spender The address which will spend the funds.
// _addedValue The amount of tokens to increase the allowance by.
// ------------------------------------------------------------------------
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// ------------------------------------------------------------------------
// Decrease the amount of tokens that an owner allowed to a spender.
//
// approve should be called when allowed[_spender] == 0. To decrement
// allowed value is better to use this function to avoid 2 calls (and wait until
// the first transaction is mined)
// _spender The address which will spend the funds.
// _subtractedValue The amount of tokens to decrease the allowance by.
// ------------------------------------------------------------------------
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
require(_spender != address(0));
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// ------------------------------------------------------------------------
// Change the ETH to BLCURR rate
// ------------------------------------------------------------------------
function changeRate(uint256 _rate) public onlyOwner {
require(_rate > 0);
RATE =_rate;
emit ChangeRate(_rate);
}
// ------------------------------------------------------------------------
// Function to mint tokens
// _to The address that will receive the minted tokens.
// _amount The amount of tokens to mint.
// A boolean that indicates if the operation was successful.
// ------------------------------------------------------------------------
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
require(_to != address(0));
require(_amount > 0);
uint newamount = _amount;
_totalSupply = _totalSupply.add(newamount);
balances[_to] = balances[_to].add(newamount);
emit Mint(_to, newamount);
emit Transfer(address(0), _to, newamount);
return true;
}
// ------------------------------------------------------------------------
// function to stop the ICO
// ------------------------------------------------------------------------
function stopICO() onlyOwner public {
isStopped = true;
}
// ------------------------------------------------------------------------
// function to resume ICO
// ------------------------------------------------------------------------
function resumeICO() onlyOwner public {
isStopped = false;
}
}
|
------------------------------------------------------------------------ Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md recommends that there are no checks for the approval double-spend attack as this should be implemented in user interfaces ------------------------------------------------------------------------
|
function approve(address spender, uint tokens) public returns (bool success) {
require(spender != address(0));
require(tokens > 0);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| 1,554,444 |
pragma solidity ^0.4.11;
interface CommonWallet {
function receive() external payable;
}
library StringUtils {
function concat(string _a, string _b)
internal
pure
returns (string)
{
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory bab = new bytes(_ba.length + _bb.length);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
}
library UintStringUtils {
function toString(uint i)
internal
pure
returns (string)
{
if (i == 0) return '0';
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
// @title AddressUtils
// @dev Utility library of inline functions on addresses
library AddressUtils {
// Returns whether the target address is a contract
// @dev This function will return false if invoked during the constructor of a contract,
// as the code is not actually created until after the constructor finishes.
// @param addr address to check
// @return whether the target address is a contract
function isContract(address addr)
internal
view
returns(bool)
{
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
// @title SafeMath256
// @dev Math operations with safety checks that throw on error
library SafeMath256 {
// @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;
}
}
library SafeMath32 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint32 a, uint32 b) internal pure returns (uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint32 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
// @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
function sub(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath8 {
// @dev Multiplies two numbers, throws on overflow.
function mul(uint8 a, uint8 b) internal pure returns (uint8 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(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
// @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
// @dev Adds two numbers, throws on overflow.
function add(uint8 a, uint8 b) internal pure returns (uint8 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/// @title A facet of DragonCore that manages special access privileges.
contract DragonAccessControl
{
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Contract owner
address internal controller_;
/// @dev Contract modes
enum Mode {TEST, PRESALE, OPERATE}
/// @dev Contract state
Mode internal mode_ = Mode.TEST;
/// @dev OffChain Server accounts ('minions') addresses
/// It's used for money withdrawal and export of tokens
mapping(address => bool) internal minions_;
/// @dev Presale contract address. Can call `presale` method.
address internal presale_;
// Modifiers ---------------------------------------------------------------
/// @dev Limit execution to controller account only.
modifier controllerOnly() {
require(controller_ == msg.sender, "controller_only");
_;
}
/// @dev Limit execution to minion account only.
modifier minionOnly() {
require(minions_[msg.sender], "minion_only");
_;
}
/// @dev Limit execution to test time only.
modifier testModeOnly {
require(mode_ == Mode.TEST, "test_mode_only");
_;
}
/// @dev Limit execution to presale time only.
modifier presaleModeOnly {
require(mode_ == Mode.PRESALE, "presale_mode_only");
_;
}
/// @dev Limit execution to operate time only.
modifier operateModeOnly {
require(mode_ == Mode.OPERATE, "operate_mode_only");
_;
}
/// @dev Limit execution to presale account only.
modifier presaleOnly() {
require(msg.sender == presale_, "presale_only");
_;
}
/// @dev set state to Mode.OPERATE.
function setOperateMode()
external
controllerOnly
presaleModeOnly
{
mode_ = Mode.OPERATE;
}
/// @dev Set presale contract address. Becomes useless when presale is over.
/// @param _presale Presale contract address.
function setPresale(address _presale)
external
controllerOnly
{
presale_ = _presale;
}
/// @dev set state to Mode.PRESALE.
function setPresaleMode()
external
controllerOnly
testModeOnly
{
mode_ = Mode.PRESALE;
}
/// @dev Get controller address.
/// @return Address of contract's controller.
function controller()
external
view
returns(address)
{
return controller_;
}
/// @dev Transfer control to new address. Set controller an approvee for
/// tokens that managed by contract itself. Remove previous controller value
/// from contract's approvees.
/// @param _to New controller address.
function setController(address _to)
external
controllerOnly
{
require(_to != NA, "_to");
require(controller_ != _to, "already_controller");
controller_ = _to;
}
/// @dev Check if address is a minion.
/// @param _addr Address to check.
/// @return True if address is a minion.
function isMinion(address _addr)
public view returns(bool)
{
return minions_[_addr];
}
function getCurrentMode()
public view returns (Mode)
{
return mode_;
}
}
/// @dev token description, storage and transfer functions
contract DragonBase is DragonAccessControl
{
using SafeMath8 for uint8;
using SafeMath32 for uint32;
using SafeMath256 for uint256;
using StringUtils for string;
using UintStringUtils for uint;
/// @dev The Birth event is fired whenever a new dragon comes into existence.
event Birth(address owner, uint256 petId, uint256 tokenId, uint256 parentA, uint256 parentB, string genes, string params);
/// @dev Token name
string internal name_;
/// @dev Token symbol
string internal symbol_;
/// @dev Token resolving url
string internal url_;
struct DragonToken {
// Constant Token params
uint8 genNum; // generation number. uses for dragon view
string genome; // genome description
uint256 petId; // offchain dragon identifier
// Parents
uint256 parentA;
uint256 parentB;
// Game-depening Token params
string params; // can change in export operation
// State
address owner;
}
/// @dev Count of minted tokens
uint256 internal mintCount_;
/// @dev Maximum token supply
uint256 internal maxSupply_;
/// @dev Count of burn tokens
uint256 internal burnCount_;
// Tokens state
/// @dev Token approvals values
mapping(uint256 => address) internal approvals_;
/// @dev Operator approvals
mapping(address => mapping(address => bool)) internal operatorApprovals_;
/// @dev Index of token in owner's token list
mapping(uint256 => uint256) internal ownerIndex_;
/// @dev Owner's tokens list
mapping(address => uint256[]) internal ownTokens_;
/// @dev Tokens
mapping(uint256 => DragonToken) internal tokens_;
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Add token to new owner. Increase owner's balance.
/// @param _to Token receiver.
/// @param _tokenId New token id.
function _addTo(address _to, uint256 _tokenId)
internal
{
DragonToken storage token = tokens_[_tokenId];
require(token.owner == NA, "taken");
uint256 lastIndex = ownTokens_[_to].length;
ownTokens_[_to].push(_tokenId);
ownerIndex_[_tokenId] = lastIndex;
token.owner = _to;
}
/// @dev Create new token and increase mintCount.
/// @param _genome New token's genome.
/// @param _params Token params string.
/// @param _parentA Token A parent.
/// @param _parentB Token B parent.
/// @return New token id.
function _createToken(
address _to,
// Constant Token params
uint8 _genNum,
string _genome,
uint256 _parentA,
uint256 _parentB,
// Game-depening Token params
uint256 _petId,
string _params
)
internal returns(uint256)
{
uint256 tokenId = mintCount_.add(1);
mintCount_ = tokenId;
DragonToken memory token = DragonToken(
_genNum,
_genome,
_petId,
_parentA,
_parentB,
_params,
NA
);
tokens_[tokenId] = token;
_addTo(_to, tokenId);
emit Birth(_to, _petId, tokenId, _parentA, _parentB, _genome, _params);
return tokenId;
}
/// @dev Get token genome.
/// @param _tokenId Token id.
/// @return Token's genome.
function getGenome(uint256 _tokenId)
external view returns(string)
{
return tokens_[_tokenId].genome;
}
/// @dev Get token params.
/// @param _tokenId Token id.
/// @return Token's params.
function getParams(uint256 _tokenId)
external view returns(string)
{
return tokens_[_tokenId].params;
}
/// @dev Get token parentA.
/// @param _tokenId Token id.
/// @return Parent token id.
function getParentA(uint256 _tokenId)
external view returns(uint256)
{
return tokens_[_tokenId].parentA;
}
/// @dev Get token parentB.
/// @param _tokenId Token id.
/// @return Parent token id.
function getParentB(uint256 _tokenId)
external view returns(uint256)
{
return tokens_[_tokenId].parentB;
}
/// @dev Check if `_tokenId` exists. Check if owner is not addres(0).
/// @param _tokenId Token id
/// @return Return true if token owner is real.
function isExisting(uint256 _tokenId)
public view returns(bool)
{
return tokens_[_tokenId].owner != NA;
}
/// @dev Receive maxium token supply value.
/// @return Contracts `maxSupply_` variable.
function maxSupply()
external view returns(uint256)
{
return maxSupply_;
}
/// @dev Set url prefix for tokenURI generation.
/// @param _url Url prefix value.
function setUrl(string _url)
external controllerOnly
{
url_ = _url;
}
/// @dev Get token symbol.
/// @return Token symbol name.
function symbol()
external view returns(string)
{
return symbol_;
}
/// @dev Get token URI to receive offchain information by it's id.
/// @param _tokenId Token id.
/// @return URL string. For example "http://erc721.tld/tokens/1".
function tokenURI(uint256 _tokenId)
external view returns(string)
{
return url_.concat(_tokenId.toString());
}
/// @dev Get token name.
/// @return Token name string.
function name()
external view returns(string)
{
return name_;
}
/// @dev return information about _owner tokens
function getTokens(address _owner)
external view returns (uint256[], uint256[], byte[])
{
uint256[] memory tokens = ownTokens_[_owner];
uint256[] memory tokenIds = new uint256[](tokens.length);
uint256[] memory petIds = new uint256[](tokens.length);
byte[] memory genomes = new byte[](tokens.length * 77);
uint index = 0;
for(uint i = 0; i < tokens.length; i++) {
uint256 tokenId = tokens[i];
DragonToken storage token = tokens_[tokenId];
tokenIds[i] = tokenId;
petIds[i] = token.petId;
bytes storage genome = bytes(token.genome);
for(uint j = 0; j < genome.length; j++) {
genomes[index++] = genome[j];
}
}
return (tokenIds, petIds, genomes);
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @dev See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC721/ERC721.sol
contract ERC721Basic
{
/// @dev Emitted when token approvee is set
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
/// @dev Emitted when owner approve all own tokens to operator.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @dev Emitted when user deposit some funds.
event Deposit(address indexed _sender, uint256 _value);
/// @dev Emitted when user deposit some funds.
event Withdraw(address indexed _sender, uint256 _value);
/// @dev Emitted when token transferred to new owner
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
// Required methods
function balanceOf(address _owner) external view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) external;
function getApproved(uint256 _tokenId) public view returns (address _to);
//function transfer(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic
{
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver
{
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data )
public returns(bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Metadata, ERC721Receiver
{
/// @dev Interface signature 721 for interface detection.
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7;
/*
bytes4(keccak256('supportsInterface(bytes4)'));
*/
bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63;
/*
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
bytes4(keccak256('tokenByIndex(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f;
/*
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('tokenURI(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd;
/*
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('getApproved(uint256)')) ^
bytes4(keccak256('setApprovalForAll(address,bool)')) ^
bytes4(keccak256('isApprovedForAll(address,address)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'));
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165)
|| (_interfaceID == InterfaceSignature_ERC721)
|| (_interfaceID == InterfaceSignature_ERC721Enumerable)
|| (_interfaceID == InterfaceSignature_ERC721Metadata));
}
}
/// @dev ERC721 methods
contract DragonOwnership is ERC721, DragonBase
{
using StringUtils for string;
using UintStringUtils for uint;
using AddressUtils for address;
/// @dev Emitted when token transferred to new owner. Additional fields is petId, genes, params
/// it uses for client-side indication
event TransferInfo(address indexed _from, address indexed _to, uint256 _tokenId, uint256 petId, string genes, string params);
/// @dev Specify if _addr is token owner or approvee. Also check if `_addr`
/// is operator for token owner.
/// @param _tokenId Token to check ownership of.
/// @param _addr Address to check if it's an owner or an aprovee of `_tokenId`.
/// @return True if token can be managed by provided `_addr`.
function isOwnerOrApproved(uint256 _tokenId, address _addr)
public view returns(bool)
{
DragonToken memory token = tokens_[_tokenId];
if (token.owner == _addr) {
return true;
}
else if (isApprovedFor(_tokenId, _addr)) {
return true;
}
else if (isApprovedForAll(token.owner, _addr)) {
return true;
}
return false;
}
/// @dev Limit execution to token owner or approvee only.
/// @param _tokenId Token to check ownership of.
modifier ownerOrApprovedOnly(uint256 _tokenId) {
require(isOwnerOrApproved(_tokenId, msg.sender), "tokenOwnerOrApproved_only");
_;
}
/// @dev Contract's own token only acceptable.
/// @param _tokenId Contract's token id.
modifier ownOnly(uint256 _tokenId) {
require(tokens_[_tokenId].owner == address(this), "own_only");
_;
}
/// @dev Determine if token is approved for specified approvee.
/// @param _tokenId Target token id.
/// @param _approvee Approvee address.
/// @return True if so.
function isApprovedFor(uint256 _tokenId, address _approvee)
public view returns(bool)
{
return approvals_[_tokenId] == _approvee;
}
/// @dev Specify is given address set as operator with setApprovalForAll.
/// @param _owner Token owner.
/// @param _operator Address to check if it an operator.
/// @return True if operator is set.
function isApprovedForAll(address _owner, address _operator)
public view returns(bool)
{
return operatorApprovals_[_owner][_operator];
}
/// @dev Check if `_tokenId` exists. Check if owner is not addres(0).
/// @param _tokenId Token id
/// @return Return true if token owner is real.
function exists(uint256 _tokenId)
public view returns(bool)
{
return tokens_[_tokenId].owner != NA;
}
/// @dev Get owner of a token.
/// @param _tokenId Token owner id.
/// @return Token owner address.
function ownerOf(uint256 _tokenId)
public view returns(address)
{
return tokens_[_tokenId].owner;
}
/// @dev Get approvee address. If there is not approvee returns 0x0.
/// @param _tokenId Token id to get approvee of.
/// @return Approvee address or 0x0.
function getApproved(uint256 _tokenId)
public view returns(address)
{
return approvals_[_tokenId];
}
/// @dev Grant owner alike controll permissions to third party.
/// @param _to Permission receiver.
/// @param _tokenId Granted token id.
function approve(address _to, uint256 _tokenId)
external ownerOrApprovedOnly(_tokenId)
{
address owner = ownerOf(_tokenId);
require(_to != owner);
if (getApproved(_tokenId) != NA || _to != NA) {
approvals_[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/// @dev Current total tokens supply. Always less then maxSupply.
/// @return Difference between minted and burned tokens.
function totalSupply()
public view returns(uint256)
{
return mintCount_;
}
/// @dev Get number of tokens which `_owner` owns.
/// @param _owner Address to count own tokens.
/// @return Count of owned tokens.
function balanceOf(address _owner)
external view returns(uint256)
{
return ownTokens_[_owner].length;
}
/// @dev Internal set approval for all without _owner check.
/// @param _owner Granting user.
/// @param _to New account approvee.
/// @param _approved Set new approvee status.
function _setApprovalForAll(address _owner, address _to, bool _approved)
internal
{
operatorApprovals_[_owner][_to] = _approved;
emit ApprovalForAll(_owner, _to, _approved);
}
/// @dev Set approval for all account tokens.
/// @param _to Approvee address.
/// @param _approved Value true or false.
function setApprovalForAll(address _to, bool _approved)
external
{
require(_to != msg.sender);
_setApprovalForAll(msg.sender, _to, _approved);
}
/// @dev Remove approval bindings for token. Do nothing if no approval
/// exists.
/// @param _from Address of token owner.
/// @param _tokenId Target token id.
function _clearApproval(address _from, uint256 _tokenId)
internal
{
if (approvals_[_tokenId] == NA) {
return;
}
approvals_[_tokenId] = NA;
emit Approval(_from, NA, _tokenId);
}
/// @dev Check if contract was received by other side properly if receiver
/// is a ctontract.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
/// @param _data Transaction data.
/// @return True on success.
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal returns(bool)
{
if (! _to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
_from, _tokenId, _data
);
return (retval == ERC721_RECEIVED);
}
/// @dev Remove token from owner. Unrecoverable.
/// @param _tokenId Removing token id.
function _remove(uint256 _tokenId)
internal
{
address owner = tokens_[_tokenId].owner;
_removeFrom(owner, _tokenId);
}
/// @dev Completely remove token from the contract. Unrecoverable.
/// @param _owner Owner of removing token.
/// @param _tokenId Removing token id.
function _removeFrom(address _owner, uint256 _tokenId)
internal
{
uint256 lastIndex = ownTokens_[_owner].length.sub(1);
uint256 lastToken = ownTokens_[_owner][lastIndex];
// Swap users token
ownTokens_[_owner][ownerIndex_[_tokenId]] = lastToken;
ownTokens_[_owner].length--;
// Swap token indexes
ownerIndex_[lastToken] = ownerIndex_[_tokenId];
ownerIndex_[_tokenId] = 0;
DragonToken storage token = tokens_[_tokenId];
token.owner = NA;
}
/// @dev Transfer token from owner `_from` to another address or contract
/// `_to` by it's `_tokenId`.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
function transferFrom( address _from, address _to, uint256 _tokenId )
public ownerOrApprovedOnly(_tokenId)
{
require(_from != NA);
require(_to != NA);
_clearApproval(_from, _tokenId);
_removeFrom(_from, _tokenId);
_addTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
DragonToken storage token = tokens_[_tokenId];
emit TransferInfo(_from, _to, _tokenId, token.petId, token.genome, token.params);
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated. Also notifies receiver of the token.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
function updateAndSafeTransferFrom(
address _to,
uint256 _tokenId,
string _params
)
public
{
updateAndSafeTransferFrom(_to, _tokenId, _params, "");
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated. Also notifies receiver of the token and send
/// protion of _data to it.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
/// @param _data Notification data.
function updateAndSafeTransferFrom(
address _to,
uint256 _tokenId,
string _params,
bytes _data
)
public
{
// Safe transfer from
updateAndTransferFrom(_to, _tokenId, _params, 0, 0);
require(_checkAndCallSafeTransfer(address(this), _to, _tokenId, _data));
}
/// @dev Update token params and transfer to new owner. Only contract's own
/// tokens could be updated.
/// @param _to Address to transfer token to.
/// @param _tokenId Id of token that should be transferred.
/// @param _params New token params.
function updateAndTransferFrom(
address _to,
uint256 _tokenId,
string _params,
uint256 _petId,
uint256 _transferCost
)
public
ownOnly(_tokenId)
minionOnly
{
require(bytes(_params).length > 0, "params_length");
// Update
tokens_[_tokenId].params = _params;
if (tokens_[_tokenId].petId == 0 ) {
tokens_[_tokenId].petId = _petId;
}
address from = tokens_[_tokenId].owner;
// Transfer from
transferFrom(from, _to, _tokenId);
// send to the server's wallet the transaction cost
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
}
/// @dev Transfer token from one owner to new one and check if it was
/// properly received if receiver is a contact.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
safeTransferFrom(_from, _to, _tokenId, "");
}
/// @dev Transfer token from one owner to new one and check if it was
/// properly received if receiver is a contact.
/// @param _from Current token owner.
/// @param _to New token owner.
/// @param _tokenId token Id.
/// @param _data Transaction data.
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
{
transferFrom(_from, _to, _tokenId);
require(_checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/// @dev Burn owned token. Increases `burnCount_` and decrease `totalSupply`
/// value.
/// @param _tokenId Id of burning token.
function burn(uint256 _tokenId)
public
ownerOrApprovedOnly(_tokenId)
{
address owner = tokens_[_tokenId].owner;
_remove(_tokenId);
burnCount_ += 1;
emit Transfer(owner, NA, _tokenId);
}
/// @dev Receive count of burned tokens. Should be greater than `totalSupply`
/// but less than `mintCount`.
/// @return Number of burned tokens
function burnCount()
external
view
returns(uint256)
{
return burnCount_;
}
function onERC721Received(address, uint256, bytes)
public returns(bytes4)
{
return ERC721_RECEIVED;
}
}
/// @title Managing contract. implements the logic of buying tokens, depositing / withdrawing funds
/// to the project account and importing / exporting tokens
contract EtherDragonsCore is DragonOwnership
{
using SafeMath8 for uint8;
using SafeMath32 for uint32;
using SafeMath256 for uint256;
using AddressUtils for address;
using StringUtils for string;
using UintStringUtils for uint;
// @dev Non Assigned address.
address constant NA = address(0);
/// @dev Bounty tokens count limit
uint256 public constant BOUNTY_LIMIT = 2500;
/// @dev Presale tokens count limit
uint256 public constant PRESALE_LIMIT = 7500;
///@dev Total gen0tokens generation limit
uint256 public constant GEN0_CREATION_LIMIT = 90000;
/// @dev Number of tokens minted in presale stage
uint256 internal presaleCount_;
/// @dev Number of tokens minted for bounty campaign
uint256 internal bountyCount_;
///@dev Company bank address
address internal bank_;
// Extension ---------------------------------------------------------------
/// @dev Contract is not payable. To fullfil balance method `depositTo`
/// should be used.
function ()
public payable
{
revert();
}
/// @dev amount on the account of the contract. This amount consists of deposits from players and the system reserve for payment of transactions
/// the player at any time to withdraw the amount corresponding to his account in the game, minus the cost of the transaction
function getBalance()
public view returns (uint256)
{
return address(this).balance;
}
/// @dev at the moment of creation of the contract we transfer the address of the bank
/// presell contract address set later
constructor(
address _bank
)
public
{
require(_bank != NA);
controller_ = msg.sender;
bank_ = _bank;
// Meta
name_ = "EtherDragons";
symbol_ = "ED";
url_ = "https://game.etherdragons.world/token/";
// Token mint limit
maxSupply_ = GEN0_CREATION_LIMIT + BOUNTY_LIMIT + PRESALE_LIMIT;
}
/// Number of tokens minted in presale stage
function totalPresaleCount()
public view returns(uint256)
{
return presaleCount_;
}
/// @dev Number of tokens minted for bounty campaign
function totalBountyCount()
public view returns(uint256)
{
return bountyCount_;
}
/// @dev Check if new token could be minted. Return true if count of minted
/// tokens less than could be minted through contract deploy.
/// Also, tokens can not be created more often than once in mintDelay_ minutes
/// @return True if current count is less then maximum tokens available for now.
function canMint()
public view returns(bool)
{
return (mintCount_ + presaleCount_ + bountyCount_) < maxSupply_;
}
/// @dev Here we write the addresses of the wallets of the server from which it is accessed
/// to contract methods.
/// @param _to New minion address
function minionAdd(address _to)
external controllerOnly
{
require(minions_[_to] == false, "already_minion");
// разрешаем этому адресу пользоваться токенами контакта
// allow the address to use contract tokens
_setApprovalForAll(address(this), _to, true);
minions_[_to] = true;
}
/// @dev delete the address of the server wallet
/// @param _to Minion address
function minionRemove(address _to)
external controllerOnly
{
require(minions_[_to], "not_a_minion");
// and forbid this wallet to use tokens of the contract
_setApprovalForAll(address(this), _to, false);
minions_[_to] = false;
}
/// @dev Here the player can put funds to the account of the contract
/// and get the same amount of in-game currency
/// the game server understands who puts money at the wallet address
function depositTo()
public payable
{
emit Deposit(msg.sender, msg.value);
}
/// @dev Transfer amount of Ethers to specified receiver. Only owner can
// call this method.
/// @param _to Transfer receiver.
/// @param _amount Transfer value.
/// @param _transferCost Transfer cost.
function transferAmount(address _to, uint256 _amount, uint256 _transferCost)
external minionOnly
{
require((_amount + _transferCost) <= address(this).balance, "not enough money!");
_to.transfer(_amount);
// send to the wallet of the server the transfer cost
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
emit Withdraw(_to, _amount);
}
/// @dev Mint new token with specified params. Transfer `_fee` to the
/// `bank`.
/// @param _to New token owner.
/// @param _fee Transaction fee.
/// @param _genNum Generation number..
/// @param _genome New genome unique value.
/// @param _parentA Parent A.
/// @param _parentB Parent B.
/// @param _petId Pet identifier.
/// @param _params List of parameters for pet.
/// @param _transferCost Transfer cost.
/// @return New token id.
function mintRelease(
address _to,
uint256 _fee,
// Constant Token params
uint8 _genNum,
string _genome,
uint256 _parentA,
uint256 _parentB,
// Game-depening Token params
uint256 _petId, //if petID = 0, then it was created outside of the server
string _params,
uint256 _transferCost
)
external minionOnly operateModeOnly returns(uint256)
{
require(canMint(), "can_mint");
require(_to != NA, "_to");
require((_fee + _transferCost) <= address(this).balance, "_fee");
require(bytes(_params).length != 0, "params_length");
require(bytes(_genome).length == 77, "genome_length");
// Parents should be both 0 or both not.
if (_parentA != 0 && _parentB != 0) {
require(_parentA != _parentB, "same_parent");
}
else if (_parentA == 0 && _parentB != 0) {
revert("parentA_empty");
}
else if (_parentB == 0 && _parentA != 0) {
revert("parentB_empty");
}
uint256 tokenId = _createToken(_to, _genNum, _genome, _parentA, _parentB, _petId, _params);
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
// Transfer mint fee to the fund
CommonWallet(bank_).receive.value(_fee)();
emit Transfer(NA, _to, tokenId);
// send to the server wallet server the transfer cost,
// withdraw it from the balance of the contract. this amount must be withdrawn from the player
// on the side of the game server
if (_transferCost > 0) {
msg.sender.transfer(_transferCost);
}
return tokenId;
}
/// @dev Create new token via presale state
/// @param _to New token owner.
/// @param _genome New genome unique value.
/// @return New token id.
/// at the pre-sale stage we sell the zero-generation pets, which have only a genome.
/// other attributes of such a token get when importing to the server
function mintPresell(address _to, string _genome)
external presaleOnly presaleModeOnly returns(uint256)
{
require(presaleCount_ < PRESALE_LIMIT, "presale_limit");
// у пресейл пета нет параметров. Их он получит после ввода в игру.
uint256 tokenId = _createToken(_to, 0, _genome, 0, 0, 0, "");
presaleCount_ += 1;
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
emit Transfer(NA, _to, tokenId);
return tokenId;
}
/// @dev Create new token for bounty activity
/// @param _to New token owner.
/// @return New token id.
function mintBounty(address _to, string _genome)
external controllerOnly returns(uint256)
{
require(bountyCount_ < BOUNTY_LIMIT, "bounty_limit");
// bounty pet has no parameters. They will receive them after importing to the game.
uint256 tokenId = _createToken(_to, 0, _genome, 0, 0, 0, "");
bountyCount_ += 1;
require(_checkAndCallSafeTransfer(NA, _to, tokenId, ""), "safe_transfer");
emit Transfer(NA, _to, tokenId);
return tokenId;
}
}
contract Presale
{
// Extension ---------------------------------------------------------------
using AddressUtils for address;
// Events ------------------------------------------------------------------
///the event is fired when starting a new wave presale stage
event StageBegin(uint8 stage, uint256 timestamp);
///the event is fired when token sold
event TokensBought(address buyerAddr, uint256[] tokenIds, bytes genomes);
// Types -------------------------------------------------------------------
struct Stage {
// Predefined values
uint256 price; // token's price on the stage
uint16 softcap; // stage softCap
uint16 hardcap; // stage hardCap
// Unknown values
uint16 bought; // sold on stage
uint32 startDate; // stage's beginDate
uint32 endDate; // stage's endDate
}
// Constants ---------------------------------------------------------------
// 10 stages of 5 genocodes
uint8 public constant STAGES = 10;
uint8 internal constant TOKENS_PER_STAGE = 5;
address constant NA = address(0);
// State -------------------------------------------------------------------
address internal CEOAddress; // contract owner
address internal bank_; // profit wallet address (not a contract)
address internal erc721_; // main contract address
/// @dev genomes for bounty stage
string[TOKENS_PER_STAGE][STAGES] internal genomes_;
/// stages data
Stage[STAGES] internal stages_;
// internal transaction counter, it uses for random generator
uint32 internal counter_;
/// stage is over
bool internal isOver_;
/// stage number
uint8 internal stageIndex_;
/// stage start Data
uint32 internal stageStart_;
// Lifetime ----------------------------------------------------------------
constructor(
address _bank,
address _erc721
)
public
{
require(_bank != NA, '_bank');
require(_erc721.isContract(), '_erc721');
CEOAddress = msg.sender;
// Addresses should not be the same.
require(_bank != CEOAddress, "bank = CEO");
require(CEOAddress != _erc721, "CEO = erc721");
require(_erc721 != _bank, "bank = erc721");
// Update state
bank_ = _bank;
erc721_ = _erc721;
// stages data
stages_[0].price = 10 finney;
stages_[0].softcap = 100;
stages_[0].hardcap = 300;
stages_[1].price = 20 finney;
stages_[1].softcap = 156;
stages_[1].hardcap = 400;
stages_[2].price = 32 finney;
stages_[2].softcap = 212;
stages_[2].hardcap = 500;
stages_[3].price = 45 finney;
stages_[3].softcap = 268;
stages_[3].hardcap = 600;
stages_[4].price = 58 finney;
stages_[4].softcap = 324;
stages_[4].hardcap = 700;
stages_[5].price = 73 finney;
stages_[5].softcap = 380;
stages_[5].hardcap = 800;
stages_[6].price = 87 finney;
stages_[6].softcap = 436;
stages_[6].hardcap = 900;
stages_[7].price = 102 finney;
stages_[7].softcap = 492;
stages_[7].hardcap = 1000;
stages_[8].price = 118 finney;
stages_[8].softcap = 548;
stages_[8].hardcap = 1100;
stages_[9].price = 129 finney;
stages_[9].softcap = 604;
stages_[9].hardcap = 1200;
}
/// fill the genomes data
function setStageGenomes(
uint8 _stage,
string _genome0,
string _genome1,
string _genome2,
string _genome3,
string _genome4
)
external controllerOnly
{
genomes_[_stage][0] = _genome0;
genomes_[_stage][1] = _genome1;
genomes_[_stage][2] = _genome2;
genomes_[_stage][3] = _genome3;
genomes_[_stage][4] = _genome4;
}
/// @dev Contract itself is non payable
function ()
public payable
{
revert();
}
// Modifiers ---------------------------------------------------------------
/// only from contract owner
modifier controllerOnly() {
require(msg.sender == CEOAddress, 'controller_only');
_;
}
/// only for active stage
modifier notOverOnly() {
require(isOver_ == false, 'notOver_only');
_;
}
// Getters -----------------------------------------------------------------
/// owner address
function getCEOAddress()
public view returns(address)
{
return CEOAddress;
}
/// counter from random number generator
function counter()
internal view returns(uint32)
{
return counter_;
}
// tokens sold by stage ...
function stageTokensBought(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].bought;
}
// stage softcap
function stageSoftcap(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].softcap;
}
/// stage hardcap
function stageHardcap(uint8 _stage)
public view returns(uint16)
{
return stages_[_stage].hardcap;
}
/// stage Start Date
function stageStartDate(uint8 _stage)
public view returns(uint)
{
return stages_[_stage].startDate;
}
/// stage Finish Date
function stageEndDate(uint8 _stage)
public view returns(uint)
{
return stages_[_stage].endDate;
}
/// stage token price
function stagePrice(uint _stage)
public view returns(uint)
{
return stages_[_stage].price;
}
// Genome Logic -----------------------------------------------------------------
/// within the prelase , the dragons are generated, which are the ancestors of the destiny
/// newborns have a high chance of mutation and are unlikely to be purebred
/// the player will have to collect the breed, crossing a lot of pets
/// In addition, you will need to pick up combat abilities
/// these characteristics are assigned to the pet when the dragon is imported to the game server.
function nextGenome()
internal returns(string)
{
uint8 n = getPseudoRandomNumber();
counter_ += 1;
return genomes_[stageIndex_][n];
}
function getPseudoRandomNumber()
internal view returns(uint8 index)
{
uint8 n = uint8(
keccak256(abi.encode(msg.sender, block.timestamp + counter_))
);
return n % TOKENS_PER_STAGE;
}
// PreSale Logic -----------------------------------------------------------------
/// Presale stage0 begin date set
/// presale start is possible only once
function setStartDate(uint32 _startDate)
external controllerOnly
{
require(stages_[0].startDate == 0, 'already_set');
stages_[0].startDate = _startDate;
stageStart_ = _startDate;
stageIndex_ = 0;
emit StageBegin(stageIndex_, stageStart_);
}
/// current stage number
/// switches to the next stage if the time has come
function stageIndex()
external view returns(uint8)
{
Stage memory stage = stages_[stageIndex_];
if (stage.endDate > 0 && stage.endDate <= now) {
return stageIndex_ + 1;
}
else {
return stageIndex_;
}
}
/// check whether the phase started
/// switch to the next stage, if necessary
function beforeBuy()
internal
{
if (stageStart_ == 0) {
revert('presale_not_started');
}
else if (stageStart_ > now) {
revert('stage_not_started');
}
Stage memory stage = stages_[stageIndex_];
if (stage.endDate > 0 && stage.endDate <= now)
{
stageIndex_ += 1;
stageStart_ = stages_[stageIndex_].startDate;
if (stageStart_ > now) {
revert('stage_not_started');
}
}
}
/// time to next midnight
function midnight()
public view returns(uint32)
{
uint32 tomorrow = uint32(now + 1 days);
uint32 remain = uint32(tomorrow % 1 days);
return tomorrow - remain;
}
/// buying a specified number of tokens
function buyTokens(uint16 numToBuy)
public payable notOverOnly returns(uint256[])
{
beforeBuy();
require(numToBuy > 0 && numToBuy <= 10, "numToBuy error");
Stage storage stage = stages_[stageIndex_];
require((stage.price * numToBuy) <= msg.value, 'price');
uint16 prevBought = stage.bought;
require(prevBought + numToBuy <= stage.hardcap, "have required tokens");
stage.bought += numToBuy;
uint256[] memory tokenIds = new uint256[](numToBuy);
bytes memory genomes = new bytes(numToBuy * 77);
uint32 genomeByteIndex = 0;
for(uint16 t = 0; t < numToBuy; t++)
{
string memory genome = nextGenome();
uint256 tokenId = EtherDragonsCore(erc721_).mintPresell(msg.sender, genome);
bytes memory genomeBytes = bytes(genome);
for(uint8 gi = 0; gi < genomeBytes.length; gi++) {
genomes[genomeByteIndex++] = genomeBytes[gi];
}
tokenIds[t] = tokenId;
}
// Transfer mint fee to the fund
bank_.transfer(address(this).balance);
if (stage.bought == stage.hardcap) {
stage.endDate = uint32(now);
stageStart_ = midnight() + 1 days + 1 seconds;
if (stageIndex_ < STAGES - 1) {
stageIndex_ += 1;
}
else {
isOver_ = true;
}
}
else if (stage.bought >= stage.softcap && prevBought < stage.softcap) {
stage.endDate = midnight() + 1 days;
if (stageIndex_ < STAGES - 1) {
stages_[stageIndex_ + 1].startDate = stage.endDate + 1 days;
}
}
emit TokensBought(msg.sender, tokenIds, genomes);
return tokenIds;
}
function currTime()
public view returns(uint)
{
return now;
}
/// stages data
function getStagesInfo()
public view returns (uint256[] prices, uint16[] softcaps, uint16[] hardcaps, uint16[] boughts)
{
prices = new uint256[](STAGES);
softcaps = new uint16[](STAGES);
hardcaps = new uint16[](STAGES);
boughts = new uint16[](STAGES);
for(uint8 s = 0; s < STAGES; s++) {
prices[s] = stages_[s].price;
softcaps[s] = stages_[s].softcap;
hardcaps[s] = stages_[s].hardcap;
boughts[s] = stages_[s].bought;
}
}
/// stages dates data
function getStagesBeginEnd()
public view returns (uint32[] startDates, uint32[] endDates)
{
startDates = new uint32[](STAGES);
endDates = new uint32[](STAGES);
for(uint8 s = 0; s < STAGES; s++) {
startDates[s] = stages_[s].startDate;
endDates[s] = stages_[s].endDate;
}
}
/// returns data which genomes can be purchased at the stage
function stageGenomes(uint8 _stage)
public view returns(byte[])
{
byte[] memory genomes = new byte[](uint16(TOKENS_PER_STAGE) * 77);
uint32 gbIndex = 0;
for(uint8 tokenIndex = 0; tokenIndex < TOKENS_PER_STAGE; tokenIndex++) {
bytes memory genomeBytes = bytes(genomes_[_stage][tokenIndex]);
for(uint8 gi = 0; gi < genomeBytes.length; gi++) {
genomes[gbIndex++] = genomeBytes[gi];
}
}
return genomes;
}
}
|
Get token params. _tokenId Token id. return Token's params.
|
function getParams(uint256 _tokenId)
external view returns(string)
{
return tokens_[_tokenId].params;
}
| 5,397,163 |
pragma solidity ^0.4.24;
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
contract F3Devents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract FoMoRapid is F3Devents{
using SafeMath for uint256;
using NameFilter for string;
using F3DKeysCalcFast for uint256;
address admin;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x56a4d4e31c09558F6A1619DFb857a482B3Bb2Fb6);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "FoMo3D Soon(tm) Edition";
string constant public symbol = "F3D";
uint256 private rndGap_ = 60 seconds; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 5 minutes; // round timer starts at this
uint256 constant private rndInc_ = 5 minutes; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 5 minutes; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com
potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com
potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = F3Ddatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com
admin = msg.sender;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
require (_addr == tx.origin);
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* - during live round. this is accurate. (well... unless someone buys before
* you do and ups the price! you better HURRY!)
* - during ICO phase. this is the max you would get based on current eth
* invested during ICO phase. if others invest after you, you will receive
* less. (so distract them with meme vids till ICO is over)
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// is ICO phase over?? & theres eth in the round?
if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)
return ( ((round_[_rID].ico.keys()).add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 100000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in ICO phase?
if (_now <= round_[_rID].strt + rndGap_)
return( ((round_[_rID].end).sub(rndInit_)).sub(_now) );
else
if (_now < round_[_rID].end)
return( (round_[_rID].end).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false)
{
uint256 _roundMask;
uint256 _roundEth;
uint256 _roundKeys;
uint256 _roundPot;
if (round_[_rID].eth == 0 && round_[_rID].ico > 0)
{
// create a temp round eth based on eth sent in during ICO phase
_roundEth = round_[_rID].ico;
// create a temp round keys based on keys bought during ICO phase
_roundKeys = (round_[_rID].ico).keys();
// create a temp round mask based on eth and keys from ICO phase
_roundMask = ((round_[_rID].icoGen).mul(1000000000000000000)) / _roundKeys;
// create a temp rount pot based on pot, and dust from mask
_roundPot = (round_[_rID].pot).add((round_[_rID].icoGen).sub((_roundMask.mul(_roundKeys)) / (1000000000000000000)));
} else {
_roundEth = round_[_rID].eth;
_roundKeys = round_[_rID].keys;
_roundMask = round_[_rID].mask;
_roundPot = round_[_rID].pot;
}
uint256 _playerKeys;
if (plyrRnds_[_pID][plyr_[_pID].lrnd].ico == 0)
_playerKeys = plyrRnds_[_pID][plyr_[_pID].lrnd].keys;
else
_playerKeys = calcPlayerICOPhaseKeys(_pID, _rID);
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( (_roundPot.mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _roundMask, _roundPot, _roundKeys, _playerKeys) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _roundMask, _roundPot, _roundKeys, _playerKeys) ),
plyr_[_pID].aff
);
}
// if round is still going on, we are in ico phase, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _roundMask, uint256 _roundPot, uint256 _roundKeys, uint256 _playerKeys)
private
view
returns(uint256)
{
return( (((_roundMask.add((((_roundPot.mul(potSplit_[round_[rID_].team].gen)) / 100).mul(1000000000000000000)) / _roundKeys)).mul(_playerKeys)) / 1000000000000000000).sub(plyrRnds_[_pID][rID_].mask) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (round_[_rID].eth != 0)
{
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
} else {
return
(
round_[_rID].ico, //0
_rID, //1
(round_[_rID].ico).keys(), //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player ico eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
if (plyrRnds_[_pID][_rID].ico == 0)
{
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
0 //6
);
} else {
return
(
_pID, //0
plyr_[_pID].name, //1
calcPlayerICOPhaseKeys(_pID, _rID), //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].ico //6
);
}
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in ICO phase or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// check to see if round has ended. and if player is new to round
_eventData_ = manageRoundAndPlayer(_pID, _eventData_);
// are we in ICO phase?
if (now <= round_[rID_].strt + rndGap_)
{
// let event data know this is a ICO phase buy order
_eventData_.compressedData = _eventData_.compressedData + 2000000000000000000000000000000;
// ICO phase core
icoPhaseCore(_pID, msg.value, _team, _affID, _eventData_);
// round is live
} else {
// let event data know this is a buy order
_eventData_.compressedData = _eventData_.compressedData + 1000000000000000000000000000000;
// call core
core(_pID, msg.value, _affID, _team, _eventData_);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in ICO phase or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// check to see if round has ended. and if player is new to round
_eventData_ = manageRoundAndPlayer(_pID, _eventData_);
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// are we in ICO phase?
if (now <= round_[rID_].strt + rndGap_)
{
// let event data know this is an ICO phase reload
_eventData_.compressedData = _eventData_.compressedData + 3000000000000000000000000000000;
// ICO phase core
icoPhaseCore(_pID, _eth, _team, _affID, _eventData_);
// round is live
} else {
// call core
core(_pID, _eth, _affID, _team, _eventData_);
}
}
/**
* @dev during ICO phase all eth sent in by each player. will be added to an
* "investment pool". upon end of ICO phase, all eth will be used to buy keys.
* each player receives an amount based on how much they put in, and the
* the average price attained.
*/
function icoPhaseCore(uint256 _pID, uint256 _eth, uint256 _team, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// if they bought at least 1 whole key (at time of purchase)
if ((round_[_rID].ico).keysRec(_eth) >= 1000000000000000000 || round_[_rID].plyr == 0)
{
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// add eth to our players & rounds ICO phase investment. this will be used
// to determine total keys and each players share
plyrRnds_[_pID][_rID].ico = _eth.add(plyrRnds_[_pID][_rID].ico);
round_[_rID].ico = _eth.add(round_[_rID].ico);
// add eth in to team eth tracker
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// send eth share to com, p3d, affiliate, and fomo3d long
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// add gen share to rounds ICO phase gen tracker (will be distributed
// when round starts)
round_[_rID].icoGen = _gen.add(round_[_rID].icoGen);
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// calculate pot share pot (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) - gen
uint256 _pot = (_eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100))).sub(_gen);
// add eth to pot
round_[_rID].pot = _pot.add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
// fire event
endTx(_rID, _pID, _team, _eth, 0, _eventData_);
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// check to see if its a new round (past ICO phase) && keys were bought in ICO phase
if (round_[_rID].eth == 0 && round_[_rID].ico > 0)
roundClaimICOKeys(_rID);
// if player is new to round and is owed keys from ICO phase
if (plyrRnds_[_pID][_rID].keys == 0 && plyrRnds_[_pID][_rID].ico > 0)
{
// assign player their keys from ICO phase
plyrRnds_[_pID][_rID].keys = calcPlayerICOPhaseKeys(_pID, _rID);
// zero out ICO phase investment
plyrRnds_[_pID][_rID].ico = 0;
}
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 1 prize was won
_eventData_.compressedData += 100000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_rID, _pID, _team, _eth, _keys, _eventData_);
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
// if player does not have unclaimed keys bought in ICO phase
// return their earnings based on keys held only.
if (plyrRnds_[_pID][_rIDlast].ico == 0)
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
else
if (now > round_[_rIDlast].strt + rndGap_ && round_[_rIDlast].eth == 0)
return( (((((round_[_rIDlast].icoGen).mul(1000000000000000000)) / (round_[_rIDlast].ico).keys()).mul(calcPlayerICOPhaseKeys(_pID, _rIDlast))) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
else
return( (((round_[_rIDlast].mask).mul(calcPlayerICOPhaseKeys(_pID, _rIDlast))) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
// otherwise return earnings based on keys owed from ICO phase
// (this would be a scenario where they only buy during ICO phase, and never
// buy/reload during round)
}
/**
* @dev average ico phase key price is total eth put in, during ICO phase,
* divided by the number of keys that were bought with that eth.
* -functionhash- 0xdcb6af48
* @return average key price
*/
function calcAverageICOPhaseKeyPrice(uint256 _rID)
public
view
returns(uint256)
{
return( (round_[_rID].ico).mul(1000000000000000000) / (round_[_rID].ico).keys() );
}
/**
* @dev at end of ICO phase, each player is entitled to X keys based on final
* average ICO phase key price, and the amount of eth they put in during ICO.
* if a player participates in the round post ICO, these will be "claimed" and
* added to their rounds total keys. if not, this will be used to calculate
* their gen earnings throughout round and on round end.
* -functionhash- 0x75661f4c
* @return players keys bought during ICO phase
*/
function calcPlayerICOPhaseKeys(uint256 _pID, uint256 _rID)
public
view
returns(uint256)
{
if (round_[_rID].icoAvg != 0 || round_[_rID].ico == 0 )
return( ((plyrRnds_[_pID][_rID].ico).mul(1000000000000000000)) / round_[_rID].icoAvg );
else
return( ((plyrRnds_[_pID][_rID].ico).mul(1000000000000000000)) / calcAverageICOPhaseKeyPrice(_rID) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* - during live round. this is accurate. (well... unless someone buys before
* you do and ups the price! you better HURRY!)
* - during ICO phase. this is the max you would get based on current eth
* invested during ICO phase. if others invest after you, you will receive
* less. (so distract them with meme vids till ICO is over)
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// is ICO phase over?? & theres eth in the round?
if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)
return ( (round_[_rID].eth).keysRec(_eth) );
else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)
return ( (round_[_rID].ico).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* - during live round. this is accurate. (well... unless someone buys before
* you do and ups the price! you better HURRY!)
* - during ICO phase. this is the max you would get based on current eth
* invested during ICO phase. if others invest after you, you will receive
* less. (so distract them with meme vids till ICO is over)
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// is ICO phase over?? & theres eth in the round?
if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)
return ( (((round_[_rID].ico).keys()).add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function manageRoundAndPlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// check to see if round has ended. we use > instead of >= so that LAST
// second snipe tx can extend the round.
if (_now > round_[_rID].end)
{
// check to see if round end has been run yet. (distributes pot)
if (round_[_rID].ended == false)
{
_eventData_ = endRound(_eventData_);
round_[_rID].ended = true;
}
// start next round in ICO phase
rID_++;
_rID++;
round_[_rID].strt = _now;
round_[_rID].end = _now.add(rndInit_).add(rndGap_);
}
// is player new to round?
if (plyr_[_pID].lrnd != _rID)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = _rID;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
}
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// check to round ended with ONLY ico phase transactions
if (round_[_rID].eth == 0 && round_[_rID].ico > 0)
roundClaimICOKeys(_rID);
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
admin.transfer(_p3d.add(_com));
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// fill next round pot with its share
round_[_rID + 1].pot += _res;
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
return(_eventData_);
}
/**
* @dev takes keys bought during ICO phase, and adds them to round. pays
* out gen rewards that accumulated during ICO phase
*/
function roundClaimICOKeys(uint256 _rID)
private
{
// update round eth to account for ICO phase eth investment
round_[_rID].eth = round_[_rID].ico;
// add keys to round that were bought during ICO phase
round_[_rID].keys = (round_[_rID].ico).keys();
// store average ICO key price
round_[_rID].icoAvg = calcAverageICOPhaseKeyPrice(_rID);
// set round mask from ICO phase
uint256 _ppt = ((round_[_rID].icoGen).mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = (round_[_rID].icoGen).sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000));
if (_dust > 0)
round_[_rID].pot = (_dust).add(round_[_rID].pot); // <<< your adding to pot and havent updated event data
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// calculate time based on number of keys bought
uint256 _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// grab time
uint256 _now = now;
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _com;
_com = 0;
}
// pay 1% out to FoMo3D long
uint256 _long = _eth / 100;
admin.transfer(_long);
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to divies contract
admin.transfer(_p3d);
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _rID, uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (_rID * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C ||
msg.sender == 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D ||
msg.sender == 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53 ||
msg.sender == 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C ||
msg.sender == 0xF39e044e1AB204460e06E87c6dca2c6319fC69E3,
"only team just can activate"
);
// can only be ran once
require(activated_ == false, "fomo3d already activated");
// activate the contract
activated_ = true;
// lets start first round in ICO phase
rID_ = 1;
round_[1].strt = now;
round_[1].end = now + rndInit_ + rndGap_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library F3Ddatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library F3DKeysCalcFast {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(200000000000000000000000000000000)).add(2500000000000000000000000000000000000000000000000000000000000000)).sqrt()).sub(50000000000000000000000000000000)) / (100000000000000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((50000000000000).mul(_keys.sq()).add(((100000000000000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface DiviesInterface {
function deposit() external payable;
}
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
/**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
logic runs whenever a reload order is executed. determines how to handle incoming eth depending on if we are in ICO phase or not/ check to see if round has ended. and if player is new to round get earnings from all vaults and return unused to gen vault because we use a custom safemath library. this will throw if player tried to spend more eth than they have. are we in ICO phase? let event data know this is an ICO phase reload ICO phase core round is live call core
|
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_ = manageRoundAndPlayer(_pID, _eventData_);
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
if (now <= round_[rID_].strt + rndGap_)
{
_eventData_.compressedData = _eventData_.compressedData + 3000000000000000000000000000000;
icoPhaseCore(_pID, _eth, _team, _affID, _eventData_);
core(_pID, _eth, _affID, _team, _eventData_);
}
}
| 10,464,539 |
// SPDX-License-Identifier: MIT
/*
Factory to create brand specific loyalty ERC20 tokens and keep track of them
*/
pragma solidity ^0.8.4;
import "hardhat/console.sol";
import "./LoyaltyERC20.sol";
contract LoyaltyCoinFactory {
mapping(address => bool) public admins;
address owner;
mapping(string => address) public loyaltyCoins;
uint256 public totalCoins;
event CoinCreated(address indexed _creator, address indexed _coinAddress, string indexed _tokenSymbol, uint _totalSupply);
event CoinsRedeemed(address indexed _user, string indexed _tokenSymbol);
constructor() {
owner = msg.sender;
admins[msg.sender] = true;
}
// change permissions later to only allow brand addresses authorized to create a coin
function createLoyaltyERC20Coin(string memory _tokenName, string memory _tokenSymbol, uint256 _totalSupply) public onlyOwnerAndAdmin {
loyaltyCoins[_tokenSymbol] = address(new LoyaltyERC20(_tokenName, _tokenSymbol, _totalSupply, msg.sender));
totalCoins++;
emit CoinCreated(msg.sender, loyaltyCoins[_tokenSymbol] , _tokenSymbol, _totalSupply);
}
//
function getCoinAddressBySymbol(string memory _tokenSymbol) public view returns(address) {
//require(LoyaltyERC20(loyaltyCoins[_tokenSymbol]).owner() != msg.sender, "does not own the token");
return(loyaltyCoins[_tokenSymbol]);
}
modifier onlyOwnerAndAdmin {
require(msg.sender == owner || admins[msg.sender], "not admin or owner");
_;
}
modifier onlyOwner {
require(msg.sender == owner, "not the owner");
_;
}
function addAdmin(address _admin) external onlyOwner {
admins[_admin] = true;
}
function deactivateAdmin(address _admin) external onlyOwner {
admins[_admin] = false;
}
//user initiated to redeem coins for items
function redeemCoins(string memory _tokenSymbol, uint256 _amount) external {
address loyaltyCoinAddress = getCoinAddressBySymbol(_tokenSymbol);
LoyaltyERC20 coin = LoyaltyERC20(loyaltyCoinAddress);
require(coin.balanceOf(msg.sender) > _amount, "not enough coins to redeem");
address coinOwner = coin.owner();
console.log("coin owner: ", coinOwner);
console.log("for coin: ", coin.symbol());
//coin.approve(address(this), _amount);
console.log("allowance: ", coin.allowance(msg.sender, address(this)));
coin.transferFrom(msg.sender, coinOwner, _amount);
emit CoinsRedeemed(msg.sender, _tokenSymbol);
}
}
|
require(LoyaltyERC20(loyaltyCoins[_tokenSymbol]).owner() != msg.sender, "does not own the token");
|
function getCoinAddressBySymbol(string memory _tokenSymbol) public view returns(address) {
return(loyaltyCoins[_tokenSymbol]);
}
| 12,625,105 |
./partial_match/1/0xE3c8a598ea5D68e1555818542ab4FFD90C61EB32/sources/YVAULTMASTER.sol
|
Update dev address by the previous dev.
|
function setDevAddress(address _devaddr) public {
require(msg.sender == devaddr, "only previous dev can change dev address");
devaddr = _devaddr;
}
| 16,078,949 |
./partial_match/1/0xb2f86E77c1D42889d60587a8431040dBC29d772a/sources/SHIBASONICBOOM.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("Sonic Shiba", "$BOOMS") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 4;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 4;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 15,609,783 |
/**
*Submitted for verification at Etherscan.io on 2021-04-07
*/
pragma solidity 0.6.7;
contract GebMath {
uint256 public constant RAY = 10 ** 27;
uint256 public constant WAD = 10 ** 18;
function ray(uint x) public pure returns (uint z) {
z = multiply(x, 10 ** 9);
}
function rad(uint x) public pure returns (uint z) {
z = multiply(x, 10 ** 27);
}
function minimum(uint x, uint y) public pure returns (uint z) {
z = (x <= y) ? x : y;
}
function addition(uint x, uint y) public pure returns (uint z) {
z = x + y;
require(z >= x, "uint-uint-add-overflow");
}
function subtract(uint x, uint y) public pure returns (uint z) {
z = x - y;
require(z <= x, "uint-uint-sub-underflow");
}
function multiply(uint x, uint y) public pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "uint-uint-mul-overflow");
}
function rmultiply(uint x, uint y) public pure returns (uint z) {
z = multiply(x, y) / RAY;
}
function rdivide(uint x, uint y) public pure returns (uint z) {
z = multiply(x, RAY) / y;
}
function wdivide(uint x, uint y) public pure returns (uint z) {
z = multiply(x, WAD) / y;
}
function wmultiply(uint x, uint y) public pure returns (uint z) {
z = multiply(x, y) / WAD;
}
function rpower(uint x, uint n, uint base) public pure returns (uint z) {
assembly {
switch x case 0 {switch n case 0 {z := base} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := base } default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, base)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, base)
}
}
}
}
}
}
abstract contract StabilityFeeTreasuryLike {
function getAllowance(address) virtual external view returns (uint, uint);
function systemCoin() virtual external view returns (address);
function pullFunds(address, address, uint) virtual external;
}
contract IncreasingTreasuryReimbursement is GebMath {
// --- Auth ---
mapping (address => uint) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "IncreasingTreasuryReimbursement/account-not-authorized");
_;
}
// --- Variables ---
// Starting reward for the fee receiver/keeper
uint256 public baseUpdateCallerReward; // [wad]
// Max possible reward for the fee receiver/keeper
uint256 public maxUpdateCallerReward; // [wad]
// Max delay taken into consideration when calculating the adjusted reward
uint256 public maxRewardIncreaseDelay; // [seconds]
// Rate applied to baseUpdateCallerReward every extra second passed beyond a certain point (e.g next time when a specific function needs to be called)
uint256 public perSecondCallerRewardIncrease; // [ray]
// SF treasury
StabilityFeeTreasuryLike public treasury;
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(
bytes32 parameter,
address addr
);
event ModifyParameters(
bytes32 parameter,
uint256 val
);
event FailRewardCaller(bytes revertReason, address feeReceiver, uint256 amount);
constructor(
address treasury_,
uint256 baseUpdateCallerReward_,
uint256 maxUpdateCallerReward_,
uint256 perSecondCallerRewardIncrease_
) public {
if (address(treasury_) != address(0)) {
require(StabilityFeeTreasuryLike(treasury_).systemCoin() != address(0), "IncreasingTreasuryReimbursement/treasury-coin-not-set");
}
require(maxUpdateCallerReward_ >= baseUpdateCallerReward_, "IncreasingTreasuryReimbursement/invalid-max-caller-reward");
require(perSecondCallerRewardIncrease_ >= RAY, "IncreasingTreasuryReimbursement/invalid-per-second-reward-increase");
authorizedAccounts[msg.sender] = 1;
treasury = StabilityFeeTreasuryLike(treasury_);
baseUpdateCallerReward = baseUpdateCallerReward_;
maxUpdateCallerReward = maxUpdateCallerReward_;
perSecondCallerRewardIncrease = perSecondCallerRewardIncrease_;
maxRewardIncreaseDelay = uint(-1);
emit AddAuthorization(msg.sender);
emit ModifyParameters("treasury", treasury_);
emit ModifyParameters("baseUpdateCallerReward", baseUpdateCallerReward);
emit ModifyParameters("maxUpdateCallerReward", maxUpdateCallerReward);
emit ModifyParameters("perSecondCallerRewardIncrease", perSecondCallerRewardIncrease);
}
// --- Boolean Logic ---
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
// --- Treasury ---
/**
* @notice This returns the stability fee treasury allowance for this contract by taking the minimum between the per block and the total allowances
**/
function treasuryAllowance() public view returns (uint256) {
(uint total, uint perBlock) = treasury.getAllowance(address(this));
return minimum(total, perBlock);
}
/*
* @notice Get the SF reward that can be sent to a function caller right now
* @param timeOfLastUpdate The last time when the function that the treasury pays for has been updated
* @param defaultDelayBetweenCalls Enforced delay between calls to the function for which the treasury reimburses callers
*/
function getCallerReward(uint256 timeOfLastUpdate, uint256 defaultDelayBetweenCalls) public view returns (uint256) {
// If the rewards are null or if the time of the last update is in the future or present, return 0
bool nullRewards = (baseUpdateCallerReward == 0 && maxUpdateCallerReward == 0);
if (either(timeOfLastUpdate >= now, nullRewards)) return 0;
// If the time elapsed is smaller than defaultDelayBetweenCalls or if the base reward is zero, return 0
uint256 timeElapsed = (timeOfLastUpdate == 0) ? defaultDelayBetweenCalls : subtract(now, timeOfLastUpdate);
if (either(timeElapsed < defaultDelayBetweenCalls, baseUpdateCallerReward == 0)) {
return 0;
}
// If too much time elapsed, return the max reward
uint256 adjustedTime = subtract(timeElapsed, defaultDelayBetweenCalls);
uint256 maxPossibleReward = minimum(maxUpdateCallerReward, treasuryAllowance() / RAY);
if (adjustedTime > maxRewardIncreaseDelay) {
return maxPossibleReward;
}
// Calculate the reward
uint256 calculatedReward = baseUpdateCallerReward;
if (adjustedTime > 0) {
calculatedReward = rmultiply(rpower(perSecondCallerRewardIncrease, adjustedTime, RAY), calculatedReward);
}
// If the reward is higher than max, set it to max
if (calculatedReward > maxPossibleReward) {
calculatedReward = maxPossibleReward;
}
return calculatedReward;
}
/**
* @notice Send a stability fee reward to an address
* @param proposedFeeReceiver The SF receiver
* @param reward The system coin amount to send
**/
function rewardCaller(address proposedFeeReceiver, uint256 reward) internal {
// If the receiver is the treasury itself or if the treasury is null or if the reward is zero, return
if (address(treasury) == proposedFeeReceiver) return;
if (either(address(treasury) == address(0), reward == 0)) return;
// Determine the actual receiver and send funds
address finalFeeReceiver = (proposedFeeReceiver == address(0)) ? msg.sender : proposedFeeReceiver;
try treasury.pullFunds(finalFeeReceiver, treasury.systemCoin(), reward) {}
catch(bytes memory revertReason) {
emit FailRewardCaller(revertReason, finalFeeReceiver, reward);
}
}
}
abstract contract LiquidationEngineLike {
function currentOnAuctionSystemCoins() virtual public view returns (uint256);
function modifyParameters(bytes32, uint256) virtual external;
}
abstract contract SAFEEngineLike {
function globalDebt() virtual public view returns (uint256);
function globalUnbackedDebt() virtual public view returns (uint256);
function coinBalance(address) virtual public view returns (uint256);
}
contract CollateralAuctionThrottler is IncreasingTreasuryReimbursement {
// --- Variables ---
// Minimum delay between consecutive updates
uint256 public updateDelay; // [seconds]
// Delay since the last update time after which backupLimitRecompute can be called
uint256 public backupUpdateDelay; // [seconds]
// Percentage of global debt taken into account in order to set LiquidationEngine.onAuctionSystemCoinLimit
uint256 public globalDebtPercentage; // [hundred]
// The minimum auction limit
uint256 public minAuctionLimit; // [rad]
// Last timestamp when the onAuctionSystemCoinLimit was updated
uint256 public lastUpdateTime; // [unix timestamp]
LiquidationEngineLike public liquidationEngine;
SAFEEngineLike public safeEngine;
// List of surplus holders
address[] public surplusHolders;
constructor(
address safeEngine_,
address liquidationEngine_,
address treasury_,
uint256 updateDelay_,
uint256 backupUpdateDelay_,
uint256 baseUpdateCallerReward_,
uint256 maxUpdateCallerReward_,
uint256 perSecondCallerRewardIncrease_,
uint256 globalDebtPercentage_,
address[] memory surplusHolders_
) public IncreasingTreasuryReimbursement(treasury_, baseUpdateCallerReward_, maxUpdateCallerReward_, perSecondCallerRewardIncrease_) {
require(safeEngine_ != address(0), "CollateralAuctionThrottler/null-safe-engine");
require(liquidationEngine_ != address(0), "CollateralAuctionThrottler/null-liquidation-engine");
require(updateDelay_ > 0, "CollateralAuctionThrottler/null-update-delay");
require(backupUpdateDelay_ > updateDelay_, "CollateralAuctionThrottler/invalid-backup-update-delay");
require(both(globalDebtPercentage_ > 0, globalDebtPercentage_ <= HUNDRED), "CollateralAuctionThrottler/invalid-global-debt-percentage");
require(surplusHolders_.length <= HOLDERS_ARRAY_LIMIT, "CollateralAuctionThrottler/invalid-holder-array-length");
safeEngine = SAFEEngineLike(safeEngine_);
liquidationEngine = LiquidationEngineLike(liquidationEngine_);
updateDelay = updateDelay_;
backupUpdateDelay = backupUpdateDelay_;
globalDebtPercentage = globalDebtPercentage_;
surplusHolders = surplusHolders_;
emit ModifyParameters(bytes32("updateDelay"), updateDelay);
emit ModifyParameters(bytes32("globalDebtPercentage"), globalDebtPercentage);
emit ModifyParameters(bytes32("backupUpdateDelay"), backupUpdateDelay);
}
// --- Math ---
uint256 internal constant ONE = 1;
uint256 internal constant HOLDERS_ARRAY_LIMIT = 10;
uint256 internal constant HUNDRED = 100;
// --- Boolean Logic ---
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y)}
}
// --- Administration ---
/*
* @notify Modify a uint256 parameter
* @param parameter The name of the parameter to modify
* @param data The new parameter value
*/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "baseUpdateCallerReward") {
require(data <= maxUpdateCallerReward, "CollateralAuctionThrottler/invalid-min-reward");
baseUpdateCallerReward = data;
}
else if (parameter == "maxUpdateCallerReward") {
require(data >= baseUpdateCallerReward, "CollateralAuctionThrottler/invalid-max-reward");
maxUpdateCallerReward = data;
}
else if (parameter == "perSecondCallerRewardIncrease") {
require(data >= RAY, "CollateralAuctionThrottler/invalid-reward-increase");
perSecondCallerRewardIncrease = data;
}
else if (parameter == "maxRewardIncreaseDelay") {
require(data > 0, "CollateralAuctionThrottler/invalid-max-increase-delay");
maxRewardIncreaseDelay = data;
}
else if (parameter == "updateDelay") {
require(data > 0, "CollateralAuctionThrottler/null-update-delay");
updateDelay = data;
}
else if (parameter == "backupUpdateDelay") {
require(data > updateDelay, "CollateralAuctionThrottler/invalid-backup-update-delay");
backupUpdateDelay = data;
}
else if (parameter == "globalDebtPercentage") {
require(both(data > 0, data <= HUNDRED), "CollateralAuctionThrottler/invalid-global-debt-percentage");
globalDebtPercentage = data;
}
else if (parameter == "minAuctionLimit") {
minAuctionLimit = data;
}
else revert("CollateralAuctionThrottler/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/*
* @notify Modify the address of a contract param
* @param parameter The name of the parameter to change the address for
* @param addr The new address
*/
function modifyParameters(bytes32 parameter, address addr) external isAuthorized {
require(addr != address(0), "CollateralAuctionThrottler/null-addr");
if (parameter == "treasury") {
require(StabilityFeeTreasuryLike(addr).systemCoin() != address(0), "CollateralAuctionThrottler/treasury-coin-not-set");
treasury = StabilityFeeTreasuryLike(addr);
}
else if (parameter == "liquidationEngine") {
liquidationEngine = LiquidationEngineLike(addr);
}
else revert("CollateralAuctionThrottler/modify-unrecognized-param");
emit ModifyParameters(parameter, addr);
}
// --- Recompute Logic ---
/*
* @notify Recompute and set the new onAuctionSystemCoinLimit
* @param feeReceiver The address that will receive the reward for recomputing the onAuctionSystemCoinLimit
*/
function recomputeOnAuctionSystemCoinLimit(address feeReceiver) public {
// Check delay between calls
require(either(subtract(now, lastUpdateTime) >= updateDelay, lastUpdateTime == 0), "CollateralAuctionThrottler/wait-more");
// Get the caller's reward
uint256 callerReward = getCallerReward(lastUpdateTime, updateDelay);
// Store the timestamp of the update
lastUpdateTime = now;
// Compute total surplus
uint256 totalSurplus;
for (uint i = 0; i < surplusHolders.length; i++) {
totalSurplus = addition(totalSurplus, safeEngine.coinBalance(surplusHolders[i]));
}
// Remove surplus from global debt
uint256 rawGlobalDebt = subtract(safeEngine.globalDebt(), totalSurplus);
rawGlobalDebt = subtract(rawGlobalDebt, safeEngine.globalUnbackedDebt());
// Calculate and set the onAuctionSystemCoinLimit
uint256 newAuctionLimit = multiply(rawGlobalDebt / HUNDRED, globalDebtPercentage);
uint256 currentOnAuctionSystemCoins = liquidationEngine.currentOnAuctionSystemCoins();
newAuctionLimit = (newAuctionLimit <= minAuctionLimit) ? minAuctionLimit : newAuctionLimit;
newAuctionLimit = (newAuctionLimit == 0) ? uint(-1) : newAuctionLimit;
newAuctionLimit = (newAuctionLimit < currentOnAuctionSystemCoins) ? currentOnAuctionSystemCoins : newAuctionLimit;
liquidationEngine.modifyParameters("onAuctionSystemCoinLimit", newAuctionLimit);
// Pay the caller for updating the rate
rewardCaller(feeReceiver, callerReward);
}
/*
* @notify Backup function for recomputing the onAuctionSystemCoinLimit in case of a severe delay since the last update
*/
function backupRecomputeOnAuctionSystemCoinLimit() public {
// Check delay between calls
require(both(subtract(now, lastUpdateTime) >= backupUpdateDelay, lastUpdateTime > 0), "CollateralAuctionThrottler/wait-more");
// Store the timestamp of the update
lastUpdateTime = now;
// Set the onAuctionSystemCoinLimit
liquidationEngine.modifyParameters("onAuctionSystemCoinLimit", uint(-1));
}
}
|
@notify Modify the address of a contract param parameter The name of the parameter to change the address for addr The new address/
|
function modifyParameters(bytes32 parameter, address addr) external isAuthorized {
require(addr != address(0), "CollateralAuctionThrottler/null-addr");
if (parameter == "treasury") {
require(StabilityFeeTreasuryLike(addr).systemCoin() != address(0), "CollateralAuctionThrottler/treasury-coin-not-set");
treasury = StabilityFeeTreasuryLike(addr);
}
else if (parameter == "liquidationEngine") {
liquidationEngine = LiquidationEngineLike(addr);
}
else revert("CollateralAuctionThrottler/modify-unrecognized-param");
emit ModifyParameters(parameter, addr);
}
| 2,086,687 |
pragma solidity >=0.6.0 <0.8.0;
import '../proxy/OwnedUpgradeabilityProxy.sol';
import '../ownable/MultiOwnable.sol';
import '../../config/InternalSmartContractConfig.sol';
import '../basic/Address.sol';
import '../../wallet/UserWallet.sol';
contract UserWalletProxy is MultiOwnable{
using Address for address payable;
event DepositETH(address indexed sender, uint256 indexed amount);
event GasFeeTransferred(address indexed gasFeeWallet, uint256 indexed gasUsed, uint256 indexed gasFeeCollected);
event TopUpPaymentWalletFailed(address indexed destPaymentWallet, uint256 indexed gasUsed, uint256 indexed accountBalance, bytes revertReason);
event TransferRequestFailed(address indexed dest, uint256 indexed userGasUsed, uint256 indexed amount, string assetName, bytes revertReason);
event SubmitWithdrawFailed(address indexed dest, uint256 indexed userGasUsed, uint256 indexed amount, uint256 amountWithFee, string assetName, bytes revertReason);
bytes32 private constant userWalletImplPosition = keccak256("net.eurus.implementation");
uint256 private constant extraGasFee = 49000;
bytes32 private constant internalSCPosition = keccak256("network.eurus.internalSC");
function getInternalSCAddress() public view returns (address impl) {
bytes32 position = internalSCPosition;
assembly {
impl := sload(position)
}
}
/**
* @dev Tells the address of the current implementation
* @return impl address of the current implementation
*/
function getUserWalletImplementation() public view returns (address impl) {
bytes32 position = userWalletImplPosition;
assembly {
impl := sload(position)
}
}
/**
* @dev Sets the address of the current implementation
* @param newAddr address representing the new implementation to be set
*/
function setInternalSCAddress(address newAddr) public onlyOwner{
bytes32 position = internalSCPosition;
assembly {
sstore(position, newAddr)
}
}
/**
* @dev For backward competible
* @param newImplementation address representing the new implementation to be set
*/
function setUserWalletImplementation(address newImplementation) public onlyOwner{
bytes32 position = userWalletImplPosition;
assembly {
sstore(position, newImplementation)
}
}
function topUpPaymentWallet(address paymentWalletAddr, uint256 /*amount*/, bytes memory /*signature*/) public {
uint256 gasBegin = gasleft();
address internalSCAddr = getInternalSCAddress();
require(internalSCAddr != address(0), "InternalSCAddress is 0");
InternalSmartContractConfig internalSC = InternalSmartContractConfig(internalSCAddr);
address _impl = internalSC.getUserWalletAddress();
require(_impl != address(0), "UserWalletAddress is 0");
bytes memory ptr;
uint256 offset;
uint256 size;
uint256 result;
assembly {
ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
if gt (size, 0) {
offset := add(ptr, 0x120)
mstore(0x40, offset)
ptr := add(ptr, 4)
let lengthFieldLength := mload(ptr)
ptr := add(ptr, lengthFieldLength)
}
}
}
address payable gasFeeWallet = payable(internalSC.getGasFeeWalletAddress());
uint256 gasUsed = gasBegin - gasleft() + internalSC.getCentralizedGasFeeAdjustment();
gasFeeWallet.sendValue(gasUsed * tx.gasprice);
uint256 currBalance = payable(this).balance;
if (result == 0 ){
emit TopUpPaymentWalletFailed(paymentWalletAddr, gasUsed, currBalance, ptr);
} else {
emit GasFeeTransferred(gasFeeWallet, gasUsed, gasUsed * tx.gasprice);
assembly{
return (ptr, size)
}
}
}
fallback () external payable {
address internalSCAddr = getInternalSCAddress();
require(internalSCAddr != address(0), "InternalSCAddress is 0");
InternalSmartContractConfig internalSC = InternalSmartContractConfig(internalSCAddr);
address _impl = internalSC.getUserWalletAddress();
require(_impl != address(0), "UserWalletAddress is 0");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
receive() external payable {
if(msg.value>0){
emit DepositETH(msg.sender,msg.value);
}
}
function requestTransfer(address dest, string memory assetName, uint256 amount) public{
address internalSCAddr = getInternalSCAddress();
require(internalSCAddr != address(0), "InternalSCAddress is 0");
InternalSmartContractConfig internalSC = InternalSmartContractConfig(internalSCAddr);
address payable userWalletImpl = payable(internalSC.getUserWalletAddress());
require(userWalletImpl != address(0), "UserWalletAddress is 0");
(bool isSuccess, bytes memory data) = userWalletImpl.delegatecall(abi.encodeWithSignature("requestTransfer(address,string,uint256)",dest, assetName, amount));
require(isSuccess, string(data));
}
//For backward competible
function requestTransfer(address dest, string memory assetName, uint256 amount, bytes memory /*signature*/) public{
uint256 gasBegin = gasleft();
address _impl = getUserWalletImplementation();
require(_impl != address(0), "getUserWalletImplementation is 0");
bytes memory ptr;
uint256 offset;
assembly {
ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0{
if gt (size, 0) {
offset := add ( ptr, 0x120)
mstore(0x40, offset)
ptr := add(ptr, 4)
let lengthFieldLength := mload(ptr)
ptr := add(ptr, lengthFieldLength)
}
}
default{
return(ptr, size)
}
}
(bool isSuccess, bytes memory data) = _impl.delegatecall(abi.encodeWithSignature("getGasFeeWalletAddress()"));
if (!isSuccess){
revert('Unable to call getGetFeeWalletAddress');
}
address gasFeeAddress = bytesToAddress(data);
address payable gasFeeWallet = payable(gasFeeAddress);
uint256 gasUsed = gasBegin - gasleft() + extraGasFee;
gasFeeWallet.transfer(gasUsed * tx.gasprice);
emit TransferRequestFailed(dest, gasUsed, amount, assetName, ptr);
emit GasFeeTransferred(gasFeeWallet, gasUsed * tx.gasprice, gasUsed * tx.gasprice); //Event needs to forward competible, previous event only having wallet address and gas fee collected 2 args
}
function submitWithdraw(address dest, uint256 withdrawAmount, uint256 amountWithFee, string memory assetName) public {
address internalSCAddr = getInternalSCAddress();
require(internalSCAddr != address(0), "InternalSCAddress is 0");
InternalSmartContractConfig internalSC = InternalSmartContractConfig(internalSCAddr);
address payable userWalletImpl = payable(internalSC.getUserWalletAddress());
require(userWalletImpl != address(0), "UserWalletAddress is 0");
(bool isSuccess, bytes memory data) = userWalletImpl.delegatecall(abi.encodeWithSignature("submitWithdraw(address,uint256,uint256,string)",dest, withdrawAmount, amountWithFee, assetName));
require(isSuccess, string(data));
}
//For backward competible
function submitWithdraw(address dest, uint256 withdrawAmount, uint256 amountWithFee, string memory assetName, bytes memory /*signature*/) public{
uint256 gasBegin = gasleft();
address _impl = getUserWalletImplementation();
require(_impl != address(0), "getUserWalletImplementation is 0");
bytes memory ptr;
uint256 offset;
assembly {
ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0{
if gt (size, 0) {
offset := add(ptr, 0x120)
mstore(0x40, offset)
ptr := add(ptr, 4)
let lengthFieldLength := mload(ptr)
ptr := add(ptr, lengthFieldLength)
}
}
default{
return(ptr, size)
}
}
(bool isSuccess, bytes memory data) = _impl.delegatecall(abi.encodeWithSignature("getGasFeeWalletAddress()"));
if (!isSuccess){
revert('Unable to call getGetFeeWalletAddress');
}
address gasFeeAddress = bytesToAddress(data);
address payable gasFeeWallet = payable(gasFeeAddress);
uint256 gasUsed = gasBegin - gasleft() + extraGasFee;
gasFeeWallet.transfer(gasUsed * tx.gasprice);
emit SubmitWithdrawFailed(dest, gasUsed, withdrawAmount, amountWithFee, assetName, ptr);
emit GasFeeTransferred(gasFeeWallet, gasUsed * tx.gasprice, gasUsed * tx.gasprice); //Event needs to forward competible, previous event only having wallet address and gas fee collected 2 args
}
function bytesToAddress(bytes memory b) private pure returns (address addr){
assembly {
addr := mload(add(b, 32))
}
}
}
|
Sets the address of the current implementation newAddr address representing the new implementation to be set/
|
function setInternalSCAddress(address newAddr) public onlyOwner{
bytes32 position = internalSCPosition;
assembly {
sstore(position, newAddr)
}
}
| 5,402,387 |
/*
Copyright 2021 Pulsar Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { PPTypes } from "./PPTypes.sol";
import { BaseMath } from "../../lib/BaseMath.sol";
import { SafeCast } from "../../lib/SafeCast.sol";
import { SignedMath } from "../../lib/SignedMath.sol";
/**
* @title PPBalanceMath
* @author Pulsar
*
* @dev Library for manipulating PPTypes.Balance structs.
*/
library PPBalanceMath {
using BaseMath for uint256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedMath for SignedMath.Int;
using PPBalanceMath for PPTypes.Balance;
// ============ Constants ============
uint256 private constant FLAG_MARGIN_IS_POSITIVE = 1 << (8 * 31);
uint256 private constant FLAG_POSITION_IS_POSITIVE = 1 << (8 * 15);
// ============ Functions ============
/**
* @dev Create a copy of the balance struct.
*/
function copy(
PPTypes.Balance memory balance
)
internal
pure
returns (PPTypes.Balance memory)
{
return PPTypes.Balance({
marginIsPositive: balance.marginIsPositive,
positionIsPositive: balance.positionIsPositive,
margin: balance.margin,
position: balance.position
});
}
/**
* @dev In-place add amount to balance.margin.
*/
function addToMargin(
PPTypes.Balance memory balance,
uint256 amount
)
internal
pure
{
SignedMath.Int memory signedMargin = balance.getMargin();
signedMargin = signedMargin.add(amount);
balance.setMargin(signedMargin);
}
/**
* @dev In-place subtract amount from balance.margin.
*/
function subFromMargin(
PPTypes.Balance memory balance,
uint256 amount
)
internal
pure
{
SignedMath.Int memory signedMargin = balance.getMargin();
signedMargin = signedMargin.sub(amount);
balance.setMargin(signedMargin);
}
/**
* @dev In-place add amount to balance.position.
*/
function addToPosition(
PPTypes.Balance memory balance,
uint256 amount
)
internal
pure
{
SignedMath.Int memory signedPosition = balance.getPosition();
signedPosition = signedPosition.add(amount);
balance.setPosition(signedPosition);
}
/**
* @dev In-place subtract amount from balance.position.
*/
function subFromPosition(
PPTypes.Balance memory balance,
uint256 amount
)
internal
pure
{
SignedMath.Int memory signedPosition = balance.getPosition();
signedPosition = signedPosition.sub(amount);
balance.setPosition(signedPosition);
}
/**
* @dev Returns the positive and negative values of the margin and position together, given a
* price, which is used as a conversion rate between the two currencies.
*
* No rounding occurs here--the returned values are "base values" with extra precision.
*/
function getPositiveAndNegativeValue(
PPTypes.Balance memory balance,
uint256 price
)
internal
pure
returns (uint256, uint256)
{
uint256 positiveValue = 0;
uint256 negativeValue = 0;
// add value of margin
if (balance.marginIsPositive) {
positiveValue = uint256(balance.margin).mul(BaseMath.base());
} else {
negativeValue = uint256(balance.margin).mul(BaseMath.base());
}
// add value of position
uint256 positionValue = uint256(balance.position).mul(price);
if (balance.positionIsPositive) {
positiveValue = positiveValue.add(positionValue);
} else {
negativeValue = negativeValue.add(positionValue);
}
return (positiveValue, negativeValue);
}
/**
* @dev Returns a compressed bytes32 representation of the balance for logging.
*/
function toBytes32(
PPTypes.Balance memory balance
)
internal
pure
returns (bytes32)
{
uint256 result =
uint256(balance.position)
| (uint256(balance.margin) << 128)
| (balance.marginIsPositive ? FLAG_MARGIN_IS_POSITIVE : 0)
| (balance.positionIsPositive ? FLAG_POSITION_IS_POSITIVE : 0);
return bytes32(result);
}
// ============ Helper Functions ============
/**
* @dev Returns a SignedMath.Int version of the margin in balance.
*/
function getMargin(
PPTypes.Balance memory balance
)
internal
pure
returns (SignedMath.Int memory)
{
return SignedMath.Int({
value: balance.margin,
isPositive: balance.marginIsPositive
});
}
/**
* @dev Returns a SignedMath.Int version of the position in balance.
*/
function getPosition(
PPTypes.Balance memory balance
)
internal
pure
returns (SignedMath.Int memory)
{
return SignedMath.Int({
value: balance.position,
isPositive: balance.positionIsPositive
});
}
/**
* @dev In-place modify the signed margin value of a balance.
*/
function setMargin(
PPTypes.Balance memory balance,
SignedMath.Int memory newMargin
)
internal
pure
{
balance.margin = newMargin.value.toUint120();
balance.marginIsPositive = newMargin.isPositive;
}
/**
* @dev In-place modify the signed position value of a balance.
*/
function setPosition(
PPTypes.Balance memory balance,
SignedMath.Int memory newPosition
)
internal
pure
{
balance.position = newPosition.value.toUint120();
balance.positionIsPositive = newPosition.isPositive;
}
}
|
In-place subtract amount from balance.position./
|
function subFromPosition(
PPTypes.Balance memory balance,
uint256 amount
)
internal
pure
{
SignedMath.Int memory signedPosition = balance.getPosition();
signedPosition = signedPosition.sub(amount);
balance.setPosition(signedPosition);
}
| 5,400,831 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./IERC721LibBeforeTokenTransferHook.sol";
/* Functionality used to whitelist OpenSea trading address, if desired */
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, the Enumerable extension, and Pausable.
*
* Closely based on and mirrors the excellent https://openzeppelin.com/contracts/.
*/
library ERC721Lib {
using Address for address;
using Strings for uint256;
/**
* @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 Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
struct ERC721Storage {
// Token name
string _name;
// Token symbol
string _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) _owners;
// Mapping owner address to token count
mapping (address => uint256) _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) _operatorApprovals;
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) _allTokensIndex;
// Base URI
string _baseURI;
// True if token transfers are paused
bool _paused;
// Hook function that can be called before token is transferred, along with a pointer to its storage struct
IERC721LibBeforeTokenTransferHook _beforeTokenTransferHookInterface;
bytes32 _beforeTokenTransferHookStorageSlot;
address proxyRegistryAddress;
}
function init(ERC721Storage storage s, string memory _name, string memory _symbol) external {
s._name = _name;
s._symbol = _symbol;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) external pure returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| interfaceId == type(IERC721Enumerable).interfaceId;
}
//
// Start of ERC721 functions
//
/**
* @dev See {IERC721-balanceOf}.
*/
function _balanceOf(ERC721Storage storage s, address owner) internal view returns (uint256) {
require(owner != address(0), "Balance query for address zero");
return s._balances[owner];
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(ERC721Storage storage s, address owner) external view returns (uint256) {
return _balanceOf(s, owner);
}
/**
* @dev See {IERC721-ownerOf}.
*/
function _ownerOf(ERC721Storage storage s, uint256 tokenId) internal view returns (address) {
address owner = s._owners[tokenId];
require(owner != address(0), "Owner query for nonexist. token");
return owner;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(ERC721Storage storage s, uint256 tokenId) external view returns (address) {
return _ownerOf(s, tokenId);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name(ERC721Storage storage s) external view returns (string memory) {
return s._name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol(ERC721Storage storage s) external view returns (string memory) {
return s._symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(ERC721Storage storage s, uint256 tokenId) external view returns (string memory) {
require(_exists(s, tokenId), "URI query for nonexistent token");
return bytes(s._baseURI).length > 0
? string(abi.encodePacked(s._baseURI, tokenId.toString()))
: "";
}
/**
* @dev Set base URI
*/
function setBaseURI(ERC721Storage storage s, string memory baseTokenURI) external {
s._baseURI = baseTokenURI;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(ERC721Storage storage s, address to, uint256 tokenId) external {
address owner = _ownerOf(s, tokenId);
require(to != owner, "Approval to current owner");
require(msg.sender == owner || _isApprovedForAll(s, owner, msg.sender),
"Not owner nor approved for all"
);
_approve(s, to, tokenId);
}
/**
* @dev Approve independently of who's the owner
*
* Obviously expose with care...
*/
function overrideApprove(ERC721Storage storage s, address to, uint256 tokenId) external {
_approve(s, to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function _getApproved(ERC721Storage storage s, uint256 tokenId) internal view returns (address) {
require(_exists(s, tokenId), "Approved query nonexist. token");
return s._tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(ERC721Storage storage s, uint256 tokenId) external view returns (address) {
return _getApproved(s, tokenId);
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(ERC721Storage storage s, address operator, bool approved) external {
require(operator != msg.sender, "Attempted approve to caller");
s._operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function _isApprovedForAll(ERC721Storage storage s, address owner, address operator) internal view returns (bool) {
// Whitelist OpenSea proxy contract for easy trading - if we have a valid proxy registry address on file
if (s.proxyRegistryAddress != address(0)) {
ProxyRegistry proxyRegistry = ProxyRegistry(s.proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
}
return s._operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(ERC721Storage storage s, address owner, address operator) external view returns (bool) {
return _isApprovedForAll(s, owner, operator);
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved");
_transfer(s, from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external {
_safeTransferFrom(s, from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function _safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal {
require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved");
_safeTransfer(s, from, to, tokenId, _data);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external {
_safeTransferFrom(s, 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(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal {
_transfer(s, from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "Transfer to non ERC721Receiver");
}
/**
* @dev directSafeTransfer
*
* CAREFUL, this does not verify the previous ownership - only use if ownership/eligibility has been asserted by other means
*/
function directSafeTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external {
_safeTransfer(s, from, to, tokenId, _data);
}
/**
* @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(ERC721Storage storage s, uint256 tokenId) internal view returns (bool) {
return s._owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(ERC721Storage storage s, address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(s, tokenId), "Operator query nonexist. token");
address owner = _ownerOf(s, tokenId);
return (spender == owner || _getApproved(s, tokenId) == spender || _isApprovedForAll(s, 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(ERC721Storage storage s, address to, uint256 tokenId) internal {
_safeMint(s, 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(ERC721Storage storage s, address to, uint256 tokenId, bytes memory _data) internal {
_unsafeMint(s, to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "Transfer to non ERC721Receiver");
}
/**
* @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 _unsafeMint(ERC721Storage storage s, address to, uint256 tokenId) internal {
require(to != address(0), "Mint to the zero address");
require(!_exists(s, tokenId), "Token already minted");
_beforeTokenTransfer(s, address(0), to, tokenId);
s._balances[to] += 1;
s._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(ERC721Storage storage s, uint256 tokenId) internal {
address owner = _ownerOf(s, tokenId);
_beforeTokenTransfer(s, owner, address(0), tokenId);
// Clear approvals
_approve(s, address(0), tokenId);
s._balances[owner] -= 1;
delete s._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(ERC721Storage storage s, address from, address to, uint256 tokenId) internal {
require(_ownerOf(s, tokenId) == from, "TransferFrom not owner/approved");
require(to != address(0), "Transfer to the zero address");
_beforeTokenTransfer(s, from, to, tokenId);
// Clear approvals from the previous owner
_approve(s, address(0), tokenId);
s._balances[from] -= 1;
s._balances[to] += 1;
s._owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(ERC721Storage storage s, address to, uint256 tokenId) internal {
s._tokenApprovals[tokenId] = to;
emit Approval(_ownerOf(s, 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("Transfer to non ERC721Receiver");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
//
// Start of functions from ERC721Enumerable
//
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(ERC721Storage storage s, address owner, uint256 index) external view returns (uint256) {
require(index < _balanceOf(s, owner), "Owner index out of bounds");
return s._ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function _totalSupply(ERC721Storage storage s) internal view returns (uint256) {
return s._allTokens.length;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply(ERC721Storage storage s) external view returns (uint256) {
return s._allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(ERC721Storage storage s, uint256 index) external view returns (uint256) {
require(index < _totalSupply(s), "Global index out of bounds");
return s._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(ERC721Storage storage s, address from, address to, uint256 tokenId) internal {
if(address(s._beforeTokenTransferHookInterface) != address(0)) {
// We have a hook that we need to delegate call
(bool success, ) = address(s._beforeTokenTransferHookInterface).delegatecall(
abi.encodeWithSelector(s._beforeTokenTransferHookInterface._beforeTokenTransferHook.selector, s._beforeTokenTransferHookStorageSlot, from, to, tokenId)
);
if(!success) {
// Bubble up the revert message
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
}
require(!_paused(s), "No token transfer while paused");
if (from == address(0)) {
_addTokenToAllTokensEnumeration(s, tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(s, from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(s, tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(s, 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(ERC721Storage storage s, address to, uint256 tokenId) private {
uint256 length = _balanceOf(s, to);
s._ownedTokens[to][length] = tokenId;
s._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(ERC721Storage storage s, uint256 tokenId) private {
s._allTokensIndex[tokenId] = s._allTokens.length;
s._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(ERC721Storage storage s, 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 = _balanceOf(s, from) - 1;
uint256 tokenIndex = s._ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = s._ownedTokens[from][lastTokenIndex];
s._ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
s._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete s._ownedTokensIndex[tokenId];
delete s._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(ERC721Storage storage s, 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 = s._allTokens.length - 1;
uint256 tokenIndex = s._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 = s._allTokens[lastTokenIndex];
s._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
s._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete s._allTokensIndex[tokenId];
s._allTokens.pop();
}
//
// Start of functions from Pausable
//
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function _paused(ERC721Storage storage s) internal view returns (bool) {
return s._paused;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused(ERC721Storage storage s) external view returns (bool) {
return s._paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused(ERC721Storage storage s) {
require(!_paused(s), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused(ERC721Storage storage s) {
require(_paused(s), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause(ERC721Storage storage s) external whenNotPaused(s) {
s._paused = true;
emit Paused(msg.sender);
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause(ERC721Storage storage s) external whenPaused(s) {
s._paused = false;
emit Unpaused(msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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.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;
import "./ERC721Lib.sol";
/**
* @dev Interface that can be used to hook additional beforeTokenTransfer functions into ERC721Lib
*/
interface IERC721LibBeforeTokenTransferHook {
/**
* @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 _beforeTokenTransferHook(bytes32 storagePosition, address from, address to, uint256 tokenId) external;
}
// 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);
}
|
Private function to add a token to this extension's ownership-tracking data structures. to address representing the new owner of the given token ID tokenId uint256 ID of the token to be added to the tokens list of the given address/
|
function _addTokenToOwnerEnumeration(ERC721Storage storage s, address to, uint256 tokenId) private {
uint256 length = _balanceOf(s, to);
s._ownedTokens[to][length] = tokenId;
s._ownedTokensIndex[tokenId] = length;
}
| 6,935,810 |
/**
*Submitted for verification at Etherscan.io on 2022-03-17
*/
// SPDX-License-Identifier: UNLICENSED
// File: contracts/abstract/OwnableDelegateProxy.sol
pragma solidity 0.8.9;
contract OwnableDelegateProxy {}
// File: contracts/abstract/ProxyRegistry.sol
pragma solidity 0.8.9;
// Part: ProxyRegistry
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// File: contracts/abstract/IERC1155TokenReceiver.sol
pragma solidity 0.8.9;
/**
* @dev ERC-1155 interface for accepting safe transfers.
*/
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
)
external returns (
bytes4
)
;
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
)
external returns (
bytes4
)
;
/**
* @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types.
* @param interfaceID The ERC-165 interface ID that is queried for support.s
* @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface.
* This function MUST NOT consume more than 5,000 gas.
* @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported.
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// File: contracts/abstract/ERC1155Metadata.sol
pragma solidity 0.8.9;
/**
* @notice Contract that handles metadata related methods.
* @dev Methods assume a deterministic generation of URI based on token IDs.
* Methods also assume that URI uses hex representation of token IDs.
*/
abstract contract ERC1155Metadata {
/***********************************|
* | Metadata Public Function s |
|__________________________________*/
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* Token IDs are assumed to be represented in their hex format in URIs
* @return URI string
*/
function uri(uint256 _id) external view virtual returns (string memory);
}
// File: contracts/abstract/IERC1155.sol
pragma solidity 0.8.9;
interface IERC1155 {
// Events
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _amount);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _amounts);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(address indexed _owner,
address indexed _operator,
bool _approved);
/**
* @dev MUST emit when the URI is updated for a token ID
* URIs are defined in RFC 3986
* The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema"
*/
event URI(string _uri, uint256 indexed _id);
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes calldata _data
)
external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
)
external;
/**
* @notice Get the balance of an account's Tokens
* @param _owner 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 _owner, uint256 _id) external view
returns (uint256);
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners 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[] calldata _owners,
uint256[] calldata _ids
)
external
view
returns (
uint256[] memory
)
;
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of 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) external;
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator True if the operator is approved, false if not
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (
bool isOperator
)
;
}
// File: contracts/abstract/IERC165.sol
pragma solidity 0.8.9;
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas
* @param _interfaceId The interface identifier, as specified in ERC-165
*/
function supportsInterface(bytes4 _interfaceId) external view
returns (bool);
}
// File: contracts/abstract/Address.sol
pragma solidity 0.8.9;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/abstract/Roles.sol
pragma solidity 0.8.9;
/**
* @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(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
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), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: contracts/abstract/Context.sol
pragma solidity 0.8.9;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: contracts/abstract/Ownable.sol
pragma solidity 0.8.9;
// Part: OpenZeppelin/[email protected]/Ownable
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
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 returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/abstract/MinterRole.sol
pragma solidity 0.8.9;
/**
* @title MinterRole
* @dev Owner is responsible to add/remove minter
*/
contract MinterRole is Context, Ownable {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
modifier onlyMinter() {
require(
isMinter(_msgSender()),
"MinterRole: caller does not have the Minter role"
);
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyOwner {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: contracts/abstract/SafeMath.sol
pragma solidity 0.8.9;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/abstract/ERC1155.sol
pragma solidity 0.8.9;
/**
* @dev Implementation of Multi-Token Standard contract
*/
abstract contract ERC1155 is IERC1155, IERC165, ERC1155Metadata {
using SafeMath for uint256;
using Address for address;
/***********************************|
* | Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 internal constant ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 internal constant ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping(address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping(address => mapping(address => bool)) internal operators;
/***********************************|
* | Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
)
public override virtual {
require((
msg.sender == _from
)
|| _isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
)
public override virtual {
// Requirements
require((
msg.sender == _from
)
|| _isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
* | Internal Transfer Functions |
|__________________________________*/
/**
* @dev Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount
)
internal {
// Update balances
balances[_from][_id] = balances[_from][_id].sub (
_amount
)
; // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @dev Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
)
internal {
if (_to.isContract()) {
try IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data) returns (bytes4 response) {
if (response != ERC1155_RECEIVED_VALUE) {
revert("ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155#_callonERC1155Received: transfer to non ERC1155Receiver implementer");
}
}
}
/**
* @dev Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _amounts
)
internal {
require (
_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"
)
;
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer;i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @dev Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
)
internal {
// Check if recipient is contract
if (_to.isContract()
) {
try IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data) returns (bytes4 response) {
if (response != ERC1155_BATCH_RECEIVED_VALUE) {
revert("ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155#_callonERC1155BatchReceived: transfer to non ERC1155Receiver implementer");
}
}
}
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external override {
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator true if the operator is approved, false if not
*/
function _isApprovedForAll(
address _owner,
address _operator
)
internal
view
returns (bool isOperator) {
return operators[_owner][_operator];
}
/**
* @notice Get the balance of an account's Tokens
* @param _owner 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 _owner, uint256 _id) override public view returns (uint256) {
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners 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 _owners, uint256[] memory _ids)
override
public
view
returns (uint256[] memory) {
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length;i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/*
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 private constant INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/*
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 private constant INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) override external pure returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
// File: contracts/abstract/ERC1155MintBurn.sol
pragma solidity 0.8.9;
/**
* @dev Multi-Fungible Tokens with minting and burning methods. These methods assume
* a parent contract to be executed as they are `internal` functions
*/
abstract contract ERC1155MintBurn is ERC1155 {
using SafeMath for uint256;
/****************************************|
* | Minting Functions |
|_______________________________________*/
/**
* @dev Mint _amount of tokens of a given id
* @param _to The address to mint tokens to
* @param _id Token id to mint
* @param _amount The amount to be minted
* @param _data Data to pass if receiver is contract
*/
function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal {
// Add _amount
balances[_to][_id] = balances[_to][_id].add(_amount);
// Emit event
emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount);
// Calling onReceive method if recipient is contract
_callonERC1155Received(address(0x0), _to, _id, _amount, _data);
}
/**
* @dev Mint tokens for each ids in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _amounts Array of amount of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function _batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
)
internal {
require (
_ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH"
)
;
// Number of mints to execute
uint256 nMint = _ids.length;
// Executing all minting
for (uint256 i = 0; i < nMint;i++) {
// Update storage balance
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit batch mint event
emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts);
// Calling onReceive method if recipient is contract
_callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, _data);
}
/****************************************|
* | Burning Functions |
|_______________________________________*/
/**
* @dev Burn _amount of tokens of a given token id
* @param _from The address to burn tokens from
* @param _id Token id to burn
* @param _amount The amount to be burned
*/
function _burn(address _from, uint256 _id,
uint256 _amount) internal {
// Substract _amount
balances[_from][_id] = balances[_from][_id].sub(_amount);
// Emit event
emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount);
}
/**
* @dev Burn tokens of given token id for each (_ids[i], _amounts[i]) pair
* @param _from The address to burn tokens from
* @param _ids Array of token ids to burn
* @param _amounts Array of the amount to be burned
*/
function _batchBurn(
address _from,
uint256[] memory _ids,
uint256[] memory _amounts
)
internal {
require (
_ids.length == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH"
)
;
// Number of mints to execute
uint256 nBurn = _ids.length;
// Executing all minting
for (uint256 i = 0; i < nBurn;i++) {
// Update storage balance
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
}
// Emit batch mint event
emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts);
}
}
// File: contracts/abstract/ERC1155Tradable.sol
pragma solidity 0.8.9;
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address,
* has create and mint functionality, and supports useful standards from OpenZeppelin,
* like _exists(), name(), symbol(), and totalSupply()
*/
abstract contract ERC1155Tradable is ERC1155MintBurn, Ownable, MinterRole {
using SafeMath for uint256;
using Address for address;
// OpenSea proxy registry to ease selling NFTs on OpenSea
address public proxyRegistryAddress;
mapping(uint256 => address) public creators;
mapping(uint256 => uint256) public tokenSupply;
mapping(uint256 => uint256) public tokenMaxSupply;
mapping(uint256 => uint8) public tokenCityIndex;
mapping(uint256 => uint8) public tokenType;
// Contract name
string public name;
// Contract symbol
string public symbol;
// URI's default URI prefix
string internal baseMetadataURI;
uint256 internal _currentTokenID = 0;
constructor (string memory _name, string memory _symbol, address _proxyRegistryAddress, string memory _baseMetadataURI) {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
baseMetadataURI = _baseMetadataURI;
}
function contractURI() public view returns (string memory) {
return string(abi.encodePacked(baseMetadataURI));
}
/**
* @dev Returns URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* Token IDs are assumed to be represented in their hex format in URIs
* @return URI string
*/
function uri(uint256 _id) override external view returns (string memory) {
require(_exists(_id), "Deed NFT doesn't exists");
return string(abi.encodePacked(baseMetadataURI, _uint2str(_id)));
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Returns the max quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function maxSupply(uint256 _id) public view returns (uint256) {
return tokenMaxSupply[_id];
}
/**
* @dev return city index of designated NFT with its identifier
*/
function cityIndex(uint256 _id) public view returns (uint256) {
require(_exists(_id), "Deed NFT doesn't exists");
return tokenCityIndex[_id];
}
/**
* @dev return card type of designated NFT with its identifier
*/
function cardType(uint256 _id) public view returns (uint256) {
require(_exists(_id), "Deed NFT doesn't exists");
return tokenType[_id];
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* @param _initialOwner the first owner of the Token
* @param _initialSupply Optional amount to supply the first owner (1 for NFT)
* @param _maxSupply max supply allowed (1 for NFT)
* @param _cityIndex city index of NFT
* (0 = Tanit, 1 = Reshef, 2 = Ashtarte, 3 = Melqart, 4 = Eshmun, 5 = Kushor, 6 = Hammon)
* @param _type card type of NFT
* (0 = Common, 1 = Uncommon, 2 = Rare, 3 = Legendary)
* @param _data Optional data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
uint256 _maxSupply,
uint8 _cityIndex,
uint8 _type,
bytes memory _data
) public onlyMinter returns (uint256) {
require(_initialSupply <= _maxSupply, "_initialSupply > _maxSupply");
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = _initialOwner;
if (_initialSupply != 0) {
_mint(_initialOwner, _id, _initialSupply, _data);
}
tokenSupply[_id] = _initialSupply;
tokenMaxSupply[_id] = _maxSupply;
tokenCityIndex[_id] = _cityIndex;
tokenType[_id] = _type;
return _id;
}
/**
* @dev Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator true if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) override public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return _isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
/**
* @dev Convert uint256 to string
* @param _i Unsigned integer to convert to string
*/
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] = bytes1(uint8(48 + _i % 10));
_i /= 10;
if (k > 0) {
k--;
}
}
return string(bstr);
}
}
// File: contracts/abstract/ManagerRole.sol
pragma solidity 0.8.9;
/**
* @title ManagerRole
* @dev Owner is responsible to add/remove manager
*/
contract ManagerRole is Context, Ownable {
using Roles for Roles.Role;
event ManagerAdded(address indexed account);
event ManagerRemoved(address indexed account);
Roles.Role private _managers;
modifier onlyManager() {
require(isManager(_msgSender()), "ManagerRole: caller does not have the Manager role");
_;
}
function isManager(address account) public view returns (bool) {
return _managers.has(account);
}
function addManager(address account) public onlyOwner {
_addManager(account);
}
function removeManager(address account) public onlyOwner {
_removeManager(account);
}
function _addManager(address account) internal {
_managers.add(account);
emit ManagerAdded(account);
}
function _removeManager(address account) internal {
_managers.remove(account);
emit ManagerRemoved(account);
}
}
// File: contracts/abstract/StrategyRole.sol
pragma solidity 0.8.9;
/**
* @title StrategyRole
* @dev Owner is responsible to add/remove strategy
*/
contract StrategyRole is Context, ManagerRole {
using Roles for Roles.Role;
event StrategyAdded(address indexed account);
event StrategyRemoved(address indexed account);
Roles.Role private _strategies;
modifier onlyStrategy() {
require(isStrategy(_msgSender()), "StrategyRole: caller does not have the Strategy role");
_;
}
function isStrategy(address account) public view returns (bool) {
return _strategies.has(account);
}
function addStrategy(address account) public onlyManager {
_addStrategy(account);
}
function removeStrategy(address account) public onlyManager {
_removeStrategy(account);
}
function _addStrategy(address account) internal {
_strategies.add(account);
emit StrategyAdded(account);
}
function _removeStrategy(address account) internal {
_strategies.remove(account);
emit StrategyRemoved(account);
}
}
// File: contracts/abstract/StrategyHandler.sol
pragma solidity 0.8.9;
/**
* @title NFT Contract for Meeds DAO
*/
interface StrategyHandler is IERC1155 {
/**
* @dev return the total use count of an NFT by a wallet
*/
function getTotalUseCount(address _account, uint256 _id) external view returns (uint256);
/**
* @dev return the use count of an NFT by wallet inside a strategy
*/
function getStrategyUseCount(address _account, uint256 _id, address _strategy) external view returns (uint256);
/**
* @notice Mark NFT as being used. Only callable by registered strategies
* @param _account User account address
* @param _id ID of the token type
*/
function startUsingNFT(address _account, uint256 _id) external returns (bool);
/**
* @notice Unmark NFT as being used. Only callable by registered strategies
* @param _account User account address
* @param _id ID of the token type
*/
function endUsingNFT(address _account, uint256 _id) external returns (bool);
}
// File: contracts/Deed.sol
pragma solidity 0.8.9;
/**
* @title NFT Contract for Meeds DAO
*/
contract Deed is ERC1155Tradable, StrategyHandler, StrategyRole {
using SafeMath for uint256;
event StartedUsingNFT(address indexed account,
uint256 indexed id,
address indexed strategy);
event EndedUsingNFT(address indexed account,
uint256 indexed id,
address indexed strategy);
// mapping account => nftId => useCount
// this is used to restrict transfers if nft is being used in any strategy
mapping(address => mapping(uint256 => uint256)) internal totalUseCount;
// mapping account => nftId => strategyAddress => useCount
// this is used to make sure a strategy can only end using nft that it started using before
mapping(address => mapping(uint256 => mapping(address => uint256)))
internal stratUseCount;
constructor (address _proxyRegistryAddress, string memory _baseMetadataURI) ERC1155Tradable("Meeds Deed Token", "DEED", _proxyRegistryAddress, _baseMetadataURI) {
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyManager {
baseMetadataURI = _newBaseMetadataURI;
}
/**
* @dev return the list of NFTs owned by an address
*/
function nftsOf(address _account) public view returns (uint256[] memory) {
uint256 len = 0;
for (uint256 i = 1; i <= _currentTokenID; i++) {
if (balances[_account][i] > 0) {
len++;
}
}
uint256 index = 0;
uint256[] memory nfts = new uint256[](len);
for (uint256 i = 1; i <= _currentTokenID; i++) {
if (balances[_account][i] > 0) {
nfts[index++] = i;
}
}
return nfts;
}
/**
* @dev return the total supply of NFTs (Token Types)
*/
function totalSupply() public view returns (uint256) {
return _currentTokenID;
}
/**
* @dev return the total use count of an NFT by owner
*/
function getTotalUseCount(address _account, uint256 _id) external view returns (uint256) {
return totalUseCount[_account][_id];
}
/**
* @dev return the use count of an NFT by wallet inside a strategy
*/
function getStrategyUseCount(address _account, uint256 _id, address _strategy) external view returns (uint256) {
return stratUseCount[_account][_id][_strategy];
}
/**
* @notice Mark NFT as being used. Only callable by registered strategies
* @param _account User account address
* @param _id ID of the token type
*/
function startUsingNFT(address _account, uint256 _id) external onlyStrategy returns (bool) {
require(balances[_account][_id] > 0, "Deed#startUsingNFT: user account doesn't own the NFT");
stratUseCount[_account][_id][msg.sender] = stratUseCount[_account][_id][msg.sender].add(1);
totalUseCount[_account][_id] = totalUseCount[_account][_id].add(1);
emit StartedUsingNFT(_account, _id, msg.sender);
return true;
}
/**
* @notice Unmark NFT as being used. Only callable by registered strategies
* @param _account User account address
* @param _id ID of the token type
*/
function endUsingNFT(address _account, uint256 _id) external onlyStrategy returns (bool) {
require(stratUseCount[_account][_id][msg.sender] > 0, "Deed#endUsingNFT: NFT is not currently in use by strategy");
stratUseCount[_account][_id][msg.sender] = stratUseCount[_account][_id][msg.sender].sub(1);
totalUseCount[_account][_id] = totalUseCount[_account][_id].sub(1);
emit EndedUsingNFT(_account, _id, msg.sender);
return true;
}
/**
* @dev Overrides safeTransferFrom function of ERC1155 to introduce totalUseCount check
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override (ERC1155, IERC1155) {
require(totalUseCount[_from][_id] == 0, "Deed#safeTransferFrom: NFT being used in strategy");
ERC1155.safeTransferFrom(_from, _to, _id, _amount, _data);
}
/**
* @dev Overrides safeBatchTransferFrom function of ERC1155 to introduce totalUseCount check
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public override (ERC1155, IERC1155) {
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// check if any nft is being used
for (uint256 i = 0; i < nTransfer; i++) {
require(totalUseCount[_from][_ids[i]] == 0, "Deed#safeBatchTransferFrom: NFT being used in strategy");
}
ERC1155.safeBatchTransferFrom(_from, _to, _ids, _amounts, _data);
}
}
|
| | Minting Functions | Mint _amount of tokens of a given id _to The address to mint tokens to _id Token id to mint _amount The amount to be minted _data Data to pass if receiver is contract/ Add _amount Emit event Calling onReceive method if recipient is contract
|
function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal {
balances[_to][_id] = balances[_to][_id].add(_amount);
emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount);
_callonERC1155Received(address(0x0), _to, _id, _amount, _data);
}
| 7,635,448 |
./full_match/1/0x1125b6816CFF259dA3Af6a5aBaF804Bc28e660B6/sources/contracts/MathGold.sol
|
Allows the DAO to set the season and Math Gold per token ID in one transaction. This ensures that there is not a gap where a user can claim more Math Gold than others season_ The season to use for claiming loot mathGoldDisplayValue The amount of Math a user can claim. This should be input as the display value, not in raw decimals. If you want to mint 100 Math, you should enter "100" rather than the value of 100 10^18. We would save a tiny amount of gas by modifying the season and mathGold variables directly. It is better practice for security, however, to avoid repeating code. This function is so rarely used that it's not worth moving these values into their own internal function to skip the gas used on the modifier check.
|
function daoSetSeasonAndMathGoldPerTokenID(
uint256 season_,
uint256 mathGoldDisplayValue
) external onlyOwner {
daoSetSeason(season_);
daoSetMathGoldPerTokenId(mathGoldDisplayValue);
}
| 16,540,561 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "./UbiquityAlgorithmicDollarManager.sol";
import "./interfaces/IDollarMintingCalculator.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./TWAPOracle.sol";
import "./libs/ABDKMathQuad.sol";
/// @title A mock coupon calculator that always returns a constant
contract DollarMintingCalculator is IDollarMintingCalculator {
using ABDKMathQuad for uint256;
using ABDKMathQuad for bytes16;
bytes16 private immutable _one = (uint256(1 ether)).fromUInt();
UbiquityAlgorithmicDollarManager public manager;
/// @param _manager the address of the manager contract so we can fetch variables
constructor(address _manager) {
manager = UbiquityAlgorithmicDollarManager(_manager);
}
/// @notice returns (TWAP_PRICE -1) * UAD_Total_Supply
function getDollarsToMint() external view override returns (uint256) {
TWAPOracle oracle = TWAPOracle(manager.twapOracleAddress());
uint256 twapPrice = oracle.consult(manager.dollarTokenAddress());
require(twapPrice > 1, "DollarMintingCalculator: not > 1");
return
twapPrice
.fromUInt()
.sub(_one)
.mul(
(
IERC20(manager.dollarTokenAddress())
.totalSupply()
.fromUInt()
.div(_one)
)
)
.toUInt();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IUbiquityAlgorithmicDollar.sol";
import "./interfaces/ICurveFactory.sol";
import "./interfaces/IMetaPool.sol";
import "./TWAPOracle.sol";
/// @title A central config for the uAD system. Also acts as a central
/// access control manager.
/// @notice For storing constants. For storing variables and allowing them to
/// be changed by the admin (governance)
/// @dev This should be used as a central access control manager which other
/// contracts use to check permissions
contract UbiquityAlgorithmicDollarManager is AccessControl {
using SafeERC20 for IERC20;
bytes32 public constant UBQ_MINTER_ROLE = keccak256("UBQ_MINTER_ROLE");
bytes32 public constant UBQ_BURNER_ROLE = keccak256("UBQ_BURNER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant COUPON_MANAGER_ROLE = keccak256("COUPON_MANAGER");
bytes32 public constant BONDING_MANAGER_ROLE = keccak256("BONDING_MANAGER");
bytes32 public constant INCENTIVE_MANAGER_ROLE =
keccak256("INCENTIVE_MANAGER");
bytes32 public constant UBQ_TOKEN_MANAGER_ROLE =
keccak256("UBQ_TOKEN_MANAGER_ROLE");
address public twapOracleAddress;
address public debtCouponAddress;
address public dollarTokenAddress; // uAD
address public couponCalculatorAddress;
address public dollarMintingCalculatorAddress;
address public bondingShareAddress;
address public bondingContractAddress;
address public stableSwapMetaPoolAddress;
address public curve3PoolTokenAddress; // 3CRV
address public treasuryAddress;
address public governanceTokenAddress; // uGOV
address public sushiSwapPoolAddress; // sushi pool uAD-uGOV
address public masterChefAddress;
address public formulasAddress;
address public autoRedeemTokenAddress; // uAR
address public uarCalculatorAddress; // uAR calculator
//key = address of couponmanager, value = excessdollardistributor
mapping(address => address) private _excessDollarDistributors;
modifier onlyAdmin() {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"uADMGR: Caller is not admin"
);
_;
}
constructor(address _admin) {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(UBQ_MINTER_ROLE, _admin);
_setupRole(PAUSER_ROLE, _admin);
_setupRole(COUPON_MANAGER_ROLE, _admin);
_setupRole(BONDING_MANAGER_ROLE, _admin);
_setupRole(INCENTIVE_MANAGER_ROLE, _admin);
_setupRole(UBQ_TOKEN_MANAGER_ROLE, address(this));
}
// TODO Add a generic setter for extra addresses that needs to be linked
function setTwapOracleAddress(address _twapOracleAddress)
external
onlyAdmin
{
twapOracleAddress = _twapOracleAddress;
// to be removed
TWAPOracle oracle = TWAPOracle(twapOracleAddress);
oracle.update();
}
function setuARTokenAddress(address _uarTokenAddress) external onlyAdmin {
autoRedeemTokenAddress = _uarTokenAddress;
}
function setDebtCouponAddress(address _debtCouponAddress)
external
onlyAdmin
{
debtCouponAddress = _debtCouponAddress;
}
function setIncentiveToUAD(address _account, address _incentiveAddress)
external
onlyAdmin
{
IUbiquityAlgorithmicDollar(dollarTokenAddress).setIncentiveContract(
_account,
_incentiveAddress
);
}
function setDollarTokenAddress(address _dollarTokenAddress)
external
onlyAdmin
{
dollarTokenAddress = _dollarTokenAddress;
}
function setGovernanceTokenAddress(address _governanceTokenAddress)
external
onlyAdmin
{
governanceTokenAddress = _governanceTokenAddress;
}
function setSushiSwapPoolAddress(address _sushiSwapPoolAddress)
external
onlyAdmin
{
sushiSwapPoolAddress = _sushiSwapPoolAddress;
}
function setUARCalculatorAddress(address _uarCalculatorAddress)
external
onlyAdmin
{
uarCalculatorAddress = _uarCalculatorAddress;
}
function setCouponCalculatorAddress(address _couponCalculatorAddress)
external
onlyAdmin
{
couponCalculatorAddress = _couponCalculatorAddress;
}
function setDollarMintingCalculatorAddress(
address _dollarMintingCalculatorAddress
) external onlyAdmin {
dollarMintingCalculatorAddress = _dollarMintingCalculatorAddress;
}
function setExcessDollarsDistributor(
address debtCouponManagerAddress,
address excessCouponDistributor
) external onlyAdmin {
_excessDollarDistributors[
debtCouponManagerAddress
] = excessCouponDistributor;
}
function setMasterChefAddress(address _masterChefAddress)
external
onlyAdmin
{
masterChefAddress = _masterChefAddress;
}
function setFormulasAddress(address _formulasAddress) external onlyAdmin {
formulasAddress = _formulasAddress;
}
function setBondingShareAddress(address _bondingShareAddress)
external
onlyAdmin
{
bondingShareAddress = _bondingShareAddress;
}
function setStableSwapMetaPoolAddress(address _stableSwapMetaPoolAddress)
external
onlyAdmin
{
stableSwapMetaPoolAddress = _stableSwapMetaPoolAddress;
}
/**
@notice set the bonding bontract smart contract address
@dev bonding contract participants deposit curve LP token
for a certain duration to earn uGOV and more curve LP token
@param _bondingContractAddress bonding contract address
*/
function setBondingContractAddress(address _bondingContractAddress)
external
onlyAdmin
{
bondingContractAddress = _bondingContractAddress;
}
/**
@notice set the treasury address
@dev the treasury fund is used to maintain the protocol
@param _treasuryAddress treasury fund address
*/
function setTreasuryAddress(address _treasuryAddress) external onlyAdmin {
treasuryAddress = _treasuryAddress;
}
/**
@notice deploy a new Curve metapools for uAD Token uAD/3Pool
@dev From the curve documentation for uncollateralized algorithmic
stablecoins amplification should be 5-10
@param _curveFactory MetaPool factory address
@param _crvBasePool Address of the base pool to use within the new metapool.
@param _crv3PoolTokenAddress curve 3Pool token Address
@param _amplificationCoefficient amplification coefficient. The smaller
it is the closer to a constant product we are.
@param _fee Trade fee, given as an integer with 1e10 precision.
*/
function deployStableSwapPool(
address _curveFactory,
address _crvBasePool,
address _crv3PoolTokenAddress,
uint256 _amplificationCoefficient,
uint256 _fee
) external onlyAdmin {
// Create new StableSwap meta pool (uAD <-> 3Crv)
address metaPool =
ICurveFactory(_curveFactory).deploy_metapool(
_crvBasePool,
ERC20(dollarTokenAddress).name(),
ERC20(dollarTokenAddress).symbol(),
dollarTokenAddress,
_amplificationCoefficient,
_fee
);
stableSwapMetaPoolAddress = metaPool;
// Approve the newly-deployed meta pool to transfer this contract's funds
uint256 crv3PoolTokenAmount =
IERC20(_crv3PoolTokenAddress).balanceOf(address(this));
uint256 uADTokenAmount =
IERC20(dollarTokenAddress).balanceOf(address(this));
// safe approve revert if approve from non-zero to non-zero allowance
IERC20(_crv3PoolTokenAddress).safeApprove(metaPool, 0);
IERC20(_crv3PoolTokenAddress).safeApprove(
metaPool,
crv3PoolTokenAmount
);
IERC20(dollarTokenAddress).safeApprove(metaPool, 0);
IERC20(dollarTokenAddress).safeApprove(metaPool, uADTokenAmount);
// coin at index 0 is uAD and index 1 is 3CRV
require(
IMetaPool(metaPool).coins(0) == dollarTokenAddress &&
IMetaPool(metaPool).coins(1) == _crv3PoolTokenAddress,
"uADMGR: COIN_ORDER_MISMATCH"
);
// Add the initial liquidity to the StableSwap meta pool
uint256[2] memory amounts =
[
IERC20(dollarTokenAddress).balanceOf(address(this)),
IERC20(_crv3PoolTokenAddress).balanceOf(address(this))
];
// set curve 3Pool address
curve3PoolTokenAddress = _crv3PoolTokenAddress;
IMetaPool(metaPool).add_liquidity(amounts, 0, msg.sender);
}
function getExcessDollarsDistributor(address _debtCouponManagerAddress)
external
view
returns (address)
{
return _excessDollarDistributors[_debtCouponManagerAddress];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
/// @title A mechanism for calculating dollars to be minted
interface IDollarMintingCalculator {
function getDollarsToMint() external view returns (uint256);
}
// 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: Apache-2.0
pragma solidity ^0.8.3;
import "./interfaces/IMetaPool.sol";
contract TWAPOracle {
address public immutable pool;
address public immutable token0;
address public immutable token1;
uint256 public price0Average;
uint256 public price1Average;
uint256 public pricesBlockTimestampLast;
uint256[2] public priceCumulativeLast;
constructor(
address _pool,
address _uADtoken0,
address _curve3CRVtoken1
) {
pool = _pool;
// coin at index 0 is uAD and index 1 is 3CRV
require(
IMetaPool(_pool).coins(0) == _uADtoken0 &&
IMetaPool(_pool).coins(1) == _curve3CRVtoken1,
"TWAPOracle: COIN_ORDER_MISMATCH"
);
token0 = _uADtoken0;
token1 = _curve3CRVtoken1;
uint256 _reserve0 = uint112(IMetaPool(_pool).balances(0));
uint256 _reserve1 = uint112(IMetaPool(_pool).balances(1));
// ensure that there's liquidity in the pair
require(_reserve0 != 0 && _reserve1 != 0, "TWAPOracle: NO_RESERVES");
// ensure that pair balance is perfect
require(_reserve0 == _reserve1, "TWAPOracle: PAIR_UNBALANCED");
priceCumulativeLast = IMetaPool(_pool).get_price_cumulative_last();
pricesBlockTimestampLast = IMetaPool(_pool).block_timestamp_last();
price0Average = 1 ether;
price1Average = 1 ether;
}
// calculate average price
function update() external {
(uint256[2] memory priceCumulative, uint256 blockTimestamp) =
_currentCumulativePrices();
if (blockTimestamp - pricesBlockTimestampLast > 0) {
// get the balances between now and the last price cumulative snapshot
uint256[2] memory twapBalances =
IMetaPool(pool).get_twap_balances(
priceCumulativeLast,
priceCumulative,
blockTimestamp - pricesBlockTimestampLast
);
// price to exchange amounIn uAD to 3CRV based on TWAP
price0Average = IMetaPool(pool).get_dy(0, 1, 1 ether, twapBalances);
// price to exchange amounIn 3CRV to uAD based on TWAP
price1Average = IMetaPool(pool).get_dy(1, 0, 1 ether, twapBalances);
// we update the priceCumulative
priceCumulativeLast = priceCumulative;
pricesBlockTimestampLast = blockTimestamp;
}
}
// note this will always return 0 before update has been called successfully
// for the first time.
function consult(address token) external view returns (uint256 amountOut) {
if (token == token0) {
// price to exchange 1 uAD to 3CRV based on TWAP
amountOut = price0Average;
} else {
require(token == token1, "TWAPOracle: INVALID_TOKEN");
// price to exchange 1 3CRV to uAD based on TWAP
amountOut = price1Average;
}
}
function _currentCumulativePrices()
internal
view
returns (uint256[2] memory priceCumulative, uint256 blockTimestamp)
{
priceCumulative = IMetaPool(pool).get_price_cumulative_last();
blockTimestamp = IMetaPool(pool).block_timestamp_last();
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math Quad Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with IEEE 754
* quadruple-precision binary floating-point numbers (quadruple precision
* numbers). As long as quadruple precision numbers are 16-bytes long, they are
* represented by bytes16 type.
*/
library ABDKMathQuad {
/*
* 0.
*/
bytes16 private constant _POSITIVE_ZERO =
0x00000000000000000000000000000000;
/*
* -0.
*/
bytes16 private constant _NEGATIVE_ZERO =
0x80000000000000000000000000000000;
/*
* +Infinity.
*/
bytes16 private constant _POSITIVE_INFINITY =
0x7FFF0000000000000000000000000000;
/*
* -Infinity.
*/
bytes16 private constant _NEGATIVE_INFINITY =
0xFFFF0000000000000000000000000000;
/*
* Canonical NaN value.
*/
bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;
/**
* Convert signed 256-bit integer number into quadruple precision number.
*
* @param x signed 256-bit integer number
* @return quadruple precision number
*/
function fromInt(int256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16383 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 256-bit integer number
* rounding towards zero. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 256-bit integer number
*/
function toInt(bytes16 x) internal pure returns (int256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16638); // Overflow
if (exponent < 16383) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(
result <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
return -int256(result); // We rely on overflow behavior here
} else {
require(
result <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(result);
}
}
}
/**
* Convert unsigned 256-bit integer number into quadruple precision number.
*
* @param x unsigned 256-bit integer number
* @return quadruple precision number
*/
function fromUInt(uint256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
uint256 result = x;
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16383 + msb) << 112);
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into unsigned 256-bit integer number
* rounding towards zero. Revert on underflow. Note, that negative floating
* point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer
* without error, because they are rounded to zero.
*
* @param x quadruple precision number
* @return unsigned 256-bit integer number
*/
function toUInt(bytes16 x) internal pure returns (uint256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
if (exponent < 16383) return 0; // Underflow
require(uint128(x) < 0x80000000000000000000000000000000); // Negative
require(exponent <= 16638); // Overflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
return result;
}
}
/**
* Convert signed 128.128 bit fixed point number into quadruple precision
* number.
*
* @param x signed 128.128 bit fixed point number
* @return quadruple precision number
*/
function from128x128(int256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16255 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 128.128 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 128.128 bit fixed point number
*/
function to128x128(bytes16 x) internal pure returns (int256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16510); // Overflow
if (exponent < 16255) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16367) result >>= 16367 - exponent;
else if (exponent > 16367) result <<= exponent - 16367;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(
result <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
return -int256(result); // We rely on overflow behavior here
} else {
require(
result <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(result);
}
}
}
/**
* Convert signed 64.64 bit fixed point number into quadruple precision
* number.
*
* @param x signed 64.64 bit fixed point number
* @return quadruple precision number
*/
function from64x64(int128 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint128(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16319 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 64.64 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 64.64 bit fixed point number
*/
function to64x64(bytes16 x) internal pure returns (int128) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16446); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x80000000000000000000000000000000);
return -int128(int256(result)); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(int256(result));
}
}
}
/**
* Convert octuple precision number into quadruple precision number.
*
* @param x octuple precision number
* @return quadruple precision number
*/
function fromOctuple(bytes32 x) internal pure returns (bytes16) {
unchecked {
bool negative =
x &
0x8000000000000000000000000000000000000000000000000000000000000000 >
0;
uint256 exponent = (uint256(x) >> 236) & 0x7FFFF;
uint256 significand =
uint256(x) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFFF) {
if (significand > 0) return NaN;
else return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
}
if (exponent > 278526)
return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else if (exponent < 245649)
return negative ? _NEGATIVE_ZERO : _POSITIVE_ZERO;
else if (exponent < 245761) {
significand =
(significand |
0x100000000000000000000000000000000000000000000000000000000000) >>
(245885 - exponent);
exponent = 0;
} else {
significand >>= 124;
exponent -= 245760;
}
uint128 result = uint128(significand | (exponent << 112));
if (negative) result |= 0x80000000000000000000000000000000;
return bytes16(result);
}
}
/**
* Convert quadruple precision number into octuple precision number.
*
* @param x quadruple precision number
* @return octuple precision number
*/
function toOctuple(bytes16 x) internal pure returns (bytes32) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 result = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF)
exponent = 0x7FFFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = mostSignificantBit(result);
result =
(result << (236 - msb)) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 245649 + msb;
}
} else {
result <<= 124;
exponent += 245760;
}
result |= exponent << 236;
if (uint128(x) >= 0x80000000000000000000000000000000)
result |= 0x8000000000000000000000000000000000000000000000000000000000000000;
return bytes32(result);
}
}
/**
* Convert double precision number into quadruple precision number.
*
* @param x double precision number
* @return quadruple precision number
*/
function fromDouble(bytes8 x) internal pure returns (bytes16) {
unchecked {
uint256 exponent = (uint64(x) >> 52) & 0x7FF;
uint256 result = uint64(x) & 0xFFFFFFFFFFFFF;
if (exponent == 0x7FF)
exponent = 0x7FFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = mostSignificantBit(result);
result =
(result << (112 - msb)) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 15309 + msb;
}
} else {
result <<= 60;
exponent += 15360;
}
result |= exponent << 112;
if (x & 0x8000000000000000 > 0)
result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into double precision number.
*
* @param x quadruple precision number
* @return double precision number
*/
function toDouble(bytes16 x) internal pure returns (bytes8) {
unchecked {
bool negative = uint128(x) >= 0x80000000000000000000000000000000;
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 significand = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF) {
if (significand > 0) return 0x7FF8000000000000;
// NaN
else
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000); // Infinity
}
if (exponent > 17406)
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000);
// Infinity
else if (exponent < 15309)
return
negative
? bytes8(0x8000000000000000) // -0
: bytes8(0x0000000000000000);
// 0
else if (exponent < 15361) {
significand =
(significand | 0x10000000000000000000000000000) >>
(15421 - exponent);
exponent = 0;
} else {
significand >>= 60;
exponent -= 15360;
}
uint64 result = uint64(significand | (exponent << 52));
if (negative) result |= 0x8000000000000000;
return bytes8(result);
}
}
/**
* Test whether given quadruple precision number is NaN.
*
* @param x quadruple precision number
* @return true if x is NaN, false otherwise
*/
function isNaN(bytes16 x) internal pure returns (bool) {
unchecked {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF >
0x7FFF0000000000000000000000000000;
}
}
/**
* Test whether given quadruple precision number is positive or negative
* infinity.
*
* @param x quadruple precision number
* @return true if x is positive or negative infinity, false otherwise
*/
function isInfinity(bytes16 x) internal pure returns (bool) {
unchecked {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ==
0x7FFF0000000000000000000000000000;
}
}
/**
* Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x
* is positive. Note that sign (-0) is zero. Revert if x is NaN.
*
* @param x quadruple precision number
* @return sign of x
*/
function sign(bytes16 x) internal pure returns (int8) {
unchecked {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
if (absoluteX == 0) return 0;
else if (uint128(x) >= 0x80000000000000000000000000000000)
return -1;
else return 1;
}
}
/**
* Calculate sign (x - y). Revert if either argument is NaN, or both
* arguments are infinities of the same sign.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return sign (x - y)
*/
function cmp(bytes16 x, bytes16 y) internal pure returns (int8) {
unchecked {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
uint128 absoluteY = uint128(y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN
// Not infinities of the same sign
require(x != y || absoluteX < 0x7FFF0000000000000000000000000000);
if (x == y) return 0;
else {
bool negativeX =
uint128(x) >= 0x80000000000000000000000000000000;
bool negativeY =
uint128(y) >= 0x80000000000000000000000000000000;
if (negativeX) {
if (negativeY) return absoluteX > absoluteY ? -1 : int8(1);
else return -1;
} else {
if (negativeY) return 1;
else return absoluteX > absoluteY ? int8(1) : -1;
}
}
}
}
/**
* Test whether x equals y. NaN, infinity, and -infinity are not equal to
* anything.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return true if x equals to y, false otherwise
*/
function eq(bytes16 x, bytes16 y) internal pure returns (bool) {
unchecked {
if (x == y) {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF <
0x7FFF0000000000000000000000000000;
} else return false;
}
}
/**
* Calculate x + y. Special values behave in the following way:
*
* NaN + x = NaN for any x.
* Infinity + x = Infinity for any finite x.
* -Infinity + x = -Infinity for any finite x.
* Infinity + Infinity = Infinity.
* -Infinity + -Infinity = -Infinity.
* Infinity + -Infinity = -Infinity + Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function add(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x;
else return NaN;
} else return x;
} else if (yExponent == 0x7FFF) return y;
else {
bool xSign = uint128(x) >= 0x80000000000000000000000000000000;
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
bool ySign = uint128(y) >= 0x80000000000000000000000000000000;
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0)
return y == _NEGATIVE_ZERO ? _POSITIVE_ZERO : y;
else if (ySignifier == 0)
return x == _NEGATIVE_ZERO ? _POSITIVE_ZERO : x;
else {
int256 delta = int256(xExponent) - int256(yExponent);
if (xSign == ySign) {
if (delta > 112) return x;
else if (delta > 0) ySignifier >>= uint256(delta);
else if (delta < -112) return y;
else if (delta < 0) {
xSignifier >>= uint256(-delta);
xExponent = yExponent;
}
xSignifier += ySignifier;
if (xSignifier >= 0x20000000000000000000000000000) {
xSignifier >>= 1;
xExponent += 1;
}
if (xExponent == 0x7FFF)
return
xSign ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else {
if (xSignifier < 0x10000000000000000000000000000)
xExponent = 0;
else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
return
bytes16(
uint128(
(
xSign
? 0x80000000000000000000000000000000
: 0
) |
(xExponent << 112) |
xSignifier
)
);
}
} else {
if (delta > 0) {
xSignifier <<= 1;
xExponent -= 1;
} else if (delta < 0) {
ySignifier <<= 1;
xExponent = yExponent - 1;
}
if (delta > 112) ySignifier = 1;
else if (delta > 1)
ySignifier =
((ySignifier - 1) >> uint256(delta - 1)) +
1;
else if (delta < -112) xSignifier = 1;
else if (delta < -1)
xSignifier =
((xSignifier - 1) >> uint256(-delta - 1)) +
1;
if (xSignifier >= ySignifier) xSignifier -= ySignifier;
else {
xSignifier = ySignifier - xSignifier;
xSign = ySign;
}
if (xSignifier == 0) return _POSITIVE_ZERO;
uint256 msb = mostSignificantBit(xSignifier);
if (msb == 113) {
xSignifier =
(xSignifier >> 1) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent += 1;
} else if (msb < 112) {
uint256 shift = 112 - msb;
if (xExponent > shift) {
xSignifier =
(xSignifier << shift) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent -= shift;
} else {
xSignifier <<= xExponent - 1;
xExponent = 0;
}
} else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF)
return
xSign ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else
return
bytes16(
uint128(
(
xSign
? 0x80000000000000000000000000000000
: 0
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
}
}
/**
* Calculate x - y. Special values behave in the following way:
*
* NaN - x = NaN for any x.
* Infinity - x = Infinity for any finite x.
* -Infinity - x = -Infinity for any finite x.
* Infinity - -Infinity = Infinity.
* -Infinity - Infinity = -Infinity.
* Infinity - Infinity = -Infinity - -Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {return add(x, y ^ 0x80000000000000000000000000000000);}
}
/**
* Calculate x * y. Special values behave in the following way:
*
* NaN * x = NaN for any x.
* Infinity * x = Infinity for any finite positive x.
* Infinity * x = -Infinity for any finite negative x.
* -Infinity * x = -Infinity for any finite positive x.
* -Infinity * x = Infinity for any finite negative x.
* Infinity * 0 = NaN.
* -Infinity * 0 = NaN.
* Infinity * Infinity = Infinity.
* Infinity * -Infinity = -Infinity.
* -Infinity * Infinity = -Infinity.
* -Infinity * -Infinity = Infinity.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function mul(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y)
return x ^ (y & 0x80000000000000000000000000000000);
else if (x ^ y == 0x80000000000000000000000000000000)
return x | y;
else return NaN;
} else {
if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
}
} else if (yExponent == 0x7FFF) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return y ^ (x & 0x80000000000000000000000000000000);
} else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
xSignifier *= ySignifier;
if (xSignifier == 0)
return
(x ^ y) & 0x80000000000000000000000000000000 > 0
? _NEGATIVE_ZERO
: _POSITIVE_ZERO;
xExponent += yExponent;
uint256 msb =
xSignifier >=
0x200000000000000000000000000000000000000000000000000000000
? 225
: xSignifier >=
0x100000000000000000000000000000000000000000000000000000000
? 224
: mostSignificantBit(xSignifier);
if (xExponent + msb < 16496) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb < 16608) {
// Subnormal
if (xExponent < 16496) xSignifier >>= 16496 - xExponent;
else if (xExponent > 16496)
xSignifier <<= xExponent - 16496;
xExponent = 0;
} else if (xExponent + msb > 49373) {
xExponent = 0x7FFF;
xSignifier = 0;
} else {
if (msb > 112) xSignifier >>= msb - 112;
else if (msb < 112) xSignifier <<= 112 - msb;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb - 16607;
}
return
bytes16(
uint128(
uint128(
(x ^ y) & 0x80000000000000000000000000000000
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
/**
* Calculate x / y. Special values behave in the following way:
*
* NaN / x = NaN for any x.
* x / NaN = NaN for any x.
* Infinity / x = Infinity for any finite non-negative x.
* Infinity / x = -Infinity for any finite negative x including -0.
* -Infinity / x = -Infinity for any finite non-negative x.
* -Infinity / x = Infinity for any finite negative x including -0.
* x / Infinity = 0 for any finite non-negative x.
* x / -Infinity = -0 for any finite non-negative x.
* x / Infinity = -0 for any finite non-negative x including -0.
* x / -Infinity = 0 for any finite non-negative x including -0.
*
* Infinity / Infinity = NaN.
* Infinity / -Infinity = -NaN.
* -Infinity / Infinity = -NaN.
* -Infinity / -Infinity = NaN.
*
* Division by zero behaves in the following way:
*
* x / 0 = Infinity for any finite positive x.
* x / -0 = -Infinity for any finite positive x.
* x / 0 = -Infinity for any finite negative x.
* x / -0 = Infinity for any finite negative x.
* 0 / 0 = NaN.
* 0 / -0 = NaN.
* -0 / 0 = NaN.
* -0 / -0 = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function div(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
} else if (yExponent == 0x7FFF) {
if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN;
else
return
_POSITIVE_ZERO |
((x ^ y) & 0x80000000000000000000000000000000);
} else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else
return
_POSITIVE_INFINITY |
((x ^ y) & 0x80000000000000000000000000000000);
} else {
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) {
if (xSignifier != 0) {
uint256 shift = 226 - mostSignificantBit(xSignifier);
xSignifier <<= shift;
xExponent = 1;
yExponent += shift - 114;
}
} else {
xSignifier =
(xSignifier | 0x10000000000000000000000000000) <<
114;
}
xSignifier = xSignifier / ySignifier;
if (xSignifier == 0)
return
(x ^ y) & 0x80000000000000000000000000000000 > 0
? _NEGATIVE_ZERO
: _POSITIVE_ZERO;
assert(xSignifier >= 0x1000000000000000000000000000);
uint256 msb =
xSignifier >= 0x80000000000000000000000000000
? mostSignificantBit(xSignifier)
: xSignifier >= 0x40000000000000000000000000000
? 114
: xSignifier >= 0x20000000000000000000000000000
? 113
: 112;
if (xExponent + msb > yExponent + 16497) {
// Overflow
xExponent = 0x7FFF;
xSignifier = 0;
} else if (xExponent + msb + 16380 < yExponent) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb + 16268 < yExponent) {
// Subnormal
if (xExponent + 16380 > yExponent)
xSignifier <<= xExponent + 16380 - yExponent;
else if (xExponent + 16380 < yExponent)
xSignifier >>= yExponent - xExponent - 16380;
xExponent = 0;
} else {
// Normal
if (msb > 112) xSignifier >>= msb - 112;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb + 16269 - yExponent;
}
return
bytes16(
uint128(
uint128(
(x ^ y) & 0x80000000000000000000000000000000
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
/**
* Calculate -x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function neg(bytes16 x) internal pure returns (bytes16) {
unchecked {return x ^ 0x80000000000000000000000000000000;}
}
/**
* Calculate |x|.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function abs(bytes16 x) internal pure returns (bytes16) {
unchecked {return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;}
}
/**
* Calculate square root of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function sqrt(bytes16 x) internal pure returns (bytes16) {
unchecked {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return _POSITIVE_ZERO;
bool oddExponent = xExponent & 0x1 == 0;
xExponent = (xExponent + 16383) >> 1;
if (oddExponent) {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 113;
else {
uint256 msb = mostSignificantBit(xSignifier);
uint256 shift = (226 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
} else {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 112;
else {
uint256 msb = mostSignificantBit(xSignifier);
uint256 shift = (225 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
}
uint256 r = 0x10000000000000000000000000000;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1; // Seven iterations should be enough
uint256 r1 = xSignifier / r;
if (r1 < r) r = r1;
return
bytes16(
uint128(
(xExponent << 112) |
(r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
}
}
}
}
/**
* Calculate binary logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function log_2(bytes16 x) internal pure returns (bytes16) {
unchecked {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else if (x == 0x3FFF0000000000000000000000000000)
return _POSITIVE_ZERO;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return _NEGATIVE_INFINITY;
bool resultNegative;
uint256 resultExponent = 16495;
uint256 resultSignifier;
if (xExponent >= 0x3FFF) {
resultNegative = false;
resultSignifier = xExponent - 0x3FFF;
xSignifier <<= 15;
} else {
resultNegative = true;
if (xSignifier >= 0x10000000000000000000000000000) {
resultSignifier = 0x3FFE - xExponent;
xSignifier <<= 15;
} else {
uint256 msb = mostSignificantBit(xSignifier);
resultSignifier = 16493 - msb;
xSignifier <<= 127 - msb;
}
}
if (xSignifier == 0x80000000000000000000000000000000) {
if (resultNegative) resultSignifier += 1;
uint256 shift =
112 - mostSignificantBit(resultSignifier);
resultSignifier <<= shift;
resultExponent -= shift;
} else {
uint256 bb = resultNegative ? 1 : 0;
while (
resultSignifier < 0x10000000000000000000000000000
) {
resultSignifier <<= 1;
resultExponent -= 1;
xSignifier *= xSignifier;
uint256 b = xSignifier >> 255;
resultSignifier += b ^ bb;
xSignifier >>= 127 + b;
}
}
return
bytes16(
uint128(
(
resultNegative
? 0x80000000000000000000000000000000
: 0
) |
(resultExponent << 112) |
(resultSignifier &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
}
}
}
}
/**
* Calculate natural logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function ln(bytes16 x) internal pure returns (bytes16) {
unchecked {return mul(log_2(x), 0x3FFE62E42FEFA39EF35793C7673007E5);}
}
/**
* Calculate 2^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function pow_2(bytes16 x) internal pure returns (bytes16) {
unchecked {
bool xNegative = uint128(x) > 0x80000000000000000000000000000000;
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF && xSignifier != 0) return NaN;
else if (xExponent > 16397)
return xNegative ? _POSITIVE_ZERO : _POSITIVE_INFINITY;
else if (xExponent < 16255)
return 0x3FFF0000000000000000000000000000;
else {
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xExponent > 16367) xSignifier <<= xExponent - 16367;
else if (xExponent < 16367) xSignifier >>= 16367 - xExponent;
if (
xNegative &&
xSignifier > 0x406E00000000000000000000000000000000
) return _POSITIVE_ZERO;
if (
!xNegative &&
xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
) return _POSITIVE_INFINITY;
uint256 resultExponent = xSignifier >> 128;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xNegative && xSignifier != 0) {
xSignifier = ~xSignifier;
resultExponent += 1;
}
uint256 resultSignifier = 0x80000000000000000000000000000000;
if (xSignifier & 0x80000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x16A09E667F3BCC908B2FB1366EA957D3E) >>
128;
if (xSignifier & 0x40000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1306FE0A31B7152DE8D5A46305C85EDEC) >>
128;
if (xSignifier & 0x20000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1172B83C7D517ADCDF7C8C50EB14A791F) >>
128;
if (xSignifier & 0x10000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10B5586CF9890F6298B92B71842A98363) >>
128;
if (xSignifier & 0x8000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1059B0D31585743AE7C548EB68CA417FD) >>
128;
if (xSignifier & 0x4000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x102C9A3E778060EE6F7CACA4F7A29BDE8) >>
128;
if (xSignifier & 0x2000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10163DA9FB33356D84A66AE336DCDFA3F) >>
128;
if (xSignifier & 0x1000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100B1AFA5ABCBED6129AB13EC11DC9543) >>
128;
if (xSignifier & 0x800000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10058C86DA1C09EA1FF19D294CF2F679B) >>
128;
if (xSignifier & 0x400000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1002C605E2E8CEC506D21BFC89A23A00F) >>
128;
if (xSignifier & 0x200000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100162F3904051FA128BCA9C55C31E5DF) >>
128;
if (xSignifier & 0x100000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000B175EFFDC76BA38E31671CA939725) >>
128;
if (xSignifier & 0x80000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100058BA01FB9F96D6CACD4B180917C3D) >>
128;
if (xSignifier & 0x40000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10002C5CC37DA9491D0985C348C68E7B3) >>
128;
if (xSignifier & 0x20000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000162E525EE054754457D5995292026) >>
128;
if (xSignifier & 0x10000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000B17255775C040618BF4A4ADE83FC) >>
128;
if (xSignifier & 0x8000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >>
128;
if (xSignifier & 0x4000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >>
128;
if (xSignifier & 0x2000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000162E43F4F831060E02D839A9D16D) >>
128;
if (xSignifier & 0x1000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000B1721BCFC99D9F890EA06911763) >>
128;
if (xSignifier & 0x800000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000058B90CF1E6D97F9CA14DBCC1628) >>
128;
if (xSignifier & 0x400000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000002C5C863B73F016468F6BAC5CA2B) >>
128;
if (xSignifier & 0x200000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000162E430E5A18F6119E3C02282A5) >>
128;
if (xSignifier & 0x100000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000B1721835514B86E6D96EFD1BFE) >>
128;
if (xSignifier & 0x80000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000058B90C0B48C6BE5DF846C5B2EF) >>
128;
if (xSignifier & 0x40000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000002C5C8601CC6B9E94213C72737A) >>
128;
if (xSignifier & 0x20000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000162E42FFF037DF38AA2B219F06) >>
128;
if (xSignifier & 0x10000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000B17217FBA9C739AA5819F44F9) >>
128;
if (xSignifier & 0x8000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000058B90BFCDEE5ACD3C1CEDC823) >>
128;
if (xSignifier & 0x4000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000002C5C85FE31F35A6A30DA1BE50) >>
128;
if (xSignifier & 0x2000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000162E42FF0999CE3541B9FFFCF) >>
128;
if (xSignifier & 0x1000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000B17217F80F4EF5AADDA45554) >>
128;
if (xSignifier & 0x800000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000058B90BFBF8479BD5A81B51AD) >>
128;
if (xSignifier & 0x400000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000002C5C85FDF84BD62AE30A74CC) >>
128;
if (xSignifier & 0x200000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000162E42FEFB2FED257559BDAA) >>
128;
if (xSignifier & 0x100000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000B17217F7D5A7716BBA4A9AE) >>
128;
if (xSignifier & 0x80000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000058B90BFBE9DDBAC5E109CCE) >>
128;
if (xSignifier & 0x40000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000002C5C85FDF4B15DE6F17EB0D) >>
128;
if (xSignifier & 0x20000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000162E42FEFA494F1478FDE05) >>
128;
if (xSignifier & 0x10000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000B17217F7D20CF927C8E94C) >>
128;
if (xSignifier & 0x8000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000058B90BFBE8F71CB4E4B33D) >>
128;
if (xSignifier & 0x4000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000002C5C85FDF477B662B26945) >>
128;
if (xSignifier & 0x2000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000162E42FEFA3AE53369388C) >>
128;
if (xSignifier & 0x1000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000B17217F7D1D351A389D40) >>
128;
if (xSignifier & 0x800000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000058B90BFBE8E8B2D3D4EDE) >>
128;
if (xSignifier & 0x400000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000002C5C85FDF4741BEA6E77E) >>
128;
if (xSignifier & 0x200000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000162E42FEFA39FE95583C2) >>
128;
if (xSignifier & 0x100000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000B17217F7D1CFB72B45E1) >>
128;
if (xSignifier & 0x80000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000058B90BFBE8E7CC35C3F0) >>
128;
if (xSignifier & 0x40000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000002C5C85FDF473E242EA38) >>
128;
if (xSignifier & 0x20000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000162E42FEFA39F02B772C) >>
128;
if (xSignifier & 0x10000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000B17217F7D1CF7D83C1A) >>
128;
if (xSignifier & 0x8000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000058B90BFBE8E7BDCBE2E) >>
128;
if (xSignifier & 0x4000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000002C5C85FDF473DEA871F) >>
128;
if (xSignifier & 0x2000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000162E42FEFA39EF44D91) >>
128;
if (xSignifier & 0x1000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000B17217F7D1CF79E949) >>
128;
if (xSignifier & 0x800000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000058B90BFBE8E7BCE544) >>
128;
if (xSignifier & 0x400000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000002C5C85FDF473DE6ECA) >>
128;
if (xSignifier & 0x200000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000162E42FEFA39EF366F) >>
128;
if (xSignifier & 0x100000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000B17217F7D1CF79AFA) >>
128;
if (xSignifier & 0x80000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000058B90BFBE8E7BCD6D) >>
128;
if (xSignifier & 0x40000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000002C5C85FDF473DE6B2) >>
128;
if (xSignifier & 0x20000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000162E42FEFA39EF358) >>
128;
if (xSignifier & 0x10000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000B17217F7D1CF79AB) >>
128;
if (xSignifier & 0x8000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000058B90BFBE8E7BCD5) >>
128;
if (xSignifier & 0x4000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000002C5C85FDF473DE6A) >>
128;
if (xSignifier & 0x2000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000162E42FEFA39EF34) >>
128;
if (xSignifier & 0x1000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000B17217F7D1CF799) >>
128;
if (xSignifier & 0x800000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000058B90BFBE8E7BCC) >>
128;
if (xSignifier & 0x400000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000002C5C85FDF473DE5) >>
128;
if (xSignifier & 0x200000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000162E42FEFA39EF2) >>
128;
if (xSignifier & 0x100000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000B17217F7D1CF78) >>
128;
if (xSignifier & 0x80000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000058B90BFBE8E7BB) >>
128;
if (xSignifier & 0x40000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000002C5C85FDF473DD) >>
128;
if (xSignifier & 0x20000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000162E42FEFA39EE) >>
128;
if (xSignifier & 0x10000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000B17217F7D1CF6) >>
128;
if (xSignifier & 0x8000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000058B90BFBE8E7A) >>
128;
if (xSignifier & 0x4000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000002C5C85FDF473C) >>
128;
if (xSignifier & 0x2000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000162E42FEFA39D) >>
128;
if (xSignifier & 0x1000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000B17217F7D1CE) >>
128;
if (xSignifier & 0x800000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000058B90BFBE8E6) >>
128;
if (xSignifier & 0x400000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000002C5C85FDF472) >>
128;
if (xSignifier & 0x200000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000162E42FEFA38) >>
128;
if (xSignifier & 0x100000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000B17217F7D1B) >>
128;
if (xSignifier & 0x80000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000058B90BFBE8D) >>
128;
if (xSignifier & 0x40000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000002C5C85FDF46) >>
128;
if (xSignifier & 0x20000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000162E42FEFA2) >>
128;
if (xSignifier & 0x10000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000B17217F7D0) >>
128;
if (xSignifier & 0x8000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000058B90BFBE7) >>
128;
if (xSignifier & 0x4000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000002C5C85FDF3) >>
128;
if (xSignifier & 0x2000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000162E42FEF9) >>
128;
if (xSignifier & 0x1000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000B17217F7C) >>
128;
if (xSignifier & 0x800000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000058B90BFBD) >>
128;
if (xSignifier & 0x400000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000002C5C85FDE) >>
128;
if (xSignifier & 0x200000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000162E42FEE) >>
128;
if (xSignifier & 0x100000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000B17217F6) >>
128;
if (xSignifier & 0x80000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000058B90BFA) >>
128;
if (xSignifier & 0x40000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000002C5C85FC) >>
128;
if (xSignifier & 0x20000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000162E42FD) >>
128;
if (xSignifier & 0x10000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000B17217E) >>
128;
if (xSignifier & 0x8000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000058B90BE) >>
128;
if (xSignifier & 0x4000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000002C5C85E) >>
128;
if (xSignifier & 0x2000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000162E42E) >>
128;
if (xSignifier & 0x1000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000B17216) >>
128;
if (xSignifier & 0x800000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000058B90A) >>
128;
if (xSignifier & 0x400000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000002C5C84) >>
128;
if (xSignifier & 0x200000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000162E41) >>
128;
if (xSignifier & 0x100000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000B1720) >>
128;
if (xSignifier & 0x80000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000058B8F) >>
128;
if (xSignifier & 0x40000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000002C5C7) >>
128;
if (xSignifier & 0x20000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000162E3) >>
128;
if (xSignifier & 0x10000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000B171) >>
128;
if (xSignifier & 0x8000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000058B8) >>
128;
if (xSignifier & 0x4000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000002C5B) >>
128;
if (xSignifier & 0x2000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000162D) >>
128;
if (xSignifier & 0x1000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000B16) >>
128;
if (xSignifier & 0x800 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000058A) >>
128;
if (xSignifier & 0x400 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000002C4) >>
128;
if (xSignifier & 0x200 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000161) >>
128;
if (xSignifier & 0x100 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000000B0) >>
128;
if (xSignifier & 0x80 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000057) >>
128;
if (xSignifier & 0x40 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000002B) >>
128;
if (xSignifier & 0x20 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000015) >>
128;
if (xSignifier & 0x10 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000000A) >>
128;
if (xSignifier & 0x8 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000004) >>
128;
if (xSignifier & 0x4 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000001) >>
128;
if (!xNegative) {
resultSignifier =
(resultSignifier >> 15) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent += 0x3FFF;
} else if (resultExponent <= 0x3FFE) {
resultSignifier =
(resultSignifier >> 15) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent = 0x3FFF - resultExponent;
} else {
resultSignifier =
resultSignifier >>
(resultExponent - 16367);
resultExponent = 0;
}
return
bytes16(uint128((resultExponent << 112) | resultSignifier));
}
}
}
/**
* Calculate e^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function exp(bytes16 x) internal pure returns (bytes16) {
unchecked {return pow_2(mul(x, 0x3FFF71547652B82FE1777D0FFDA0D23A));}
}
/**
* Get index of the most significant non-zero bit in binary representation of
* x. Reverts if x is zero.
*
* @return index of the most significant non-zero bit in binary representation
* of x
*/
function mostSignificantBit(uint256 x) private pure returns (uint256) {
unchecked {
require(x > 0);
uint256 result = 0;
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
result += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
result += 64;
}
if (x >= 0x100000000) {
x >>= 32;
result += 32;
}
if (x >= 0x10000) {
x >>= 16;
result += 16;
}
if (x >= 0x100) {
x >>= 8;
result += 8;
}
if (x >= 0x10) {
x >>= 4;
result += 4;
}
if (x >= 0x4) {
x >>= 2;
result += 2;
}
if (x >= 0x2) result += 1; // No need to shift x anymore
return result;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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.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: Apache-2.0
pragma solidity ^0.8.3;
import "./IERC20Ubiquity.sol";
/// @title UAD stablecoin interface
/// @author Ubiquity Algorithmic Dollar
interface IUbiquityAlgorithmicDollar is IERC20Ubiquity {
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
function setIncentiveContract(address account, address incentive) external;
function incentiveContract(address account) external view returns (address);
}
// SPDX-License-Identifier: MIT
// !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !!
pragma solidity ^0.8.3;
interface ICurveFactory {
event BasePoolAdded(address base_pool, address implementat);
event MetaPoolDeployed(
address coin,
address base_pool,
uint256 A,
uint256 fee,
address deployer
);
function find_pool_for_coins(address _from, address _to)
external
view
returns (address);
function find_pool_for_coins(
address _from,
address _to,
uint256 i
) external view returns (address);
function get_n_coins(address _pool)
external
view
returns (uint256, uint256);
function get_coins(address _pool) external view returns (address[2] memory);
function get_underlying_coins(address _pool)
external
view
returns (address[8] memory);
function get_decimals(address _pool)
external
view
returns (uint256[2] memory);
function get_underlying_decimals(address _pool)
external
view
returns (uint256[8] memory);
function get_rates(address _pool) external view returns (uint256[2] memory);
function get_balances(address _pool)
external
view
returns (uint256[2] memory);
function get_underlying_balances(address _pool)
external
view
returns (uint256[8] memory);
function get_A(address _pool) external view returns (uint256);
function get_fees(address _pool) external view returns (uint256, uint256);
function get_admin_balances(address _pool)
external
view
returns (uint256[2] memory);
function get_coin_indices(
address _pool,
address _from,
address _to
)
external
view
returns (
int128,
int128,
bool
);
function add_base_pool(
address _base_pool,
address _metapool_implementation,
address _fee_receiver
) external;
function deploy_metapool(
address _base_pool,
string memory _name,
string memory _symbol,
address _coin,
uint256 _A,
uint256 _fee
) external returns (address);
function commit_transfer_ownership(address addr) external;
function accept_transfer_ownership() external;
function set_fee_receiver(address _base_pool, address _fee_receiver)
external;
function convert_fees() external returns (bool);
function admin() external view returns (address);
function future_admin() external view returns (address);
function pool_list(uint256 arg0) external view returns (address);
function pool_count() external view returns (uint256);
function base_pool_list(uint256 arg0) external view returns (address);
function base_pool_count() external view returns (uint256);
function fee_receiver(address arg0) external view returns (address);
}
// SPDX-License-Identifier: UNLICENSED
// !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !!
pragma solidity ^0.8.3;
interface IMetaPool {
event Transfer(
address indexed sender,
address indexed receiver,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event TokenExchange(
address indexed buyer,
int128 sold_id,
uint256 tokens_sold,
int128 bought_id,
uint256 tokens_bought
);
event TokenExchangeUnderlying(
address indexed buyer,
int128 sold_id,
uint256 tokens_sold,
int128 bought_id,
uint256 tokens_bought
);
event AddLiquidity(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 invariant,
uint256 token_supply
);
event RemoveLiquidity(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 token_supply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 token_amount,
uint256 coin_amount,
uint256 token_supply
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 invariant,
uint256 token_supply
);
event CommitNewAdmin(uint256 indexed deadline, address indexed admin);
event NewAdmin(address indexed admin);
event CommitNewFee(
uint256 indexed deadline,
uint256 fee,
uint256 admin_fee
);
event NewFee(uint256 fee, uint256 admin_fee);
event RampA(
uint256 old_A,
uint256 new_A,
uint256 initial_time,
uint256 future_time
);
event StopRampA(uint256 A, uint256 t);
function initialize(
string memory _name,
string memory _symbol,
address _coin,
uint256 _decimals,
uint256 _A,
uint256 _fee,
address _admin
) external;
function decimals() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function get_previous_balances() external view returns (uint256[2] memory);
function get_balances() external view returns (uint256[2] memory);
function get_twap_balances(
uint256[2] memory _first_balances,
uint256[2] memory _last_balances,
uint256 _time_elapsed
) external view returns (uint256[2] memory);
function get_price_cumulative_last()
external
view
returns (uint256[2] memory);
function admin_fee() external view returns (uint256);
function A() external view returns (uint256);
function A_precise() external view returns (uint256);
function get_virtual_price() external view returns (uint256);
function calc_token_amount(uint256[2] memory _amounts, bool _is_deposit)
external
view
returns (uint256);
function calc_token_amount(
uint256[2] memory _amounts,
bool _is_deposit,
bool _previous
) external view returns (uint256);
function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount)
external
returns (uint256);
function add_liquidity(
uint256[2] memory _amounts,
uint256 _min_mint_amount,
address _receiver
) external returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx,
uint256[2] memory _balances
) external view returns (uint256);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx,
uint256[2] memory _balances
) external view returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address _receiver
) external returns (uint256);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address _receiver
) external returns (uint256);
function remove_liquidity(
uint256 _burn_amount,
uint256[2] memory _min_amounts
) external returns (uint256[2] memory);
function remove_liquidity(
uint256 _burn_amount,
uint256[2] memory _min_amounts,
address _receiver
) external returns (uint256[2] memory);
function remove_liquidity_imbalance(
uint256[2] memory _amounts,
uint256 _max_burn_amount
) external returns (uint256);
function remove_liquidity_imbalance(
uint256[2] memory _amounts,
uint256 _max_burn_amount,
address _receiver
) external returns (uint256);
function calc_withdraw_one_coin(uint256 _burn_amount, int128 i)
external
view
returns (uint256);
function calc_withdraw_one_coin(
uint256 _burn_amount,
int128 i,
bool _previous
) external view returns (uint256);
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received
) external returns (uint256);
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received,
address _receiver
) external returns (uint256);
function ramp_A(uint256 _future_A, uint256 _future_time) external;
function stop_ramp_A() external;
function admin_balances(uint256 i) external view returns (uint256);
function withdraw_admin_fees() external;
function admin() external view returns (address);
function coins(uint256 arg0) external view returns (address);
function balances(uint256 arg0) external view returns (uint256);
function fee() external view returns (uint256);
function block_timestamp_last() external view returns (uint256);
function initial_A() external view returns (uint256);
function future_A() external view returns (uint256);
function initial_A_time() external view returns (uint256);
function future_A_time() external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function balanceOf(address arg0) external view returns (uint256);
function allowance(address arg0, address arg1)
external
view
returns (uint256);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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: Apache-2.0
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title ERC20 Ubiquiti preset interface
/// @author Ubiquity Algorithmic Dollar
interface IERC20Ubiquity is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(address indexed _burned, uint256 _amount);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
}
// 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);
}
|
Convert quadruple precision number into octuple precision number. x quadruple precision number return octuple precision number/
|
function toOctuple(bytes16 x) internal pure returns (bytes32) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 result = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF)
else if (exponent == 0) {
if (result > 0) {
uint256 msb = mostSignificantBit(result);
result =
(result << (236 - msb)) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 245649 + msb;
}
result <<= 124;
exponent += 245760;
}
result |= exponent << 236;
if (uint128(x) >= 0x80000000000000000000000000000000)
result |= 0x8000000000000000000000000000000000000000000000000000000000000000;
return bytes32(result);
}
}
| 96,091 |
./partial_match/1/0xe612636BF13650B0C9d46d58f94e973809f252ed/sources/Staker.sol
|
Pauses all token transfers. See {ERC20Pausable} and {Pausable-_pause}. Requirements: - the caller must have the `PAUSER_ROLE`./
|
function pause() public {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have pauser role to pause"
);
_pause();
}
| 3,669,748 |
pragma solidity ^0.4.25;
/*
* @title: SafeMath
* @dev: Helper contract functions to arithmatic operations safely.
*/
contract SafeMath {
function Sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function Add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
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;
}
}
/*
* @title: Token
* @dev: Interface contract for ERC20 tokens
*/
contract Token {
function totalSupply() public view returns (uint256 supply);
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 (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/*
* @title: Staking
* @author BlockBank (https://www.blockbank.co.kr)
*/
contract Staking is SafeMath
{
// _prAddress: ERC20 contract address
// msg.sender: owner && operator
constructor(address _prAddress) public
{
owner = msg.sender;
operator = owner;
prAddress = _prAddress;
isContractUse = true;
}
address public owner;
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
address public operator;
// Functions with this modifier can only be executed by the operator
modifier onlyOperator() {
require(msg.sender == operator);
_;
}
function transferOperator(address _operator) onlyOwner public {
operator = _operator;
}
bool public isContractUse;
// Functions with this modifier can only be executed when this contract is not abandoned
modifier onlyContractUse {
require(isContractUse == true);
_;
}
function SetContractUse(bool _isContractUse) onlyOperator public{
isContractUse = _isContractUse;
}
uint32 public lastAcccountId;
mapping (uint32 => address) id_account;
mapping (uint32 => bool) accountId_freeze;
mapping (address => uint32) account_id;
// Find or add account
function FindOrAddAccount(address findAddress) private returns (uint32)
{
if (account_id[findAddress] == 0)
{
account_id[findAddress] = ++lastAcccountId;
id_account[lastAcccountId] = findAddress;
}
return account_id[findAddress];
}
// Find or revert account
function FindOrRevertAccount() private view returns (uint32)
{
uint32 accountId = account_id[msg.sender];
require(accountId != 0);
return accountId;
}
// Get account id of msg sender
function GetMyAccountId() view public returns (uint32)
{
return account_id[msg.sender];
}
// Get account id of any users
function GetAccountId(address account) view public returns (uint32)
{
return account_id[account];
}
// Freeze or unfreez of account
function SetFreezeByAddress(bool isFreeze, address account) onlyOperator public
{
uint32 accountId = account_id[account];
if (accountId != 0)
{
accountId_freeze[accountId] = isFreeze;
}
}
function IsFreezeByAddress(address account) public view returns (bool)
{
uint32 accountId = account_id[account];
if (accountId != 0)
{
return accountId_freeze[accountId];
}
return false;
}
// reserved: Balance held up in orderBook
// available: Balance available for trade
struct Balance
{
uint256 available;
uint256 maturity;
}
struct ListItem
{
uint32 prev;
uint32 next;
}
mapping (uint32 => Balance) AccountId_Balance;
uint256 public totalBonus;
address public prAddress;
uint256 public interest6weeks; //bp
uint256 public interest12weeks; //bp
// set interst for each holding period: 6 / 12 weeks
function SetInterest(uint256 _interest6weeks, uint256 _interest12weeks) onlyOperator public
{
interest6weeks = _interest6weeks;
interest12weeks = _interest12weeks;
}
// deposit bonus to pay interest
function depositBonus(uint256 amount) onlyOwner public
{
require(Token(prAddress).transferFrom(msg.sender, this, amount));
totalBonus = Add(totalBonus, amount);
}
// withdraw bonus to owner account
function WithdrawBonus(uint256 amount) onlyOwner public
{
require(Token(prAddress).transfer(msg.sender, amount));
totalBonus = Sub(totalBonus, amount);
}
// Deposit ERC20's for saving
function storeToken6Weeks(uint256 amount) onlyContractUse public
{
uint32 accountId = FindOrAddAccount(msg.sender);
require(accountId_freeze[accountId] == false);
require(AccountId_Balance[accountId].available == 0);
require(Token(prAddress).transferFrom(msg.sender, this, amount));
uint256 interst = Mul(amount, interest6weeks) / 10000;
totalBonus = Sub(totalBonus, interst);
AccountId_Balance[accountId].available = Add(AccountId_Balance[accountId].available, amount + interst);
AccountId_Balance[accountId].maturity = now + 6 weeks;
}
// Deposit ERC20's for saving
function storeToken12Weeks(uint128 amount) onlyContractUse public
{
uint32 accountId = FindOrAddAccount(msg.sender);
require(accountId_freeze[accountId] == false);
require(AccountId_Balance[accountId].available == 0);
require(Token(prAddress).transferFrom(msg.sender, this, amount));
uint256 interst = Mul(amount, interest12weeks) / 10000;
totalBonus = Sub(totalBonus, interst);
AccountId_Balance[accountId].available = Add(AccountId_Balance[accountId].available, amount + interst);
AccountId_Balance[accountId].maturity = now + 12 weeks;
}
// Withdraw ERC20's to personal addresstrue
function withdrawToken() public
{
uint32 accountId = FindOrAddAccount(msg.sender);
require(AccountId_Balance[accountId].maturity < now);
uint256 amount = AccountId_Balance[accountId].available;
require(amount > 0);
AccountId_Balance[accountId].available = 0;
require(Token(prAddress).transfer(msg.sender, amount));
}
// Below two emergency functions will be never used in normal situations.
// These function is only prepared for emergency case such as smart contract hacking Vulnerability or smart contract abolishment
// Withdrawn fund by these function cannot belong to any operators or owners.
// Withdrawn fund should be distributed to individual accounts having original ownership of withdrawn fund.
function emergencyWithdrawalETH(uint256 amount) onlyOwner public
{
require(msg.sender.send(amount));
}
function emergencyWithdrawalToken(uint256 amount) onlyOwner public
{
Token(prAddress).transfer(msg.sender, amount);
}
function getMyBalance() view public returns (uint256 available, uint256 maturity)
{
uint32 accountId = FindOrRevertAccount();
available = AccountId_Balance[accountId].available;
maturity = AccountId_Balance[accountId].maturity;
}
function getTimeStamp() view public returns (uint256)
{
return now;
}
}
|
Withdraw ERC20's to personal addresstrue
|
function withdrawToken() public
{
uint32 accountId = FindOrAddAccount(msg.sender);
require(AccountId_Balance[accountId].maturity < now);
uint256 amount = AccountId_Balance[accountId].available;
require(amount > 0);
AccountId_Balance[accountId].available = 0;
require(Token(prAddress).transfer(msg.sender, amount));
}
| 12,826,072 |
pragma solidity ^0.4.18;
import "./ownership/Ownable.sol";
/**
* @title TrustFactory
* @author Nathan Glover
* @notice manages anything to do with the creation, deletion and modificaiton of charitable trusts.
*/
contract TrustFactory is Ownable {
/* Events */
event NewTrust(uint trustId);
event ChangedTrustAddress(uint trustId, address trustAddr);
/**
* @notice Throws if called by any account other then the owner
* of the trust being modified
*/
modifier onlyTrustOwner(uint _trustId) {
require(msg.sender == addressLookup[_trustId]);
_;
}
struct Trust {
// Allows a trust to be untrusted
bool trustEnabled;
// Trust address of the charity or org that put up
address trustAddress;
}
// Public array of all Trusts
Trust[] public trusts;
/* Mappings */
mapping (uint => address) addressLookup;
/**
* @notice Private trust creation that is handled internally
* @param _enabled Is the trust enabled
* @param _trustAddr The address to link this trust to
*/
function _createTrust(bool _enabled, address _trustAddr) internal {
// 'id' is the index of the trust in the array of trusts
uint id = trusts.push(Trust(_enabled, _trustAddr)) - 1;
// Map both the address to the trust
// and the trust to the address
addressLookup[id] = _trustAddr;
// Send an event alerting the Trusts creation
NewTrust(id);
}
/**
* @notice Allows the contract owner to add a new trust
* @param _trustAddr The address to link this trust to
*/
function createTrust(address _trustAddr) onlyOwner public {
_createTrust(true, _trustAddr);
}
/**
* @notice Allows the contract owner to enable and disable trusts
* @param _id The id of the trust that should be toggled
* @param _enabled A boolean true or false, where true is to enable
* and false is to disable the trust
*/
function toggleTrust(uint _id, bool _enabled) onlyOwner public {
trusts[_id].trustEnabled = _enabled;
}
/**
* @dev Allows a trust to change their address
* @param _id The id of the trust where the address wants to be altered;
* the msg.sender must match the address in the id being changed
* @param _newTrustAddr The new trust address to be set
*/
//
function changeTrustAddress(uint _id, address _newTrustAddr) onlyTrustOwner(_id) public {
trusts[_id].trustAddress = _newTrustAddr;
addressLookup[_id] = _newTrustAddr;
ChangedTrustAddress(_id, _newTrustAddr);
}
}
|
Private trust creation that is handled internally _enabled Is the trust enabled _trustAddr The address to link this trust to/ 'id' is the index of the trust in the array of trusts Map both the address to the trust and the trust to the address Send an event alerting the Trusts creation
|
function _createTrust(bool _enabled, address _trustAddr) internal {
uint id = trusts.push(Trust(_enabled, _trustAddr)) - 1;
addressLookup[id] = _trustAddr;
NewTrust(id);
}
| 5,469,414 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
import './TRKeys.sol';
/// @notice The Reliquary Grail of Light
library TRGrailLight {
function getElement() public pure returns (string memory) {
return 'Light';
}
function getPalette() public pure returns (string memory) {
return 'Pastel';
}
function getEssence() public pure returns (string memory) {
return 'Photonic';
}
function getStyle() public pure returns (string memory) {
return 'Pajamas';
}
function getSpeed() public pure returns (string memory) {
return 'Swift';
}
function getGravity() public pure returns (string memory) {
return 'Lunar';
}
function getDisplay() public pure returns (string memory) {
return 'Mirrored';
}
function getColorCount() public pure returns (uint256) {
return 5;
}
function getRelicType() public pure returns (string memory) {
return TRKeys.RELIC_TYPE_GRAIL;
}
function getRuneflux() public pure returns (uint256) {
return 420;
}
function getCorruption() public pure returns (uint256) {
return 888;
}
function getGlyph() public pure returns (uint256[] memory) {
uint256[] memory glyph = new uint256[](64);
glyph[0] = uint256(0);
glyph[1] = uint256(0);
glyph[2] = uint256(0);
glyph[3] = uint256(0);
glyph[4] = uint256(0);
glyph[5] = uint256(0);
glyph[6] = uint256(0);
glyph[7] = uint256(0);
glyph[8] = uint256(0);
glyph[9] = uint256(0);
glyph[10] = uint256(0);
glyph[11] = uint256(234554421000000000000000000000000000);
glyph[12] = uint256(135666666655310000000000000000000000000);
glyph[13] = uint256(3566667666665543000000000000000000000000);
glyph[14] = uint256(136666666655565555410000000000000000000000);
glyph[15] = uint256(2356666666555555555541000000000000000000000);
glyph[16] = uint256(23677877666655565555554100000000000000000000);
glyph[17] = uint256(246677766666666666555555410000000000000000000);
glyph[18] = uint256(1466666777777776666555555651000000000000000000);
glyph[19] = uint256(5566788888777776676665545555000000000000000000);
glyph[20] = uint256(33678888888777766666666655555300000000000000000);
glyph[21] = uint256(336788877777666666666666655554400000000000000000);
glyph[22] = uint256(5467777767667666666666666566555400000000000000000);
glyph[23] = uint256(6667766778888888887654578766556500000000000000000);
glyph[24] = uint256(6667777888888765543321112377666620000000000000000);
glyph[25] = uint256(18767788897866654433221111113766520000000000000000);
glyph[26] = uint256(68667788776789986433322111113458610000000000000000);
glyph[27] = uint256(18676786556566666763322111643246810000000000000000);
glyph[28] = uint256(7776855656665555544332111111115500000000000000000);
glyph[29] = uint256(4667624557678766544332111123216100000000000000000);
glyph[30] = uint256(574524568899999754332111578967200000000000000000);
glyph[31] = uint256(245424467868686484322117731568200000000000000000);
glyph[32] = uint256(55325476765556244321115331248100000000000000000);
glyph[33] = uint256(155325476766464343221112221357000000000000000000);
glyph[34] = uint256(256535576677664432211113411265000000000000000000);
glyph[35] = uint256(156545577654443222211111123173000000000000000000);
glyph[36] = uint256(35565687655433222231111111161000000000000000000);
glyph[37] = uint256(34455786555543333454111111140000000000000000000);
glyph[38] = uint256(94554876455555444454111111420000000000000000000);
glyph[39] = uint256(896544868445665555543111212720000000000000000000);
glyph[40] = uint256(4998557878645666655653322224810001220000000000000);
glyph[41] = uint256(19999467889865566667855633336534443210000000000000);
glyph[42] = uint256(89999466888986566667876644566600000000000000000000);
glyph[43] = uint256(299999456888998755667876654776755432210000000000000);
glyph[44] = uint256(999999566888998876567776556767610000130000000000000);
glyph[45] = uint256(4999956677888999877665665666757755000000000000000000);
glyph[46] = uint256(9998667777888899887766655666777756640000000000000000);
glyph[47] = uint256(49995667777787899887665564322587556665000000000000000);
glyph[48] = uint256(199926667676787799887654575321685575666400000000000000);
glyph[49] = uint256(156526667666787799887642454221274476677730000000000000);
glyph[50] = uint256(26677757687699876543664321164477777760000000000000);
glyph[51] = uint256(16677657677699876532565521154378888772000000000000);
glyph[52] = uint256(15777656676798876432455331153378888884000000000000);
glyph[53] = uint256(12778865566798876422465431182458888885100000000000);
glyph[54] = uint256(112488885555798876422455432194527889996200000000000);
glyph[55] = uint256(123388885545788765432356432288343788886200000000000);
glyph[56] = uint256(123458886544676554322367777669642578885210000000000);
glyph[57] = uint256(1234457888644565443322278887448935278874210000000000);
glyph[58] = uint256(11234455889543654333322222222237937368873111000000000);
glyph[59] = uint256(12234555689653774333333443333357948648982112000000000);
glyph[60] = uint256(12334455689853777644444333322223778847971112100000000);
glyph[61] = uint256(12344455669944777665444333322223458874971111100000000);
glyph[62] = uint256(112344555668756776644444333322222334885861111210000000);
glyph[63] = uint256(122344555666477776444444333322222223588651111210000000);
return glyph;
}
function getDescription() public pure returns (string memory) {
return "The Grail of Light. There is no time. Now is forever. Just a photon's leap away.";
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
import './TRUtils.sol';
/// @notice The Reliquary Constants
library TRKeys {
struct RuneCore {
uint256 tokenId;
uint8 level;
uint32 mana;
bool isDivinityQuestLoot;
bool isSecretDiscovered;
uint8 secretsDiscovered;
uint256 runeCode;
string runeHash;
string transmutation;
address credit;
uint256[] glyph;
uint24[] colors;
address metadataAddress;
string hiddenLeyLines;
}
uint256 public constant FIRST_OPEN_VIBES_ID = 7778;
address public constant VIBES_GENESIS = 0x6c7C97CaFf156473F6C9836522AE6e1d6448Abe7;
address public constant VIBES_OPEN = 0xF3FCd0F025c21F087dbEB754516D2AD8279140Fc;
uint8 public constant CURIO_SUPPLY = 64;
uint256 public constant CURIO_TITHE = 80000000000000000; // 0.08 ETH
uint32 public constant MANA_PER_YEAR = 100;
uint32 public constant MANA_PER_YEAR_LV2 = 150;
uint32 public constant SECONDS_PER_YEAR = 31536000;
uint32 public constant MANA_FROM_REVELATION = 50;
uint32 public constant MANA_FROM_DIVINATION = 50;
uint32 public constant MANA_FROM_VIBRATION = 100;
uint32 public constant MANA_COST_TO_UPGRADE = 150;
uint256 public constant RELIC_SIZE = 64;
uint256 public constant RELIC_SUPPLY = 1047;
uint256 public constant TOTAL_SUPPLY = CURIO_SUPPLY + RELIC_SUPPLY;
uint256 public constant RELIC_TITHE = 150000000000000000; // 0.15 ETH
uint256 public constant INVENTORY_CAPACITY = 10;
uint256 public constant BYTES_PER_RELICHASH = 3;
uint256 public constant BYTES_PER_BLOCKHASH = 32;
uint256 public constant HALF_POSSIBILITY_SPACE = (16**6) / 2;
bytes32 public constant RELICHASH_MASK = 0x0000000000000000000000000000000000000000000000000000000000ffffff;
uint256 public constant RELIC_DISCOUNT_GENESIS = 120000000000000000; // 0.12 ETH
uint256 public constant RELIC_DISCOUNT_OPEN = 50000000000000000; // 0.05 ETH
uint256 public constant RELIQUARY_CHAMBER_OUTSIDE = 0;
uint256 public constant RELIQUARY_CHAMBER_GUARDIANS_HALL = 1;
uint256 public constant RELIQUARY_CHAMBER_INNER_SANCTUM = 2;
uint256 public constant RELIQUARY_CHAMBER_DIVINITYS_END = 3;
uint256 public constant RELIQUARY_CHAMBER_CHAMPIONS_VAULT = 4;
uint256 public constant ELEMENTAL_GUARDIAN_DNA = 88888888;
uint256 public constant GRAIL_ID_NONE = 0;
uint256 public constant GRAIL_ID_NATURE = 1;
uint256 public constant GRAIL_ID_LIGHT = 2;
uint256 public constant GRAIL_ID_WATER = 3;
uint256 public constant GRAIL_ID_EARTH = 4;
uint256 public constant GRAIL_ID_WIND = 5;
uint256 public constant GRAIL_ID_ARCANE = 6;
uint256 public constant GRAIL_ID_SHADOW = 7;
uint256 public constant GRAIL_ID_FIRE = 8;
uint256 public constant GRAIL_COUNT = 8;
uint256 public constant GRAIL_DISTRIBUTION = 100;
uint8 public constant SECRETS_OF_THE_GRAIL = 128;
uint8 public constant MODE_TRANSMUTE_ELEMENT = 1;
uint8 public constant MODE_CREATE_GLYPH = 2;
uint8 public constant MODE_IMAGINE_COLORS = 3;
uint256 public constant MAX_COLOR_INTS = 10;
string public constant ROLL_ELEMENT = 'ELEMENT';
string public constant ROLL_PALETTE = 'PALETTE';
string public constant ROLL_SHUFFLE = 'SHUFFLE';
string public constant ROLL_RED = 'RED';
string public constant ROLL_GREEN = 'GREEN';
string public constant ROLL_BLUE = 'BLUE';
string public constant ROLL_REDSIGN = 'REDSIGN';
string public constant ROLL_GREENSIGN = 'GREENSIGN';
string public constant ROLL_BLUESIGN = 'BLUESIGN';
string public constant ROLL_RANDOMCOLOR = 'RANDOMCOLOR';
string public constant ROLL_RELICTYPE = 'RELICTYPE';
string public constant ROLL_STYLE = 'STYLE';
string public constant ROLL_COLORCOUNT = 'COLORCOUNT';
string public constant ROLL_SPEED = 'SPEED';
string public constant ROLL_GRAVITY = 'GRAVITY';
string public constant ROLL_DISPLAY = 'DISPLAY';
string public constant ROLL_GRAILS = 'GRAILS';
string public constant ROLL_RUNEFLUX = 'RUNEFLUX';
string public constant ROLL_CORRUPTION = 'CORRUPTION';
string public constant RELIC_TYPE_GRAIL = 'Grail';
string public constant RELIC_TYPE_CURIO = 'Curio';
string public constant RELIC_TYPE_FOCUS = 'Focus';
string public constant RELIC_TYPE_AMULET = 'Amulet';
string public constant RELIC_TYPE_TALISMAN = 'Talisman';
string public constant RELIC_TYPE_TRINKET = 'Trinket';
string public constant GLYPH_TYPE_GRAIL = 'Origin';
string public constant GLYPH_TYPE_CUSTOM = 'Divine';
string public constant GLYPH_TYPE_NONE = 'None';
string public constant ELEM_NATURE = 'Nature';
string public constant ELEM_LIGHT = 'Light';
string public constant ELEM_WATER = 'Water';
string public constant ELEM_EARTH = 'Earth';
string public constant ELEM_WIND = 'Wind';
string public constant ELEM_ARCANE = 'Arcane';
string public constant ELEM_SHADOW = 'Shadow';
string public constant ELEM_FIRE = 'Fire';
string public constant ANY_PAL_CUSTOM = 'Divine';
string public constant NAT_PAL_JUNGLE = 'Jungle';
string public constant NAT_PAL_CAMOUFLAGE = 'Camouflage';
string public constant NAT_PAL_BIOLUMINESCENCE = 'Bioluminescence';
string public constant NAT_ESS_FOREST = 'Forest';
string public constant NAT_ESS_LIFE = 'Life';
string public constant NAT_ESS_SWAMP = 'Swamp';
string public constant NAT_ESS_WILDBLOOD = 'Wildblood';
string public constant NAT_ESS_SOUL = 'Soul';
string public constant LIG_PAL_PASTEL = 'Pastel';
string public constant LIG_PAL_INFRARED = 'Infrared';
string public constant LIG_PAL_ULTRAVIOLET = 'Ultraviolet';
string public constant LIG_ESS_HEAVENLY = 'Heavenly';
string public constant LIG_ESS_FAE = 'Fae';
string public constant LIG_ESS_PRISMATIC = 'Prismatic';
string public constant LIG_ESS_RADIANT = 'Radiant';
string public constant LIG_ESS_PHOTONIC = 'Photonic';
string public constant WAT_PAL_FROZEN = 'Frozen';
string public constant WAT_PAL_DAWN = 'Dawn';
string public constant WAT_PAL_OPALESCENT = 'Opalescent';
string public constant WAT_ESS_TIDAL = 'Tidal';
string public constant WAT_ESS_ARCTIC = 'Arctic';
string public constant WAT_ESS_STORM = 'Storm';
string public constant WAT_ESS_ILLUVIAL = 'Illuvial';
string public constant WAT_ESS_UNDINE = 'Undine';
string public constant EAR_PAL_COAL = 'Coal';
string public constant EAR_PAL_SILVER = 'Silver';
string public constant EAR_PAL_GOLD = 'Gold';
string public constant EAR_ESS_MINERAL = 'Mineral';
string public constant EAR_ESS_CRAGGY = 'Craggy';
string public constant EAR_ESS_DWARVEN = 'Dwarven';
string public constant EAR_ESS_GNOMIC = 'Gnomic';
string public constant EAR_ESS_CRYSTAL = 'Crystal';
string public constant WIN_PAL_BERRY = 'Berry';
string public constant WIN_PAL_THUNDER = 'Thunder';
string public constant WIN_PAL_AERO = 'Aero';
string public constant WIN_ESS_SYLPHIC = 'Sylphic';
string public constant WIN_ESS_VISCERAL = 'Visceral';
string public constant WIN_ESS_FROSTED = 'Frosted';
string public constant WIN_ESS_ELECTRIC = 'Electric';
string public constant WIN_ESS_MAGNETIC = 'Magnetic';
string public constant ARC_PAL_FROSTFIRE = 'Frostfire';
string public constant ARC_PAL_COSMIC = 'Cosmic';
string public constant ARC_PAL_COLORLESS = 'Colorless';
string public constant ARC_ESS_MAGIC = 'Magic';
string public constant ARC_ESS_ASTRAL = 'Astral';
string public constant ARC_ESS_FORBIDDEN = 'Forbidden';
string public constant ARC_ESS_RUNIC = 'Runic';
string public constant ARC_ESS_UNKNOWN = 'Unknown';
string public constant SHA_PAL_DARKNESS = 'Darkness';
string public constant SHA_PAL_VOID = 'Void';
string public constant SHA_PAL_UNDEAD = 'Undead';
string public constant SHA_ESS_NIGHT = 'Night';
string public constant SHA_ESS_FORGOTTEN = 'Forgotten';
string public constant SHA_ESS_ABYSSAL = 'Abyssal';
string public constant SHA_ESS_EVIL = 'Evil';
string public constant SHA_ESS_LOST = 'Lost';
string public constant FIR_PAL_HEAT = 'Heat';
string public constant FIR_PAL_EMBER = 'Ember';
string public constant FIR_PAL_CORRUPTED = 'Corrupted';
string public constant FIR_ESS_INFERNAL = 'Infernal';
string public constant FIR_ESS_MOLTEN = 'Molten';
string public constant FIR_ESS_ASHEN = 'Ashen';
string public constant FIR_ESS_DRACONIC = 'Draconic';
string public constant FIR_ESS_CELESTIAL = 'Celestial';
string public constant STYLE_SMOOTH = 'Smooth';
string public constant STYLE_PAJAMAS = 'Pajamas';
string public constant STYLE_SILK = 'Silk';
string public constant STYLE_SKETCH = 'Sketch';
string public constant SPEED_ZEN = 'Zen';
string public constant SPEED_TRANQUIL = 'Tranquil';
string public constant SPEED_NORMAL = 'Normal';
string public constant SPEED_FAST = 'Fast';
string public constant SPEED_SWIFT = 'Swift';
string public constant SPEED_HYPER = 'Hyper';
string public constant GRAV_LUNAR = 'Lunar';
string public constant GRAV_ATMOSPHERIC = 'Atmospheric';
string public constant GRAV_LOW = 'Low';
string public constant GRAV_NORMAL = 'Normal';
string public constant GRAV_HIGH = 'High';
string public constant GRAV_MASSIVE = 'Massive';
string public constant GRAV_STELLAR = 'Stellar';
string public constant GRAV_GALACTIC = 'Galactic';
string public constant DISPLAY_NORMAL = 'Normal';
string public constant DISPLAY_MIRRORED = 'Mirrored';
string public constant DISPLAY_UPSIDEDOWN = 'UpsideDown';
string public constant DISPLAY_MIRROREDUPSIDEDOWN = 'MirroredUpsideDown';
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
/// @notice The Reliquary Utility Methods
library TRUtils {
function random(string memory input) public pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function getColorCode(uint256 color) public pure returns (string memory) {
bytes16 hexChars = '0123456789abcdef';
uint256 r1 = (color >> uint256(20)) & uint256(15);
uint256 r2 = (color >> uint256(16)) & uint256(15);
uint256 g1 = (color >> uint256(12)) & uint256(15);
uint256 g2 = (color >> uint256(8)) & uint256(15);
uint256 b1 = (color >> uint256(4)) & uint256(15);
uint256 b2 = color & uint256(15);
bytes memory code = new bytes(6);
code[0] = hexChars[r1];
code[1] = hexChars[r2];
code[2] = hexChars[g1];
code[3] = hexChars[g2];
code[4] = hexChars[b1];
code[5] = hexChars[b2];
return string(code);
}
function compare(string memory a, string memory b) public pure returns (bool) {
if (bytes(a).length != bytes(b).length) {
return false;
} else {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
function toString(uint256 value) public 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);
}
// https://ethereum.stackexchange.com/a/8447
function toAsciiString(address x) public pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
function char(bytes1 b) internal pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
// https://stackoverflow.com/a/69302348/424107
function toCapsHexString(uint256 i) internal pure returns (string memory) {
if (i == 0) return '0';
uint j = i;
uint length;
while (j != 0) {
length++;
j = j >> 4;
}
uint mask = 15;
bytes memory bstr = new bytes(length);
uint k = length;
while (i != 0) {
uint curr = (i & mask);
bstr[--k] = curr > 9 ?
bytes1(uint8(55 + curr)) :
bytes1(uint8(48 + curr)); // 55 = 65 - 10
i = i >> 4;
}
return string(bstr);
}
}
|
Inspired by OraclizeAPI's implementation - MIT license https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
|
function toString(uint256 value) public 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);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
| 136,665 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 128 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
}
// SPDX-License-Identifier: UNLICENSED
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity 0.8.11;
library BytesLib {
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IIdleToken {
function decimals() external view returns (uint8);
function getGovTokens() external view returns (address[] memory);
function tokenPriceWithFee(address user) external view returns (uint256);
function balanceOf(address user) external view returns (uint256);
function redeemIdleToken(uint256 amount) external;
function mintIdleToken(
uint256 amount,
bool,
address referral
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import './IV2SwapRouter.sol';
import './IV3SwapRouter.sol';
/// @title Router token swapping functionality
interface ISwapRouter02 is IV2SwapRouter, IV3SwapRouter {
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V2
interface IV2SwapRouter {
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param amountIn The amount of token to swap
/// @param amountOutMin The minimum amount of output that must be received
/// @param path The ordered list of tokens to swap through
/// @param to The recipient address
/// @return amountOut The amount of the received token
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to
) external payable returns (uint256 amountOut);
/// @notice Swaps as little as possible of one token for an exact amount of another token
/// @param amountOut The amount of token to swap for
/// @param amountInMax The maximum amount of input that the caller will pay
/// @param path The ordered list of tokens to swap through
/// @param to The recipient address
/// @return amountIn The amount of token to pay
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to
) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IV3SwapRouter{
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// that may remain in the router after the swap.
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// that may remain in the router after the swap.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../external/@openzeppelin/token/ERC20/IERC20.sol";
import "./ISwapData.sol";
interface IBaseStrategy {
function underlying() external view returns (IERC20);
function getStrategyBalance() external view returns (uint128);
function getStrategyUnderlyingWithRewards() external view returns(uint128);
function process(uint256[] calldata, bool, SwapData[] calldata) external;
function processReallocation(uint256[] calldata, ProcessReallocationData calldata) external returns(uint128);
function processDeposit(uint256[] calldata) external;
function fastWithdraw(uint128, uint256[] calldata, SwapData[] calldata) external returns(uint128);
function claimRewards(SwapData[] calldata) external;
function emergencyWithdraw(address recipient, uint256[] calldata data) external;
function initialize() external;
function disable() external;
}
struct ProcessReallocationData {
uint128 sharesToWithdraw;
uint128 optimizedShares;
uint128 optimizedWithdrawnAmount;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
/**
* @notice Strict holding information how to swap the asset
* @member slippage minumum output amount
* @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path
*/
struct SwapData {
uint256 slippage; // min amount out
bytes path; // 1st byte is action, then path
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../external/@openzeppelin/utils/SafeCast.sol";
/**
* @notice A collection of custom math ustils used throughout the system
*/
library Math {
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? b : a;
}
function getProportion128(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) {
return SafeCast.toUint128(((mul1 * mul2) / div));
}
function getProportion128Unchecked(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) {
unchecked {
return uint128((mul1 * mul2) / div);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
/** @notice Handle setting zero value in a storage word as uint128 max value.
*
* @dev
* The purpose of this is to avoid resetting a storage word to the zero value;
* the gas cost of re-initializing the value is the same as setting the word originally.
* so instead, if word is to be set to zero, we set it to uint128 max.
*
* - anytime a word is loaded from storage: call "get"
* - anytime a word is written to storage: call "set"
* - common operations on uints are also bundled here.
*
* NOTE: This library should ONLY be used when reading or writing *directly* from storage.
*/
library Max128Bit {
uint128 internal constant ZERO = type(uint128).max;
function get(uint128 a) internal pure returns(uint128) {
return (a == ZERO) ? 0 : a;
}
function set(uint128 a) internal pure returns(uint128){
return (a == 0) ? ZERO : a;
}
function add(uint128 a, uint128 b) internal pure returns(uint128 c){
a = get(a);
c = set(a + b);
}
}
// SPDX-License-Identifier: BUSL-1.1
import "../interfaces/ISwapData.sol";
pragma solidity 0.8.11;
/// @notice Strategy struct for all strategies
struct Strategy {
uint128 totalShares;
/// @notice Denotes strategy completed index
uint24 index;
/// @notice Denotes whether strategy is removed
/// @dev after removing this value can never change, hence strategy cannot be added back again
bool isRemoved;
/// @notice Pending geposit amount and pending shares withdrawn by all users for next index
Pending pendingUser;
/// @notice Used if strategies "dohardwork" hasn't been executed yet in the current index
Pending pendingUserNext;
/// @dev Usually a temp variable when compounding
mapping(address => uint256) pendingRewards;
/// @dev Usually a temp variable when compounding
uint128 pendingDepositReward;
/// @notice Amount of lp tokens the strategy holds, NOTE: not all strategies use it
uint256 lpTokens;
// ----- REALLOCATION VARIABLES -----
bool isInDepositPhase;
/// @notice Used to store amount of optimized shares, so they can be substracted at the end
/// @dev Only for temporary use, should be reset to 0 in same transaction
uint128 optimizedSharesWithdrawn;
/// @dev Underlying amount pending to be deposited from other strategies at reallocation
/// @dev resets after the strategy reallocation DHW is finished
uint128 pendingReallocateDeposit;
/// @notice Stores amount of optimized underlying amount when reallocating
/// @dev resets after the strategy reallocation DHW is finished
/// @dev This is "virtual" amount that was matched between this strategy and others when reallocating
uint128 pendingReallocateOptimizedDeposit;
// ------------------------------------
/// @notice Total underlying amoung at index
mapping(uint256 => TotalUnderlying) totalUnderlying;
/// @notice Batches stored after each DHW with index as a key
/// @dev Holds information for vauls to redeem newly gained shares and withdrawn amounts belonging to users
mapping(uint256 => Batch) batches;
/// @notice Batches stored after each DHW reallocating (if strategy was set to reallocate)
/// @dev Holds information for vauls to redeem newly gained shares and withdrawn shares to complete reallocation
mapping(uint256 => BatchReallocation) reallocationBatches;
/// @notice Vaults holding this strategy shares
mapping(address => Vault) vaults;
/// @notice Future proof storage
mapping(bytes32 => AdditionalStorage) additionalStorage;
/// @dev Make sure to reset it to 0 after emergency withdrawal
uint256 emergencyPending;
}
/// @notice Unprocessed deposit underlying amount and strategy share amount from users
struct Pending {
uint128 deposit;
uint128 sharesToWithdraw;
}
/// @notice Struct storing total underlying balance of a strategy for an index, along with total shares at same index
struct TotalUnderlying {
uint128 amount;
uint128 totalShares;
}
/// @notice Stored after executing DHW for each index.
/// @dev This is used for vaults to redeem their deposit.
struct Batch {
/// @notice total underlying deposited in index
uint128 deposited;
uint128 depositedReceived;
uint128 depositedSharesReceived;
uint128 withdrawnShares;
uint128 withdrawnReceived;
}
/// @notice Stored after executing reallocation DHW each index.
struct BatchReallocation {
/// @notice Deposited amount received from reallocation
uint128 depositedReallocation;
/// @notice Received shares from reallocation
uint128 depositedReallocationSharesReceived;
/// @notice Used to know how much tokens was received for reallocating
uint128 withdrawnReallocationReceived;
/// @notice Amount of shares to withdraw for reallocation
uint128 withdrawnReallocationShares;
}
/// @notice VaultBatches could be refactored so we only have 2 structs current and next (see how Pending is working)
struct Vault {
uint128 shares;
/// @notice Withdrawn amount as part of the reallocation
uint128 withdrawnReallocationShares;
/// @notice Index to action
mapping(uint256 => VaultBatch) vaultBatches;
}
/// @notice Stores deposited and withdrawn shares by the vault
struct VaultBatch {
/// @notice Vault index to deposited amount mapping
uint128 deposited;
/// @notice Vault index to withdrawn user shares mapping
uint128 withdrawnShares;
}
/// @notice Used for reallocation calldata
struct VaultData {
address vault;
uint8 strategiesCount;
uint256 strategiesBitwise;
uint256 newProportions;
}
/// @notice Calldata when executing reallocatin DHW
/// @notice Used in the withdraw part of the reallocation DHW
struct ReallocationWithdrawData {
uint256[][] reallocationTable;
StratUnderlyingSlippage[] priceSlippages;
RewardSlippages[] rewardSlippages;
uint256[] stratIndexes;
uint256[][] slippages;
}
/// @notice Calldata when executing reallocatin DHW
/// @notice Used in the deposit part of the reallocation DHW
struct ReallocationData {
uint256[] stratIndexes;
uint256[][] slippages;
}
/// @notice In case some adapters need extra storage
struct AdditionalStorage {
uint256 value;
address addressValue;
uint96 value96;
}
/// @notice Strategy total underlying slippage, to verify validity of the strategy state
struct StratUnderlyingSlippage {
uint128 min;
uint128 max;
}
/// @notice Containig information if and how to swap strategy rewards at the DHW
/// @dev Passed in by the do-hard-worker
struct RewardSlippages {
bool doClaim;
SwapData[] swapData;
}
/// @notice Helper struct to compare strategy share between eachother
/// @dev Used for reallocation optimization of shares (strategy matching deposits and withdrawals between eachother when reallocating)
struct PriceData {
uint128 totalValue;
uint128 totalShares;
}
/// @notice Strategy reallocation values after reallocation optimization of shares was calculated
struct ReallocationShares {
uint128[] optimizedWithdraws;
uint128[] optimizedShares;
uint128[] totalSharesWithdrawn;
}
/// @notice Shared storage for multiple strategies
/// @dev This is used when strategies are part of the same proticil (e.g. Curve 3pool)
struct StrategiesShared {
uint184 value;
uint32 lastClaimBlock;
uint32 lastUpdateBlock;
uint8 stratsCount;
mapping(uint256 => address) stratAddresses;
mapping(bytes32 => uint256) bytesValues;
}
/// @notice Base storage shared betweek Spool contract and Strategies
/// @dev this way we can use same values when performing delegate call
/// to strategy implementations from the Spool contract
abstract contract BaseStorage {
// ----- DHW VARIABLES -----
/// @notice Force while DHW (all strategies) to be executed in only one transaction
/// @dev This is enforced to increase the gas efficiency of the system
/// Can be removed by the DAO if gas gost of the strategies goes over the block limit
bool internal forceOneTxDoHardWork;
/// @notice Global index of the system
/// @dev Insures the correct strategy DHW execution.
/// Every strategy in the system must be equal or one less than global index value
/// Global index increments by 1 on every do-hard-work
uint24 public globalIndex;
/// @notice number of strategies unprocessed (by the do-hard-work) in the current index to be completed
uint8 internal doHardWorksLeft;
// ----- REALLOCATION VARIABLES -----
/// @notice Used for offchain execution to get the new reallocation table.
bool internal logReallocationTable;
/// @notice number of withdrawal strategies unprocessed (by the do-hard-work) in the current index
/// @dev only used when reallocating
/// after it reaches 0, deposit phase of the reallocation can begin
uint8 public withdrawalDoHardWorksLeft;
/// @notice Index at which next reallocation is set
uint24 public reallocationIndex;
/// @notice 2D table hash containing information of how strategies should be reallocated between eachother
/// @dev Created when allocation provider sets reallocation for the vaults
/// This table is stored as a hash in the system and verified on reallocation DHW
/// Resets to 0 after reallocation DHW is completed
bytes32 internal reallocationTableHash;
/// @notice Hash of all the strategies array in the system at the time when reallocation was set for index
/// @dev this array is used for the whole reallocation period even if a strategy gets exploited when reallocating.
/// This way we can remove the strategy from the system and not breaking the flow of the reallocaton
/// Resets when DHW is completed
bytes32 internal reallocationStrategiesHash;
// -----------------------------------
/// @notice Denoting if an address is the do-hard-worker
mapping(address => bool) public isDoHardWorker;
/// @notice Denoting if an address is the allocation provider
mapping(address => bool) public isAllocationProvider;
/// @notice Strategies shared storage
/// @dev used as a helper storage to save common inoramation
mapping(bytes32 => StrategiesShared) internal strategiesShared;
/// @notice Mapping of strategy implementation address to strategy system values
mapping(address => Strategy) public strategies;
/// @notice Flag showing if disable was skipped when a strategy has been removed
/// @dev If true disable can still be run
mapping(address => bool) internal _skippedDisable;
/// @notice Flag showing if after removing a strategy emergency withdraw can still be executed
/// @dev If true emergency withdraw can still be executed
mapping(address => bool) internal _awaitingEmergencyWithdraw;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../external/@openzeppelin/token/ERC20/IERC20.sol";
/// @title Common Spool contracts constants
abstract contract BaseConstants {
/// @dev 2 digits precision
uint256 internal constant FULL_PERCENT = 100_00;
/// @dev Accuracy when doing shares arithmetics
uint256 internal constant ACCURACY = 10**30;
}
/// @title Contains USDC token related values
abstract contract USDC {
/// @notice USDC token contract address
IERC20 internal constant USDC_ADDRESS = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../external/GNSPS-solidity-bytes-utils/BytesLib.sol";
import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol";
import "../external/uniswap/interfaces/ISwapRouter02.sol";
import "../interfaces/ISwapData.sol";
/// @notice Denotes swap action mode
enum SwapAction {
NONE,
UNI_V2_DIRECT,
UNI_V2_WETH,
UNI_V2,
UNI_V3_DIRECT,
UNI_V3_WETH,
UNI_V3
}
/// @title Contains logic facilitating swapping using Uniswap
abstract contract SwapHelper {
using BytesLib for bytes;
using SafeERC20 for IERC20;
/// @dev The length of the bytes encoded swap action
uint256 private constant ACTION_SIZE = 1;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev Maximum V2 path length (4 swaps)
uint256 private constant MAX_V2_PATH = ADDR_SIZE * 3;
/// @dev V3 WETH path length
uint256 private constant WETH_V3_PATH_SIZE = FEE_SIZE + FEE_SIZE;
/// @dev Minimum V3 custom path length (2 swaps)
uint256 private constant MIN_V3_PATH = FEE_SIZE + NEXT_OFFSET;
/// @dev Maximum V3 path length (4 swaps)
uint256 private constant MAX_V3_PATH = FEE_SIZE + NEXT_OFFSET * 3;
/// @notice Uniswap router supporting Uniswap V2 and V3
ISwapRouter02 internal immutable uniswapRouter;
/// @notice Address of WETH token
address private immutable WETH;
/**
* @notice Sets initial values
* @param _uniswapRouter Uniswap router address
* @param _WETH WETH token address
*/
constructor(ISwapRouter02 _uniswapRouter, address _WETH) {
uniswapRouter = _uniswapRouter;
WETH = _WETH;
}
/**
* @notice Approve reward token and swap the `amount` to a strategy underlying asset
* @param from Token to swap from
* @param to Token to swap to
* @param amount Amount of tokens to swap
* @param swapData Swap details showing the path of the swap
* @return result Amount of underlying (`to`) tokens recieved
*/
function _approveAndSwap(
IERC20 from,
IERC20 to,
uint256 amount,
SwapData calldata swapData
) internal virtual returns (uint256) {
// if there is nothing to swap, return
if(amount == 0)
return 0;
// if amount is not uint256 max approve unswap router to spend tokens
// otherwise rewards were already sent to the router
if(amount < type(uint256).max) {
from.safeApprove(address(uniswapRouter), amount);
} else {
amount = 0;
}
// get swap action from first byte
SwapAction action = SwapAction(swapData.path.toUint8(0));
uint256 result;
if (action == SwapAction.UNI_V2_DIRECT) { // V2 Direct
address[] memory path = new address[](2);
result = _swapV2(from, to, amount, swapData.slippage, path);
} else if (action == SwapAction.UNI_V2_WETH) { // V2 WETH
address[] memory path = new address[](3);
path[1] = WETH;
result = _swapV2(from, to, amount, swapData.slippage, path);
} else if (action == SwapAction.UNI_V2) { // V2 Custom
address[] memory path = _getV2Path(swapData.path);
result = _swapV2(from, to, amount, swapData.slippage, path);
} else if (action == SwapAction.UNI_V3_DIRECT) { // V3 Direct
result = _swapDirectV3(from, to, amount, swapData.slippage, swapData.path);
} else if (action == SwapAction.UNI_V3_WETH) { // V3 WETH
bytes memory wethPath = _getV3WethPath(swapData.path);
result = _swapV3(from, to, amount, swapData.slippage, wethPath);
} else if (action == SwapAction.UNI_V3) { // V3 Custom
require(swapData.path.length > MIN_V3_PATH, "SwapHelper::_approveAndSwap: Path too short");
uint256 actualpathSize = swapData.path.length - ACTION_SIZE;
require((actualpathSize - FEE_SIZE) % NEXT_OFFSET == 0 &&
actualpathSize <= MAX_V3_PATH,
"SwapHelper::_approveAndSwap: Bad V3 path");
result = _swapV3(from, to, amount, swapData.slippage, swapData.path[ACTION_SIZE:]);
} else {
revert("SwapHelper::_approveAndSwap: No action");
}
if (from.allowance(address(this), address(uniswapRouter)) > 0) {
from.safeApprove(address(uniswapRouter), 0);
}
return result;
}
/**
* @notice Swaps tokens using Uniswap V2
* @param from Token to swap from
* @param to Token to swap to
* @param amount Amount of tokens to swap
* @param slippage Allowed slippage
* @param path Steps to complete the swap
* @return result Amount of underlying (`to`) tokens recieved
*/
function _swapV2(
IERC20 from,
IERC20 to,
uint256 amount,
uint256 slippage,
address[] memory path
) internal virtual returns (uint256) {
path[0] = address(from);
path[path.length - 1] = address(to);
return uniswapRouter.swapExactTokensForTokens(
amount,
slippage,
path,
address(this)
);
}
/**
* @notice Swaps tokens using Uniswap V3
* @param from Token to swap from
* @param to Token to swap to
* @param amount Amount of tokens to swap
* @param slippage Allowed slippage
* @param path Steps to complete the swap
* @return result Amount of underlying (`to`) tokens recieved
*/
function _swapV3(
IERC20 from,
IERC20 to,
uint256 amount,
uint256 slippage,
bytes memory path
) internal virtual returns (uint256) {
IV3SwapRouter.ExactInputParams memory params =
IV3SwapRouter.ExactInputParams({
path: abi.encodePacked(address(from), path, address(to)),
recipient: address(this),
amountIn: amount,
amountOutMinimum: slippage
});
// Executes the swap.
uint received = uniswapRouter.exactInput(params);
return received;
}
/**
* @notice Does a direct swap from `from` address to the `to` address using Uniswap V3
* @param from Token to swap from
* @param to Token to swap to
* @param amount Amount of tokens to swap
* @param slippage Allowed slippage
* @param fee V3 direct fee configuration
* @return result Amount of underlying (`to`) tokens recieved
*/
function _swapDirectV3(
IERC20 from,
IERC20 to,
uint256 amount,
uint256 slippage,
bytes memory fee
) internal virtual returns (uint256) {
require(fee.length == FEE_SIZE + ACTION_SIZE, "SwapHelper::_swapDirectV3: Bad V3 direct fee");
IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter.ExactInputSingleParams(
address(from),
address(to),
// ignore first byte
fee.toUint24(ACTION_SIZE),
address(this),
amount,
slippage,
0
);
return uniswapRouter.exactInputSingle(params);
}
/**
* @notice Converts passed bytes to V2 path
* @param pathBytes Swap path in bytes, converted to addresses
* @return path list of addresses in the swap path (skipping first and last element)
*/
function _getV2Path(bytes calldata pathBytes) internal pure returns(address[] memory) {
require(pathBytes.length > ACTION_SIZE, "SwapHelper::_getV2Path: No path provided");
uint256 actualpathSize = pathBytes.length - ACTION_SIZE;
require(actualpathSize % ADDR_SIZE == 0 && actualpathSize <= MAX_V2_PATH, "SwapHelper::_getV2Path: Bad V2 path");
uint256 pathLength = actualpathSize / ADDR_SIZE;
address[] memory path = new address[](pathLength + 2);
// ignore first byte
path[1] = pathBytes.toAddress(ACTION_SIZE);
for (uint256 i = 1; i < pathLength; i++) {
path[i + 1] = pathBytes.toAddress(i * ADDR_SIZE + ACTION_SIZE);
}
return path;
}
/**
* @notice Get Unswap V3 path to swap tokens via WETH LP pool
* @param pathBytes Swap path in bytes
* @return wethPath Unswap V3 path routing via WETH pool
*/
function _getV3WethPath(bytes calldata pathBytes) internal view returns(bytes memory) {
require(pathBytes.length == WETH_V3_PATH_SIZE + ACTION_SIZE, "SwapHelper::_getV3WethPath: Bad V3 WETH path");
// ignore first byte as it's used for swap action
return abi.encodePacked(pathBytes[ACTION_SIZE:4], WETH, pathBytes[4:]);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./SwapHelper.sol";
/// @title Swap helper implementation with SwapRouter02 on Mainnet
contract SwapHelperMainnet is SwapHelper {
constructor()
SwapHelper(ISwapRouter02(0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)
{}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../interfaces/IBaseStrategy.sol";
import "../shared/BaseStorage.sol";
import "../shared/Constants.sol";
import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol";
import "../libraries/Math.sol";
import "../libraries/Max/128Bit.sol";
/**
* @notice Implementation of the {IBaseStrategy} interface.
*
* @dev
* This implementation of the {IBaseStrategy} is meant to operate
* on single-collateral strategies and uses a delta system to calculate
* whether a withdrawal or deposit needs to be performed for a particular
* strategy.
*/
abstract contract BaseStrategy is IBaseStrategy, BaseStorage, BaseConstants {
using SafeERC20 for IERC20;
using Max128Bit for uint128;
/* ========== CONSTANTS ========== */
/// @notice minimum shares size to avoid loss of share due to computation precision
uint128 private constant MIN_SHARES = 10**8;
/* ========== STATE VARIABLES ========== */
/// @notice The total slippage slots the strategy supports, used for validation of provided slippage
uint256 internal immutable rewardSlippageSlots;
/// @notice Slots for processing
uint256 internal immutable processSlippageSlots;
/// @notice Slots for reallocation
uint256 internal immutable reallocationSlippageSlots;
/// @notice Slots for deposit
uint256 internal immutable depositSlippageSlots;
/**
* @notice do force claim of rewards.
*
* @dev
* Some strategies auto claim on deposit/withdraw,
* so execute the claim actions to store the reward amounts.
*/
bool internal immutable forceClaim;
/// @notice flag to force balance validation before running process strategy
/// @dev this is done so noone can manipulate the strategies before we interact with them and cause harm to the system
bool internal immutable doValidateBalance;
/// @notice The self address, set at initialization to allow proper share accounting
address internal immutable self;
/// @notice The underlying asset of the strategy
IERC20 public immutable override underlying;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Initializes the base strategy values.
*
* @dev
* It performs certain pre-conditional validations to ensure the contract
* has been initialized properly, such as that the address argument of the
* underlying asset is valid.
*
* Slippage slots for certain strategies may be zero if there is no compounding
* work to be done.
*
* @param _underlying token used for deposits
* @param _rewardSlippageSlots slots for rewards
* @param _processSlippageSlots slots for processing
* @param _reallocationSlippageSlots slots for reallocation
* @param _depositSlippageSlots slots for deposits
* @param _forceClaim force claim of rewards
* @param _doValidateBalance force balance validation
*/
constructor(
IERC20 _underlying,
uint256 _rewardSlippageSlots,
uint256 _processSlippageSlots,
uint256 _reallocationSlippageSlots,
uint256 _depositSlippageSlots,
bool _forceClaim,
bool _doValidateBalance
) {
require(
_underlying != IERC20(address(0)),
"BaseStrategy::constructor: Underlying address cannot be 0"
);
self = address(this);
underlying = _underlying;
rewardSlippageSlots = _rewardSlippageSlots;
processSlippageSlots = _processSlippageSlots;
reallocationSlippageSlots = _reallocationSlippageSlots;
depositSlippageSlots = _depositSlippageSlots;
forceClaim = _forceClaim;
doValidateBalance = _doValidateBalance;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Process the latest pending action of the strategy
*
* @dev
* it yields amount of funds processed as well as the reward buffer of the strategy.
* The function will auto-compound rewards if requested and supported.
*
* Requirements:
*
* - the slippages provided must be valid in length
* - if the redeposit flag is set to true, the strategy must support
* compounding of rewards
*
* @param slippages slippages to process
* @param redeposit if redepositing is to occur
* @param swapData swap data for processing
*/
function process(uint256[] calldata slippages, bool redeposit, SwapData[] calldata swapData) external override
{
slippages = _validateStrategyBalance(slippages);
if (forceClaim || redeposit) {
_validateRewardsSlippage(swapData);
_processRewards(swapData);
}
if (processSlippageSlots != 0)
_validateProcessSlippage(slippages);
_process(slippages, 0);
}
/**
* @notice Process first part of the reallocation DHW
* @dev Withdraws for reallocation, depositn and withdraww for a user
*
* @param slippages Parameters to apply when performing a deposit or a withdraw
* @param processReallocationData Data containing amuont of optimized and not optimized shares to withdraw
* @return withdrawnReallocationReceived actual amount recieveed from peforming withdraw
*/
function processReallocation(uint256[] calldata slippages, ProcessReallocationData calldata processReallocationData) external override returns(uint128)
{
slippages = _validateStrategyBalance(slippages);
if (reallocationSlippageSlots != 0)
_validateReallocationSlippage(slippages);
_process(slippages, processReallocationData.sharesToWithdraw);
uint128 withdrawnReallocationReceived = _updateReallocationWithdraw(processReallocationData);
return withdrawnReallocationReceived;
}
/**
* @dev Update reallocation batch storage for index after withdrawing reallocated shares
* @param processReallocationData Data containing amount of optimized and not optimized shares to withdraw
* @return Withdrawn reallocation received
*/
function _updateReallocationWithdraw(ProcessReallocationData calldata processReallocationData) internal virtual returns(uint128) {
Strategy storage strategy = strategies[self];
uint24 stratIndex = _getProcessingIndex();
BatchReallocation storage batch = strategy.reallocationBatches[stratIndex];
// save actual withdrawn amount, without optimized one
uint128 withdrawnReallocationReceived = batch.withdrawnReallocationReceived;
strategy.optimizedSharesWithdrawn += processReallocationData.optimizedShares;
batch.withdrawnReallocationReceived += processReallocationData.optimizedWithdrawnAmount;
batch.withdrawnReallocationShares = processReallocationData.optimizedShares + processReallocationData.sharesToWithdraw;
return withdrawnReallocationReceived;
}
/**
* @notice Process deposit
* @param slippages Array of slippage parameters to apply when depositing
*/
function processDeposit(uint256[] calldata slippages)
external
override
{
slippages = _validateStrategyBalance(slippages);
if (depositSlippageSlots != 0)
_validateDepositSlippage(slippages);
_processDeposit(slippages);
}
/**
* @notice Returns total starategy balance includign pending rewards
* @return strategyBalance total starategy balance includign pending rewards
*/
function getStrategyUnderlyingWithRewards() public view override returns(uint128)
{
return _getStrategyUnderlyingWithRewards();
}
/**
* @notice Fast withdraw
* @param shares Shares to fast withdraw
* @param slippages Array of slippage parameters to apply when withdrawing
* @param swapData Swap slippage and path array
* @return Withdrawn amount withdawn
*/
function fastWithdraw(uint128 shares, uint256[] calldata slippages, SwapData[] calldata swapData) external override returns(uint128)
{
slippages = _validateStrategyBalance(slippages);
_validateRewardsSlippage(swapData);
if (processSlippageSlots != 0)
_validateProcessSlippage(slippages);
uint128 withdrawnAmount = _processFastWithdraw(shares, slippages, swapData);
strategies[self].totalShares -= shares;
return withdrawnAmount;
}
/**
* @notice Claims and possibly compounds strategy rewards.
*
* @param swapData swap data for processing
*/
function claimRewards(SwapData[] calldata swapData) external override
{
_validateRewardsSlippage(swapData);
_processRewards(swapData);
}
/**
* @notice Withdraws all actively deployed funds in the strategy, liquifying them in the process.
*
* @param recipient recipient of the withdrawn funds
* @param data data necessary execute the emergency withdraw
*/
function emergencyWithdraw(address recipient, uint256[] calldata data) external virtual override {
uint256 balanceBefore = underlying.balanceOf(address(this));
_emergencyWithdraw(recipient, data);
uint256 balanceAfter = underlying.balanceOf(address(this));
uint256 withdrawnAmount = 0;
if (balanceAfter > balanceBefore) {
withdrawnAmount = balanceAfter - balanceBefore;
}
Strategy storage strategy = strategies[self];
if (strategy.emergencyPending > 0) {
withdrawnAmount += strategy.emergencyPending;
strategy.emergencyPending = 0;
}
// also withdraw all unprocessed deposit for a strategy
if (strategy.pendingUser.deposit.get() > 0) {
withdrawnAmount += strategy.pendingUser.deposit.get();
strategy.pendingUser.deposit = 0;
}
if (strategy.pendingUserNext.deposit.get() > 0) {
withdrawnAmount += strategy.pendingUserNext.deposit.get();
strategy.pendingUserNext.deposit = 0;
}
// if strategy was already processed in the current index that hasn't finished yet,
// transfer the withdrawn amount
// reset total underlying to 0
if (strategy.index == globalIndex && doHardWorksLeft > 0) {
uint256 withdrawnReceived = strategy.batches[strategy.index].withdrawnReceived;
withdrawnAmount += withdrawnReceived;
strategy.batches[strategy.index].withdrawnReceived = 0;
strategy.totalUnderlying[strategy.index].amount = 0;
}
if (withdrawnAmount > 0) {
// check if the balance is high enough to withdraw the total withdrawnAmount
if (balanceAfter < withdrawnAmount) {
// if not withdraw the current balance
withdrawnAmount = balanceAfter;
}
underlying.safeTransfer(recipient, withdrawnAmount);
}
}
/**
* @notice Initialize a strategy.
* @dev Execute strategy specific one-time actions if needed.
*/
function initialize() external virtual override {}
/**
* @notice Disables a strategy.
* @dev Cleans strategy specific values if needed.
*/
function disable() external virtual override {}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @dev Validate strategy balance
* @param slippages Check if the strategy balance is within defined min and max values
* @return slippages Same array without first 2 slippages
*/
function _validateStrategyBalance(uint256[] calldata slippages) internal virtual returns(uint256[] calldata) {
if (doValidateBalance) {
require(slippages.length >= 2, "BaseStrategy:: _validateStrategyBalance: Invalid number of slippages");
uint128 strategyBalance = getStrategyBalance();
require(
slippages[0] <= strategyBalance &&
slippages[1] >= strategyBalance,
"BaseStrategy::_validateStrategyBalance: Bad strategy balance"
);
return slippages[2:];
}
return slippages;
}
/**
* @dev Validate reards slippage
* @param swapData Swap slippage and path array
*/
function _validateRewardsSlippage(SwapData[] calldata swapData) internal view virtual {
if (swapData.length > 0) {
require(
swapData.length == _getRewardSlippageSlots(),
"BaseStrategy::_validateSlippage: Invalid Number of reward slippages Defined"
);
}
}
/**
* @dev Retrieve reward slippage slots
* @return Reward slippage slots
*/
function _getRewardSlippageSlots() internal view virtual returns(uint256) {
return rewardSlippageSlots;
}
/**
* @dev Validate process slippage
* @param slippages parameters to verify validity of the strategy state
*/
function _validateProcessSlippage(uint256[] calldata slippages) internal view virtual {
_validateSlippage(slippages.length, processSlippageSlots);
}
/**
* @dev Validate reallocation slippage
* @param slippages parameters to verify validity of the strategy state
*/
function _validateReallocationSlippage(uint256[] calldata slippages) internal view virtual {
_validateSlippage(slippages.length, reallocationSlippageSlots);
}
/**
* @dev Validate deposit slippage
* @param slippages parameters to verify validity of the strategy state
*/
function _validateDepositSlippage(uint256[] calldata slippages) internal view virtual {
_validateSlippage(slippages.length, depositSlippageSlots);
}
/**
* @dev Validates the provided slippage in length.
* @param currentLength actual slippage array length
* @param shouldBeLength expected slippages array length
*/
function _validateSlippage(uint256 currentLength, uint256 shouldBeLength)
internal
view
virtual
{
require(
currentLength == shouldBeLength,
"BaseStrategy::_validateSlippage: Invalid Number of Slippages Defined"
);
}
/**
* @dev Retrieve processing index
* @return Processing index
*/
function _getProcessingIndex() internal view returns(uint24) {
return strategies[self].index + 1;
}
/**
* @dev Calculates shares before they are added to the total shares
* @param strategyTotalShares Total shares for strategy
* @param stratTotalUnderlying Total underlying for strategy
* @return newShares New shares calculated
*/
function _getNewSharesAfterWithdraw(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){
uint128 oldUnderlying;
if (stratTotalUnderlying > depositAmount) {
oldUnderlying = stratTotalUnderlying - depositAmount;
}
if (strategyTotalShares == 0 || oldUnderlying == 0) {
// Enforce minimum shares size to avoid loss of share due to computation precision
newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount;
} else {
newShares = Math.getProportion128(depositAmount, strategyTotalShares, oldUnderlying);
}
}
/**
* @dev Calculates shares when they are already part of the total shares
*
* @param strategyTotalShares Total shares
* @param stratTotalUnderlying Total underlying
* @return newShares New shares calculated
*/
function _getNewShares(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){
if (strategyTotalShares == 0 || stratTotalUnderlying == 0) {
// Enforce minimum shares size to avoid loss of share due to computation precision
newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount;
} else {
newShares = Math.getProportion128(depositAmount, strategyTotalShares, stratTotalUnderlying);
}
}
/**
* @dev Reset allowance to zero if previously set to a higher value.
* @param token Asset
* @param spender Spender address
*/
function _resetAllowance(IERC20 token, address spender) internal {
if (token.allowance(address(this), spender) > 0) {
token.safeApprove(spender, 0);
}
}
/* ========== VIRTUAL FUNCTIONS ========== */
function getStrategyBalance()
public
view
virtual
override
returns (uint128);
function _processRewards(SwapData[] calldata) internal virtual;
function _emergencyWithdraw(address recipient, uint256[] calldata data) internal virtual;
function _process(uint256[] memory, uint128 reallocateSharesToWithdraw) internal virtual;
function _processDeposit(uint256[] memory) internal virtual;
function _getStrategyUnderlyingWithRewards() internal view virtual returns(uint128);
function _processFastWithdraw(uint128, uint256[] memory, SwapData[] calldata) internal virtual returns(uint128);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./RewardStrategy.sol";
import "../shared/SwapHelperMainnet.sol";
/**
* @notice Multiple reward strategy logic
*/
abstract contract MultipleRewardStrategy is RewardStrategy, SwapHelperMainnet {
/* ========== OVERRIDDEN FUNCTIONS ========== */
/**
* @notice Claim rewards
* @param swapData Slippage and path array
* @return Rewards
*/
function _claimRewards(SwapData[] calldata swapData) internal virtual override returns(Reward[] memory) {
return _claimMultipleRewards(type(uint128).max, swapData);
}
/**
* @dev Claim fast withdraw rewards
* @param shares Amount of shares
* @param swapData Swap slippage and path
* @return Rewards
*/
function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal virtual override returns(Reward[] memory) {
return _claimMultipleRewards(shares, swapData);
}
/* ========== VIRTUAL FUNCTIONS ========== */
function _claimMultipleRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./BaseStrategy.sol";
import "../libraries/Max/128Bit.sol";
import "../libraries/Math.sol";
struct ProcessInfo {
uint128 totalWithdrawReceived;
uint128 userDepositReceived;
}
/**
* @notice Process strategy logic
*/
abstract contract ProcessStrategy is BaseStrategy {
using Max128Bit for uint128;
/* ========== OVERRIDDEN FUNCTIONS ========== */
/**
* @notice Process the strategy pending deposits, withdrawals, and collected strategy rewards
* @dev
* Deposit amount amd withdrawal shares are matched between eachother, effecively only one of
* those 2 is called. Shares are converted to the dollar value, based on the current strategy
* total balance. This ensures the minimum amount of assets are moved around to lower the price
* drift and total fees paid to the protocols the strategy is interacting with (if there are any)
*
* @param slippages Strategy slippage values verifying the validity of the strategy state
* @param reallocateSharesToWithdraw Reallocation shares to withdraw (non-zero only if reallocation DHW is in progress, otherwise 0)
*/
function _process(uint256[] memory slippages, uint128 reallocateSharesToWithdraw) internal override virtual {
// PREPARE
Strategy storage strategy = strategies[self];
uint24 processingIndex = _getProcessingIndex();
Batch storage batch = strategy.batches[processingIndex];
uint128 strategyTotalShares = strategy.totalShares;
uint128 pendingSharesToWithdraw = strategy.pendingUser.sharesToWithdraw.get();
uint128 userDeposit = strategy.pendingUser.deposit.get();
// CALCULATE THE ACTION
// if withdrawing for reallocating, add shares to total withdraw shares
if (reallocateSharesToWithdraw > 0) {
pendingSharesToWithdraw += reallocateSharesToWithdraw;
}
// total deposit received from users + compound reward (if there are any)
uint128 totalPendingDeposit = userDeposit;
// add compound reward (pendingDepositReward) to deposit
uint128 withdrawalReward = 0;
if (strategy.pendingDepositReward > 0) {
uint128 pendingDepositReward = strategy.pendingDepositReward;
totalPendingDeposit += pendingDepositReward;
// calculate compound reward (withdrawalReward) for users withdrawing in this batch
if (pendingSharesToWithdraw > 0 && strategyTotalShares > 0) {
withdrawalReward = Math.getProportion128(pendingSharesToWithdraw, pendingDepositReward, strategyTotalShares);
// substract withdrawal reward from total deposit
totalPendingDeposit -= withdrawalReward;
}
// Reset pendingDepositReward
strategy.pendingDepositReward = 0;
}
// if there is no pending deposit or withdrawals, return
if (totalPendingDeposit == 0 && pendingSharesToWithdraw == 0) {
return;
}
uint128 pendingWithdrawalAmount = 0;
if (pendingSharesToWithdraw > 0) {
pendingWithdrawalAmount =
Math.getProportion128(getStrategyBalance(), pendingSharesToWithdraw, strategyTotalShares);
}
// ACTION: DEPOSIT OR WITHDRAW
ProcessInfo memory processInfo;
if (totalPendingDeposit > pendingWithdrawalAmount) { // DEPOSIT
// uint128 amount = totalPendingDeposit - pendingWithdrawalAmount;
uint128 depositReceived = _deposit(totalPendingDeposit - pendingWithdrawalAmount, slippages);
processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward;
// pendingWithdrawalAmount is optimized deposit: totalPendingDeposit - amount;
uint128 totalDepositReceived = depositReceived + pendingWithdrawalAmount;
// calculate user deposit received, excluding compound rewards
processInfo.userDepositReceived = Math.getProportion128(totalDepositReceived, userDeposit, totalPendingDeposit);
} else if (totalPendingDeposit < pendingWithdrawalAmount) { // WITHDRAW
// uint128 amount = pendingWithdrawalAmount - totalPendingDeposit;
uint128 withdrawReceived = _withdraw(
// calculate back the shares from actual withdraw amount
// NOTE: we can do unchecked calculation and casting as
// the multiplier is always smaller than the divisor
Math.getProportion128Unchecked(
(pendingWithdrawalAmount - totalPendingDeposit),
pendingSharesToWithdraw,
pendingWithdrawalAmount
),
slippages
);
// optimized withdraw is total pending deposit: pendingWithdrawalAmount - amount = totalPendingDeposit;
processInfo.totalWithdrawReceived = withdrawReceived + totalPendingDeposit + withdrawalReward;
processInfo.userDepositReceived = userDeposit;
} else {
processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward;
processInfo.userDepositReceived = userDeposit;
}
// UPDATE STORAGE AFTER
{
uint128 stratTotalUnderlying = getStrategyBalance();
// Update withdraw batch
if (pendingSharesToWithdraw > 0) {
batch.withdrawnReceived = processInfo.totalWithdrawReceived;
batch.withdrawnShares = pendingSharesToWithdraw;
strategyTotalShares -= pendingSharesToWithdraw;
// update reallocation batch
if (reallocateSharesToWithdraw > 0) {
BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex];
uint128 withdrawnReallocationReceived =
Math.getProportion128(processInfo.totalWithdrawReceived, reallocateSharesToWithdraw, pendingSharesToWithdraw);
reallocationBatch.withdrawnReallocationReceived = withdrawnReallocationReceived;
// substract reallocation values from user values
batch.withdrawnReceived -= withdrawnReallocationReceived;
batch.withdrawnShares -= reallocateSharesToWithdraw;
}
}
// Update deposit batch
if (userDeposit > 0) {
uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, processInfo.userDepositReceived);
batch.deposited = userDeposit;
batch.depositedReceived = processInfo.userDepositReceived;
batch.depositedSharesReceived = newShares;
strategyTotalShares += newShares;
}
// Update shares
if (strategyTotalShares != strategy.totalShares) {
strategy.totalShares = strategyTotalShares;
}
// Set underlying at index
strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;
strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares;
}
}
/**
* @notice Process deposit
* @param slippages Slippages array
*/
function _processDeposit(uint256[] memory slippages) internal override virtual {
Strategy storage strategy = strategies[self];
uint128 depositOptimizedAmount = strategy.pendingReallocateOptimizedDeposit;
uint128 optimizedSharesWithdrawn = strategy.optimizedSharesWithdrawn;
uint128 depositAmount = strategy.pendingReallocateDeposit;
// if a strategy is not part of reallocation return
if (
depositOptimizedAmount == 0 &&
optimizedSharesWithdrawn == 0 &&
depositAmount == 0
) {
return;
}
uint24 processingIndex = _getProcessingIndex();
BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex];
uint128 strategyTotalShares = strategy.totalShares;
// get shares from optimized deposit
if (depositOptimizedAmount > 0) {
uint128 stratTotalUnderlying = getStrategyBalance();
uint128 newShares = _getNewShares(strategyTotalShares, stratTotalUnderlying, depositOptimizedAmount);
// add new shares
strategyTotalShares += newShares;
// update reallocation batch
reallocationBatch.depositedReallocation = depositOptimizedAmount;
reallocationBatch.depositedReallocationSharesReceived = newShares;
strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;
// reset
strategy.pendingReallocateOptimizedDeposit = 0;
}
// remove optimized withdraw shares
if (optimizedSharesWithdrawn > 0) {
strategyTotalShares -= optimizedSharesWithdrawn;
// reset
strategy.optimizedSharesWithdrawn = 0;
}
// get shares from actual deposit
if (depositAmount > 0) {
// deposit
uint128 depositReceived = _deposit(depositAmount, slippages);
// NOTE: might return it from _deposit (only certain strategies need it)
uint128 stratTotalUnderlying = getStrategyBalance();
uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, depositReceived);
// add new shares
strategyTotalShares += newShares;
// update reallocation batch
reallocationBatch.depositedReallocation += depositReceived;
reallocationBatch.depositedReallocationSharesReceived += newShares;
strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;
// reset
strategy.pendingReallocateDeposit = 0;
}
// update share storage
strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares;
strategy.totalShares = strategyTotalShares;
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice get the value of the strategy shares in the underlying tokens
* @param shares Number of shares
* @return amount Underling amount representing the `share` value of the strategy
*/
function _getSharesToAmount(uint256 shares) internal virtual returns(uint128 amount) {
amount = Math.getProportion128( getStrategyBalance(), shares, strategies[self].totalShares );
}
/**
* @notice get slippage amount, and action type (withdraw/deposit).
* @dev
* Most significant bit represents an action, 0 for a withdrawal and 1 for deposit.
*
* This ensures the slippage will be used for the action intended by the do-hard-worker,
* otherwise the transavtion will revert.
*
* @param slippageAction number containing the slippage action and the actual slippage amount
* @return isDeposit Flag showing if the slippage is for the deposit action
* @return slippage the slippage value cleaned of the most significant bit
*/
function _getSlippageAction(uint256 slippageAction) internal pure returns (bool isDeposit, uint256 slippage) {
// remove most significant bit
slippage = (slippageAction << 1) >> 1;
// if values are not the same (the removed bit was 1) set action to deposit
if (slippageAction != slippage) {
isDeposit = true;
}
}
/* ========== VIRTUAL FUNCTIONS ========== */
function _deposit(uint128 amount, uint256[] memory slippages) internal virtual returns(uint128 depositReceived);
function _withdraw(uint128 shares, uint256[] memory slippages) internal virtual returns(uint128 withdrawReceived);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./ProcessStrategy.sol";
import "../shared/SwapHelper.sol";
struct Reward {
uint256 amount;
IERC20 token;
}
/**
* @notice Reward strategy logic
*/
abstract contract RewardStrategy is ProcessStrategy, SwapHelper {
/* ========== OVERRIDDEN FUNCTIONS ========== */
/**
* @notice Gey strategy underlying asset with rewards
* @return Total underlying
*/
function _getStrategyUnderlyingWithRewards() internal view override virtual returns(uint128) {
Strategy storage strategy = strategies[self];
uint128 totalUnderlying = getStrategyBalance();
totalUnderlying += strategy.pendingDepositReward;
return totalUnderlying;
}
/**
* @notice Process an instant withdrawal from the protocol per users request.
*
* @param shares Amount of shares
* @param slippages Array of slippages
* @param swapData Data used in processing
* @return Withdrawn amount
*/
function _processFastWithdraw(uint128 shares, uint256[] memory slippages, SwapData[] calldata swapData) internal override virtual returns(uint128) {
uint128 withdrawRewards = _processFastWithdrawalRewards(shares, swapData);
uint128 withdrawReceived = _withdraw(shares, slippages);
return withdrawReceived + withdrawRewards;
}
/**
* @notice Process rewards
* @param swapData Data used in processing
*/
function _processRewards(SwapData[] calldata swapData) internal override virtual {
Strategy storage strategy = strategies[self];
Reward[] memory rewards = _claimRewards(swapData);
uint128 collectedAmount = _sellRewards(rewards, swapData);
if (collectedAmount > 0) {
strategy.pendingDepositReward += collectedAmount;
}
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice Process fast withdrawal rewards
* @param shares Amount of shares
* @param swapData Values used for swapping the rewards
* @return withdrawalRewards Withdrawal rewards
*/
function _processFastWithdrawalRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(uint128 withdrawalRewards) {
Strategy storage strategy = strategies[self];
Reward[] memory rewards = _claimFastWithdrawRewards(shares, swapData);
withdrawalRewards += _sellRewards(rewards, swapData);
if (strategy.pendingDepositReward > 0) {
uint128 fastWithdrawCompound = Math.getProportion128(strategy.pendingDepositReward, shares, strategy.totalShares);
if (fastWithdrawCompound > 0) {
strategy.pendingDepositReward -= fastWithdrawCompound;
withdrawalRewards += fastWithdrawCompound;
}
}
}
/**
* @notice Sell rewards to the underlying token
* @param rewards Rewards to sell
* @param swapData Values used for swapping the rewards
* @return collectedAmount Collected underlying amount
*/
function _sellRewards(Reward[] memory rewards, SwapData[] calldata swapData) internal virtual returns(uint128 collectedAmount) {
for (uint256 i = 0; i < rewards.length; i++) {
// add compound amount from current batch to the fast withdraw
if (rewards[i].amount > 0) {
uint128 compoundAmount = SafeCast.toUint128(
_approveAndSwap(
rewards[i].token,
underlying,
rewards[i].amount,
swapData[i]
)
);
// add to pending reward
collectedAmount += compoundAmount;
}
}
}
/**
* @notice Get reward claim amount for `shares`
* @param shares Amount of shares
* @param rewardAmount Total reward amount
* @return rewardAmount Amount of reward for the shares
*/
function _getRewardClaimAmount(uint128 shares, uint256 rewardAmount) internal virtual view returns(uint128) {
// for do hard work claim everything
if (shares == type(uint128).max) {
return SafeCast.toUint128(rewardAmount);
} else { // for fast withdrawal claim calculate user withdraw amount
return SafeCast.toUint128((rewardAmount * shares) / strategies[self].totalShares);
}
}
/* ========== VIRTUAL FUNCTIONS ========== */
function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards);
function _claimRewards(SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../MultipleRewardStrategy.sol";
import "../../external/interfaces/idle-finance/IIdleToken.sol";
/**
* @notice Idle strategy implementation
*/
contract IdleStrategy is MultipleRewardStrategy {
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
/// @notice Idle token contract
IIdleToken public immutable idleToken;
/// @notice One idle token shares amount
uint256 public immutable oneShare;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Set initial values
* @param _idleToken Idle token contract
* @param _underlying Underlying asset
*/
constructor(
IIdleToken _idleToken,
IERC20 _underlying
)
BaseStrategy(_underlying, 0, 1, 1, 1, true, false)
{
require(address(_idleToken) != address(0), "IdleStrategy::constructor: Token address cannot be 0");
idleToken = _idleToken;
oneShare = 10 ** uint256(_idleToken.decimals());
}
/* ========== VIEWS ========== */
/**
* @notice Get strategy balance
* @return strategyBalance Strategy balance in strategy underlying tokens
*/
function getStrategyBalance() public view override returns(uint128) {
uint256 idleTokenBalance = idleToken.balanceOf(address(this));
return SafeCast.toUint128(_getIdleTokenValue(idleTokenBalance));
}
/* ========== OVERRIDDEN FUNCTIONS ========== */
/**
* @notice Dynamically return reward slippage length
* @dev Reward slippage lenght corresponds with amount of reward tokens a strategy provides
*/
function _getRewardSlippageSlots() internal view override returns(uint256) {
return idleToken.getGovTokens().length;
}
/**
* @notice Deposit to Idle (mint idle tokens)
* @param amount Amount to deposit
* @param slippages Slippages array
* @return Minted idle amount
*/
function _deposit(uint128 amount, uint256[] memory slippages) internal override returns(uint128) {
(bool isDeposit, uint256 slippage) = _getSlippageAction(slippages[0]);
require(isDeposit, "IdleStrategy::_deposit: Withdraw slippage provided");
// deposit underlying
underlying.safeApprove(address(idleToken), amount);
// NOTE: Middle Flag is unused so can be anything
uint256 mintedIdleAmount = idleToken.mintIdleToken(
amount,
true,
address(this)
);
_resetAllowance(underlying, address(idleToken));
require(
mintedIdleAmount >= slippage,
"IdleStrategy::_deposit: Insufficient Idle Amount Minted"
);
return SafeCast.toUint128(_getIdleTokenValue(mintedIdleAmount));
}
/**
* @notice Withdraw from the Idle strategy
* @param shares Amount of shares to withdraw
* @param slippages Slippage values
* @return undelyingWithdrawn Withdrawn underlying recieved amount
*/
function _withdraw(uint128 shares, uint256[] memory slippages) internal override returns(uint128) {
(bool isDeposit, uint256 slippage) = _getSlippageAction(slippages[0]);
require(!isDeposit, "IdleStrategy::_withdraw: Deposit slippage provided");
uint256 idleTokensTotal = idleToken.balanceOf(address(this));
uint256 redeemIdleAmount = (idleTokensTotal * shares) / strategies[self].totalShares;
// withdraw idle tokens from vault
uint256 undelyingBefore = underlying.balanceOf(address(this));
idleToken.redeemIdleToken(redeemIdleAmount);
uint256 undelyingWithdrawn = underlying.balanceOf(address(this)) - undelyingBefore;
require(
undelyingWithdrawn >= slippage,
"IdleStrategy::_withdraw: Insufficient withdrawn amount"
);
return SafeCast.toUint128(undelyingWithdrawn);
}
/**
* @notice Emergency withdraw all the balance from the idle strategy
*/
function _emergencyWithdraw(address, uint256[] calldata) internal override {
idleToken.redeemIdleToken(idleToken.balanceOf(address(this)));
}
/* ========== PRIVATE FUNCTIONS ========== */
/**
* @notice Get idle token value for the given token amount
* @param idleAmount Idle token amount
* @return Token value for given amount
*/
function _getIdleTokenValue(uint256 idleAmount) private view returns(uint256) {
if (idleAmount == 0)
return 0;
return (idleAmount * idleToken.tokenPriceWithFee(address(this))) / oneShare;
}
/**
* @notice Claim all idle governance reward tokens
* @dev Force claiming tokens on every strategy interaction
* @param shares amount of shares to claim for
* @param _swapData Swap values, representing paths to swap the tokens to underlying
* @return rewards Claimed reward tokens
*/
function _claimMultipleRewards(uint128 shares, SwapData[] calldata _swapData) internal override returns(Reward[] memory rewards) {
address[] memory rewardTokens = idleToken.getGovTokens();
SwapData[] memory swapData = _swapData;
if (swapData.length == 0) {
// if no slippages provided we just loop over the rewards to save them
swapData = new SwapData[](rewardTokens.length);
} else {
// init rewards array, to compound them
rewards = new Reward[](rewardTokens.length);
}
uint256[] memory newRewardTokenAmounts = _claimStrategyRewards(rewardTokens);
Strategy storage strategy = strategies[self];
for (uint256 i = 0; i < rewardTokens.length; i++) {
if (swapData[i].slippage > 0) {
uint256 rewardTokenAmount = newRewardTokenAmounts[i] + strategy.pendingRewards[rewardTokens[i]];
if (rewardTokenAmount > 0) {
uint256 claimedAmount = _getRewardClaimAmount(shares, rewardTokenAmount);
if (rewardTokenAmount > claimedAmount) {
// if we don't swap all the tokens (fast withdraw), save the rest
uint256 rewardAmountLeft = rewardTokenAmount - claimedAmount;
strategy.pendingRewards[rewardTokens[i]] = rewardAmountLeft;
} else if (rewardTokenAmount > newRewardTokenAmounts[i]) {
// if reward amount is more than new rewards, we reset pendng to 0, otherwise it was 0 already
strategy.pendingRewards[rewardTokens[i]] = 0;
}
rewards[i] = Reward(claimedAmount, IERC20(rewardTokens[i]));
}
} else if (newRewardTokenAmounts[i] > 0) {
strategy.pendingRewards[rewardTokens[i]] += newRewardTokenAmounts[i];
}
}
}
/**
* @notice Claim strategy rewards
* @param rewardTokens Tokens to claim
* @return Reward token amounts
*/
function _claimStrategyRewards(address[] memory rewardTokens) private returns(uint256[] memory) {
uint256[] memory rewardTokenAmountsBefore = _getRewardTokenAmounts(rewardTokens);
// claim
idleToken.redeemIdleToken(0);
uint256[] memory rewardTokenAmounts = new uint[](rewardTokens.length);
// calculate reward token amounts
for (uint256 i = 0; i < rewardTokenAmountsBefore.length; i++) {
rewardTokenAmounts[i] = IERC20(rewardTokens[i]).balanceOf(address(this)) - rewardTokenAmountsBefore[i];
}
return rewardTokenAmounts;
}
/**
* @notice Get reward token amounts
* @param rewardTokens Reward token address array
* @return Reward token amounts
*/
function _getRewardTokenAmounts(address[] memory rewardTokens) private view returns(uint256[] memory) {
uint256[] memory rewardTokenAmounts = new uint[](rewardTokens.length);
for (uint256 i = 0; i < rewardTokenAmounts.length; i++) {
rewardTokenAmounts[i] = IERC20(rewardTokens[i]).balanceOf(address(this));
}
return rewardTokenAmounts;
}
}
|
Get reward token amounts rewardTokens Reward token address array return Reward token amounts/
|
function _getRewardTokenAmounts(address[] memory rewardTokens) private view returns(uint256[] memory) {
uint256[] memory rewardTokenAmounts = new uint[](rewardTokens.length);
for (uint256 i = 0; i < rewardTokenAmounts.length; i++) {
rewardTokenAmounts[i] = IERC20(rewardTokens[i]).balanceOf(address(this));
}
return rewardTokenAmounts;
}
| 1,489,484 |
./partial_match/1/0x12CAe7c85Db90a5688111f98C89Be05e94Eb46c0/sources/CryptoPipisMint.sol
|
Maximum tokens to mint is 10,000 For contract owner to mass mint the remaining tokens if any to be then sold on open marketplaces Transfer excess amount of ether
|
function mint(uint256 _amount) public payable {
uint256 _price = _amount * price_;
uint256 _mintable = uint(10000) - INFT(nft).totalSupply();
require(_amount <= _mintable, "Mint: quantity exceeds available tokens for mint");
require(_amount <= 10, "Mint: quantity exceeds maximum allowed per transaction");
if (msg.sender == owner_) {
_price = 0;
require(INFT(nft).balanceOf(msg.sender) + _amount <= 100, 'Exceeds max mint per wallet reached');
}
require(msg.value >= _price, "Insufficient payment");
INFT(nft).mintSeaDrop(msg.sender, _amount);
if (msg.value > _price) {
payable(msg.sender).transfer(msg.value - _price);
}
emit Minted(msg.sender, _amount);
}
| 2,676,293 |
./full_match/11155111/0x3703F4412Fa17BA5FCd301B2b731a7969f1fc7A6/sources/contracts/TransparentCharity.sol
|
Function to create an account for a donor
|
function createDonorAccount(string memory _name) external {
require(donors[msg.sender].balance == 0, "Account already exists.");
donors[msg.sender].Address = payable(msg.sender);
donors[msg.sender].balance = payable(msg.sender).balance;
donors[msg.sender].name = _name;
donorAddresses.push(msg.sender);
}
| 3,797,222 |
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Recoverable is Ownable {
/// @dev Empty constructor (for now)
function Recoverable() {
}
/// @dev This will be invoked by the owner, when owner wants to rescue tokens
/// @param token Token which will we rescue to the owner from the contract
function recoverTokens(ERC20Basic token) onlyOwner public {
token.transfer(owner, tokensToBeReturned(token));
}
/// @dev Interface function, can be overwritten by the superclass
/// @param token Token which balance we will check and return
/// @return The amount of tokens (in smallest denominator) the contract owns
function tokensToBeReturned(ERC20Basic token) public returns (uint) {
return token.balanceOf(this);
}
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* Safe unsigned safe math.
*
* https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli
*
* Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol
*
* Maintained here until merged to mainline zeppelin-solidity.
*
*/
library SafeMathLib {
function times(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function minus(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a);
return c;
}
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
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) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove 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.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
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 specifing the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* Standard EIP-20 token with an interface marker.
*
* @notice Interface marker is used by crowdsale contracts to validate that addresses point a good token contract.
*
*/
contract StandardTokenExt is StandardToken {
/* Interface declaration */
function isToken() public constant returns (bool weAre) {
return true;
}
}
/**
* Hold tokens for a group investor of investors until the unlock date.
*
* After the unlock date the investor can claim their tokens.
*
* Steps
*
* - Prepare a spreadsheet for token allocation
* - Deploy this contract, with the sum to tokens to be distributed, from the owner account
* - Call setInvestor for all investors from the owner account using a local script and CSV input
* - Move tokensToBeAllocated in this contract using StandardToken.transfer()
* - Call lock from the owner account
* - Wait until the freeze period is over
* - After the freeze time is over investors can call claim() from their address to get their tokens
*
*/
contract TokenVault is Ownable, Recoverable {
using SafeMathLib for uint;
/** How many investors we have now */
uint public investorCount;
/** Sum from the spreadsheet how much tokens we should get on the contract. If the sum does not match at the time of the lock the vault is faulty and must be recreated.*/
uint public tokensToBeAllocated;
/** How many tokens investors have claimed so far */
uint public totalClaimed;
/** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */
uint public tokensAllocatedTotal;
/** How much we have allocated to the investors invested */
mapping(address => uint) public balances;
/** How many tokens investors have claimed */
mapping(address => uint) public claimed;
/** When was the last claim by an investor **/
mapping(address => uint) public lastClaimedAt;
/** When our claim freeze is over (UNIX timestamp) */
uint public freezeEndsAt;
/** When this vault was locked (UNIX timestamp) */
uint public lockedAt;
/** defining the tap **/
uint public tokensPerSecond;
/** We can also define our own token, which will override the ICO one ***/
StandardTokenExt public token;
/** What is our current state.
*
* Loading: Investor data is being loaded and contract not yet locked
* Holding: Holding tokens for investors
* Distributing: Freeze time is over, investors can claim their tokens
*/
enum State{Unknown, Loading, Holding, Distributing}
/** We allocated tokens for investor */
event Allocated(address investor, uint value);
/** We distributed tokens to an investor */
event Distributed(address investors, uint count);
event Locked();
/**
* Create presale contract where lock up period is given days
*
* @param _owner Who can load investor data and lock
* @param _freezeEndsAt UNIX timestamp when the vault unlocks
* @param _token Token contract address we are distributing
* @param _tokensToBeAllocated Total number of tokens this vault will hold - including decimal multiplication
* @param _tokensPerSecond Define the tap: how many tokens we permit an user to withdraw per second, 0 to disable
*/
function TokenVault(address _owner, uint _freezeEndsAt, StandardTokenExt _token, uint _tokensToBeAllocated, uint _tokensPerSecond) {
owner = _owner;
// Invalid owenr
if(owner == 0) {
throw;
}
token = _token;
// Check the address looks like a token contract
if(!token.isToken()) {
throw;
}
// Give argument
if(_freezeEndsAt == 0) {
throw;
}
// Sanity check on _tokensToBeAllocated
if(_tokensToBeAllocated == 0) {
throw;
}
if (_freezeEndsAt < now) {
freezeEndsAt = now;
} else {
freezeEndsAt = _freezeEndsAt;
}
tokensToBeAllocated = _tokensToBeAllocated;
tokensPerSecond = _tokensPerSecond;
}
/// @dev Add a presale participating allocation
function setInvestor(address investor, uint amount) public onlyOwner {
if(lockedAt > 0) {
// Cannot add new investors after the vault is locked
throw;
}
if(amount == 0) throw; // No empty buys
// Don't allow reset
if(balances[investor] > 0) {
throw;
}
balances[investor] = amount;
investorCount++;
tokensAllocatedTotal += amount;
Allocated(investor, amount);
}
/// @dev Lock the vault
/// - All balances have been loaded in correctly
/// - Tokens are transferred on this vault correctly
/// - Checks are in place to prevent creating a vault that is locked with incorrect token balances.
function lock() onlyOwner {
if(lockedAt > 0) {
throw; // Already locked
}
// Spreadsheet sum does not match to what we have loaded to the investor data
if(tokensAllocatedTotal != tokensToBeAllocated) {
throw;
}
// Do not lock the vault if the given tokens are not on this contract
if(token.balanceOf(address(this)) != tokensAllocatedTotal) {
throw;
}
lockedAt = now;
Locked();
}
/// @dev In the case locking failed, then allow the owner to reclaim the tokens on the contract.
function recoverFailedLock() onlyOwner {
if(lockedAt > 0) {
throw;
}
// Transfer all tokens on this contract back to the owner
token.transfer(owner, token.balanceOf(address(this)));
}
/// @dev Get the current balance of tokens in the vault
/// @return uint How many tokens there are currently in vault
function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) {
return token.balanceOf(address(this));
}
/// @dev Check how many tokens "investor" can claim
/// @param investor Address of the investor
/// @return uint How many tokens the investor can claim now
function getCurrentlyClaimableAmount(address investor) public constant returns (uint claimableAmount) {
uint maxTokensLeft = balances[investor] - claimed[investor];
if (now < freezeEndsAt) {
return 0;
}
if (tokensPerSecond > 0) {
uint previousClaimAt = lastClaimedAt[investor];
uint maxClaim;
if (previousClaimAt == 0) {
previousClaimAt = freezeEndsAt;
}
maxClaim = (now - previousClaimAt) * tokensPerSecond;
if (maxClaim > maxTokensLeft) {
return maxTokensLeft;
} else {
return maxClaim;
}
} else {
return maxTokensLeft;
}
}
/// @dev Claim N bought tokens to the investor as the msg sender
function claim() {
address investor = msg.sender;
if(lockedAt == 0) {
throw; // We were never locked
}
if(now < freezeEndsAt) {
throw; // Trying to claim early
}
if(balances[investor] == 0) {
// Not our investor
throw;
}
uint amount = getCurrentlyClaimableAmount(investor);
require (amount > 0);
lastClaimedAt[investor] = now;
claimed[investor] += amount;
totalClaimed += amount;
token.transfer(investor, amount);
Distributed(investor, amount);
}
/// @dev This function is prototyped in Recoverable contract
function tokensToBeReturned(ERC20Basic tokenToClaim) public returns (uint) {
if (address(tokenToClaim) == address(token)) {
return getBalance().minus(tokensAllocatedTotal);
} else {
return tokenToClaim.balanceOf(this);
}
}
/// @dev Resolve the contract umambigious state
function getState() public constant returns(State) {
if(lockedAt == 0) {
return State.Loading;
} else if(now > freezeEndsAt) {
return State.Distributing;
} else {
return State.Holding;
}
}
}
|
Check how many tokens "investor" can claim investor Address of the investor return uint How many tokens the investor can claim now
|
function getCurrentlyClaimableAmount(address investor) public constant returns (uint claimableAmount) {
uint maxTokensLeft = balances[investor] - claimed[investor];
if (now < freezeEndsAt) {
return 0;
}
if (tokensPerSecond > 0) {
uint previousClaimAt = lastClaimedAt[investor];
uint maxClaim;
if (previousClaimAt == 0) {
previousClaimAt = freezeEndsAt;
}
maxClaim = (now - previousClaimAt) * tokensPerSecond;
if (maxClaim > maxTokensLeft) {
return maxTokensLeft;
return maxClaim;
}
return maxTokensLeft;
}
}
| 395,477 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
import "./HoldefiOwnable.sol";
/// @notice File: contracts/Holdefi.sol
interface HoldefiInterface {
struct Market {
uint256 totalSupply;
uint256 supplyIndex;
uint256 supplyIndexUpdateTime;
uint256 totalBorrow;
uint256 borrowIndex;
uint256 borrowIndexUpdateTime;
uint256 promotionReserveScaled;
uint256 promotionReserveLastUpdateTime;
uint256 promotionDebtScaled;
uint256 promotionDebtLastUpdateTime;
}
function marketAssets(address market) external view returns (Market memory);
function holdefiSettings() external view returns (address contractAddress);
function beforeChangeSupplyRate (address market) external;
function beforeChangeBorrowRate (address market) external;
function reserveSettlement (address market) external;
}
/// @title HoldefiSettings contract
/// @author Holdefi Team
/// @notice This contract is for Holdefi settings implementation
/// @dev Error codes description:
/// SE01: Market is not exist
/// SE02: Collateral is not exist
/// SE03: Conflict with Holdefi contract
/// SE04: The contract should be set once
/// SE05: Rate should be in the allowed range
/// SE06: Sender should be Holdefi contract
/// SE07: Collateral is exist
/// SE08: Market is exist
/// SE09: Market list is full
/// SE10: Total borrow is not zero
/// SE11: Changing rate is not allowed at this time
/// SE12: Changing rate should be less than Max allowed
contract HoldefiSettings is HoldefiOwnable {
using SafeMath for uint256;
/// @notice Markets Features
struct MarketSettings {
bool isExist; // Market is exist or not
bool isActive; // Market is open for deposit or not
uint256 borrowRate;
uint256 borrowRateUpdateTime;
uint256 suppliersShareRate;
uint256 suppliersShareRateUpdateTime;
uint256 promotionRate;
}
/// @notice Collateral Features
struct CollateralSettings {
bool isExist; // Collateral is exist or not
bool isActive; // Collateral is open for deposit or not
uint256 valueToLoanRate;
uint256 VTLUpdateTime;
uint256 penaltyRate;
uint256 penaltyUpdateTime;
uint256 bonusRate;
}
uint256 constant private rateDecimals = 10 ** 4;
address constant private ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 constant private periodBetweenUpdates = 604800; // seconds per week
uint256 constant private maxBorrowRate = 4000; // 40%
uint256 constant private borrowRateMaxIncrease = 500; // 5%
uint256 constant private minSuppliersShareRate = 5000; // 50%
uint256 constant private suppliersShareRateMaxDecrease = 500; // 5%
uint256 constant private maxValueToLoanRate = 20000; // 200%
uint256 constant private valueToLoanRateMaxIncrease = 500; // 5%
uint256 constant private maxPenaltyRate = 13000; // 130%
uint256 constant private penaltyRateMaxIncrease = 500; // 5%
uint256 constant private maxPromotionRate = 10000; // 100%
uint256 constant private maxListsLength = 50;
/// @dev Used for calculating liquidation threshold
/// There is 5% gap between value to loan rate and liquidation rate
uint256 constant private fivePercentLiquidationGap = 500;
mapping (address => MarketSettings) public marketAssets;
address[] public marketsList;
mapping (address => CollateralSettings) public collateralAssets;
HoldefiInterface public holdefiContract;
/// @notice Event emitted when market activation status is changed
event MarketActivationChanged(address indexed market, bool status);
/// @notice Event emitted when collateral activation status is changed
event CollateralActivationChanged(address indexed collateral, bool status);
/// @notice Event emitted when market existence status is changed
event MarketExistenceChanged(address indexed market, bool status);
/// @notice Event emitted when collateral existence status is changed
event CollateralExistenceChanged(address indexed collateral, bool status);
/// @notice Event emitted when market borrow rate is changed
event BorrowRateChanged(address indexed market, uint256 newRate, uint256 oldRate);
/// @notice Event emitted when market suppliers share rate is changed
event SuppliersShareRateChanged(address indexed market, uint256 newRate, uint256 oldRate);
/// @notice Event emitted when market promotion rate is changed
event PromotionRateChanged(address indexed market, uint256 newRate, uint256 oldRate);
/// @notice Event emitted when collateral value to loan rate is changed
event ValueToLoanRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate);
/// @notice Event emitted when collateral penalty rate is changed
event PenaltyRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate);
/// @notice Event emitted when collateral bonus rate is changed
event BonusRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate);
/// @dev Modifier to make a function callable only when the market is exist
/// @param market Address of the given market
modifier marketIsExist(address market) {
require (marketAssets[market].isExist, "SE01");
_;
}
/// @dev Modifier to make a function callable only when the collateral is exist
/// @param collateral Address of the given collateral
modifier collateralIsExist(address collateral) {
require (collateralAssets[collateral].isExist, "SE02");
_;
}
/// @notice you cannot send ETH to this contract
receive() external payable {
revert();
}
/// @notice Activate a market asset
/// @dev Can only be called by the owner
/// @param market Address of the given market
function activateMarket (address market) external onlyOwner marketIsExist(market) {
activateMarketInternal(market);
}
/// @notice Deactivate a market asset
/// @dev Can only be called by the owner
/// @param market Address of the given market
function deactivateMarket (address market) external onlyOwner marketIsExist(market) {
marketAssets[market].isActive = false;
emit MarketActivationChanged(market, false);
}
/// @notice Activate a collateral asset
/// @dev Can only be called by the owner
/// @param collateral Address the given collateral
function activateCollateral (address collateral) external onlyOwner collateralIsExist(collateral) {
activateCollateralInternal(collateral);
}
/// @notice Deactivate a collateral asset
/// @dev Can only be called by the owner
/// @param collateral Address of the given collateral
function deactivateCollateral (address collateral) external onlyOwner collateralIsExist(collateral) {
collateralAssets[collateral].isActive = false;
emit CollateralActivationChanged(collateral, false);
}
/// @notice Returns the list of markets
/// @return res List of markets
function getMarketsList() external view returns (address[] memory res) {
res = marketsList;
}
/// @notice Disposable function to interact with Holdefi contract
/// @dev Can only be called by the owner
/// @param holdefiContractAddress Address of the Holdefi contract
function setHoldefiContract(HoldefiInterface holdefiContractAddress) external onlyOwner {
require (holdefiContractAddress.holdefiSettings() == address(this), "SE03");
require (address(holdefiContract) == address(0), "SE04");
holdefiContract = holdefiContractAddress;
}
/// @notice Returns supply, borrow and promotion rate of the given market
/// @dev supplyRate = (totalBorrow * borrowRate) * suppliersShareRate / totalSupply
/// @param market Address of the given market
/// @return borrowRate Borrow rate of the given market
/// @return supplyRateBase Supply rate base of the given market
/// @return promotionRate Promotion rate of the given market
function getInterests (address market)
external
view
returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate)
{
uint256 totalBorrow = holdefiContract.marketAssets(market).totalBorrow;
uint256 totalSupply = holdefiContract.marketAssets(market).totalSupply;
borrowRate = marketAssets[market].borrowRate;
if (totalSupply == 0) {
supplyRateBase = 0;
}
else {
uint256 totalInterestFromBorrow = totalBorrow.mul(borrowRate);
uint256 suppliersShare = totalInterestFromBorrow.mul(marketAssets[market].suppliersShareRate).div(rateDecimals);
supplyRateBase = suppliersShare.div(totalSupply);
}
promotionRate = marketAssets[market].promotionRate;
}
/// @notice Set promotion rate for a market
/// @dev Can only be called by the owner
/// @param market Address of the given market
/// @param newPromotionRate New promotion rate
function setPromotionRate (address market, uint256 newPromotionRate) external onlyOwner {
require (newPromotionRate <= maxPromotionRate, "SE05");
holdefiContract.reserveSettlement(market);
emit PromotionRateChanged(market, newPromotionRate, marketAssets[market].promotionRate);
marketAssets[market].promotionRate = newPromotionRate;
}
/// @notice Reset promotion rate of the market to zero
/// @dev Can only be called by holdefi contract
/// @param market Address of the given market
function resetPromotionRate (address market) external {
require (msg.sender == address(holdefiContract), "SE06");
emit PromotionRateChanged(market, 0, marketAssets[market].promotionRate);
marketAssets[market].promotionRate = 0;
}
/// @notice Set borrow rate for a market
/// @dev Can only be called by the owner
/// @param market Address of the given market
/// @param newBorrowRate New borrow rate
function setBorrowRate (address market, uint256 newBorrowRate)
external
onlyOwner
marketIsExist(market)
{
setBorrowRateInternal(market, newBorrowRate);
}
/// @notice Set suppliers share rate for a market
/// @dev Can only be called by the owner
/// @param market Address of the given market
/// @param newSuppliersShareRate New suppliers share rate
function setSuppliersShareRate (address market, uint256 newSuppliersShareRate)
external
onlyOwner
marketIsExist(market)
{
setSuppliersShareRateInternal(market, newSuppliersShareRate);
}
/// @notice Set value to loan rate for a collateral
/// @dev Can only be called by the owner
/// @param collateral Address of the given collateral
/// @param newValueToLoanRate New value to loan rate
function setValueToLoanRate (address collateral, uint256 newValueToLoanRate)
external
onlyOwner
collateralIsExist(collateral)
{
setValueToLoanRateInternal(collateral, newValueToLoanRate);
}
/// @notice Set penalty rate for a collateral
/// @dev Can only be called by the owner
/// @param collateral Address of the given collateral
/// @param newPenaltyRate New penalty rate
function setPenaltyRate (address collateral, uint256 newPenaltyRate)
external
onlyOwner
collateralIsExist(collateral)
{
setPenaltyRateInternal(collateral, newPenaltyRate);
}
/// @notice Set bonus rate for a collateral
/// @dev Can only be called by the owner
/// @param collateral Address of the given collateral
/// @param newBonusRate New bonus rate
function setBonusRate (address collateral, uint256 newBonusRate)
external
onlyOwner
collateralIsExist(collateral)
{
setBonusRateInternal(collateral, newBonusRate);
}
/// @notice Add a new asset as a market
/// @dev Can only be called by the owner
/// @param market Address of the new market
/// @param borrowRate BorrowRate of the new market
/// @param suppliersShareRate SuppliersShareRate of the new market
function addMarket (address market, uint256 borrowRate, uint256 suppliersShareRate)
external
onlyOwner
{
require (!marketAssets[market].isExist, "SE08");
require (marketsList.length < maxListsLength, "SE09");
marketsList.push(market);
marketAssets[market].isExist = true;
emit MarketExistenceChanged(market, true);
setBorrowRateInternal(market, borrowRate);
setSuppliersShareRateInternal(market, suppliersShareRate);
activateMarketInternal(market);
}
/// @notice Remove a market asset
/// @dev Can only be called by the owner
/// @param market Address of the given market
function removeMarket (address market) external onlyOwner marketIsExist(market) {
require (holdefiContract.marketAssets(market).totalBorrow == 0, "SE10");
holdefiContract.beforeChangeBorrowRate(market);
uint256 index;
uint256 marketListLength = marketsList.length;
for (uint256 i = 0 ; i < marketListLength ; i++) {
if (marketsList[i] == market) {
index = i;
}
}
marketsList[index] = marketsList[marketListLength-1];
marketsList.pop();
delete marketAssets[market];
emit MarketExistenceChanged(market, false);
}
/// @notice Add a new asset as a collateral
/// @dev Can only be called by the owner
/// @param collateral Address of the new collateral
/// @param valueToLoanRate ValueToLoanRate of the new collateral
/// @param penaltyRate PenaltyRate of the new collateral
/// @param bonusRate BonusRate of the new collateral
function addCollateral (
address collateral,
uint256 valueToLoanRate,
uint256 penaltyRate,
uint256 bonusRate
)
external
onlyOwner
{
require (!collateralAssets[collateral].isExist, "SE07");
collateralAssets[collateral].isExist = true;
emit CollateralExistenceChanged(collateral, true);
setValueToLoanRateInternal(collateral, valueToLoanRate);
setPenaltyRateInternal(collateral, penaltyRate);
setBonusRateInternal(collateral, bonusRate);
activateCollateralInternal(collateral);
}
/// @notice Activate the market
function activateMarketInternal (address market) internal {
marketAssets[market].isActive = true;
emit MarketActivationChanged(market, true);
}
/// @notice Activate the collateral
function activateCollateralInternal (address collateral) internal {
collateralAssets[collateral].isActive = true;
emit CollateralActivationChanged(collateral, true);
}
/// @notice Set borrow rate operation
function setBorrowRateInternal (address market, uint256 newBorrowRate) internal {
require (newBorrowRate <= maxBorrowRate, "SE05");
uint256 currentTime = block.timestamp;
if (marketAssets[market].borrowRateUpdateTime != 0) {
if (newBorrowRate > marketAssets[market].borrowRate) {
uint256 deltaTime = currentTime.sub(marketAssets[market].borrowRateUpdateTime);
require (deltaTime >= periodBetweenUpdates, "SE11");
uint256 maxIncrease = marketAssets[market].borrowRate.add(borrowRateMaxIncrease);
require (newBorrowRate <= maxIncrease, "SE12");
}
holdefiContract.beforeChangeBorrowRate(market);
}
emit BorrowRateChanged(market, newBorrowRate, marketAssets[market].borrowRate);
marketAssets[market].borrowRate = newBorrowRate;
marketAssets[market].borrowRateUpdateTime = currentTime;
}
/// @notice Set suppliers share rate operation
function setSuppliersShareRateInternal (address market, uint256 newSuppliersShareRate) internal {
require (
newSuppliersShareRate >= minSuppliersShareRate && newSuppliersShareRate <= rateDecimals,
"SE05"
);
uint256 currentTime = block.timestamp;
if (marketAssets[market].suppliersShareRateUpdateTime != 0) {
if (newSuppliersShareRate < marketAssets[market].suppliersShareRate) {
uint256 deltaTime = currentTime.sub(marketAssets[market].suppliersShareRateUpdateTime);
require (deltaTime >= periodBetweenUpdates, "SE11");
uint256 decreasedAllowed = newSuppliersShareRate.add(suppliersShareRateMaxDecrease);
require (
marketAssets[market].suppliersShareRate <= decreasedAllowed,
"SE12"
);
}
holdefiContract.beforeChangeSupplyRate(market);
}
emit SuppliersShareRateChanged(
market,
newSuppliersShareRate,
marketAssets[market].suppliersShareRate
);
marketAssets[market].suppliersShareRate = newSuppliersShareRate;
marketAssets[market].suppliersShareRateUpdateTime = currentTime;
}
/// @notice Set value to loan rate operation
function setValueToLoanRateInternal (address collateral, uint256 newValueToLoanRate) internal {
require (
newValueToLoanRate <= maxValueToLoanRate &&
collateralAssets[collateral].penaltyRate.add(fivePercentLiquidationGap) <= newValueToLoanRate,
"SE05"
);
uint256 currentTime = block.timestamp;
if (
collateralAssets[collateral].VTLUpdateTime != 0 &&
newValueToLoanRate > collateralAssets[collateral].valueToLoanRate
) {
uint256 deltaTime = currentTime.sub(collateralAssets[collateral].VTLUpdateTime);
require (deltaTime >= periodBetweenUpdates,"SE11");
uint256 maxIncrease = collateralAssets[collateral].valueToLoanRate.add(
valueToLoanRateMaxIncrease
);
require (newValueToLoanRate <= maxIncrease,"SE12");
}
emit ValueToLoanRateChanged(
collateral,
newValueToLoanRate,
collateralAssets[collateral].valueToLoanRate
);
collateralAssets[collateral].valueToLoanRate = newValueToLoanRate;
collateralAssets[collateral].VTLUpdateTime = currentTime;
}
/// @notice Set penalty rate operation
function setPenaltyRateInternal (address collateral, uint256 newPenaltyRate) internal {
require (
newPenaltyRate <= maxPenaltyRate &&
newPenaltyRate <= collateralAssets[collateral].valueToLoanRate.sub(fivePercentLiquidationGap) &&
collateralAssets[collateral].bonusRate <= newPenaltyRate,
"SE05"
);
uint256 currentTime = block.timestamp;
if (
collateralAssets[collateral].penaltyUpdateTime != 0 &&
newPenaltyRate > collateralAssets[collateral].penaltyRate
) {
uint256 deltaTime = currentTime.sub(collateralAssets[collateral].penaltyUpdateTime);
require (deltaTime >= periodBetweenUpdates, "SE11");
uint256 maxIncrease = collateralAssets[collateral].penaltyRate.add(penaltyRateMaxIncrease);
require (newPenaltyRate <= maxIncrease, "SE12");
}
emit PenaltyRateChanged(collateral, newPenaltyRate, collateralAssets[collateral].penaltyRate);
collateralAssets[collateral].penaltyRate = newPenaltyRate;
collateralAssets[collateral].penaltyUpdateTime = currentTime;
}
/// @notice Set Bonus rate operation
function setBonusRateInternal (address collateral, uint256 newBonusRate) internal {
require (
newBonusRate <= collateralAssets[collateral].penaltyRate && newBonusRate >= rateDecimals,
"SE05"
);
emit BonusRateChanged(collateral, newBonusRate, collateralAssets[collateral].bonusRate);
collateralAssets[collateral].bonusRate = newBonusRate;
}
}
|
Set promotion rate for a market Can only be called by the owner market Address of the given market newPromotionRate New promotion rate
|
function setPromotionRate (address market, uint256 newPromotionRate) external onlyOwner {
require (newPromotionRate <= maxPromotionRate, "SE05");
holdefiContract.reserveSettlement(market);
emit PromotionRateChanged(market, newPromotionRate, marketAssets[market].promotionRate);
marketAssets[market].promotionRate = newPromotionRate;
}
| 626,486 |
pragma solidity ^0.4.25;
pragma experimental ABIEncoderV2;
import "./Table.sol";
contract Asset {
//State variables
string Bank_name = "bank";
int256 Bank_asset_value = 99999;
// event
// 建表
event CreateTableEvent(int count);
// 资产注册
event RegisterEvent(int256 ret, string account, int256 asset_value);
// 资产额度转移
event TransferEvent(int256 ret, string from_account, string to_account, int256 asset_value);
// 签发应收账款交易上链(添加交易)
event CreateReceiptEvent(int256 ret, string id, string borrower, string debtee, int256 money);
// 应收账款的转让上链(拆分交易)
event DivideReceiptEvent(int256 ret, string original_id, string new_id, string newDebtee, int256 money);
// 利用应收账款向银行融资上链(融资)
event FinanceReceiptEvent(int256 ret, string id, string financer, int256 money);
// 应收账款支付结算上链(返还交易)
event RepayReceiptEvent(int256 ret, string id, int256 money);
constructor() public {
// 构造函数中创建t_asset表
createTable();
// 注册银行账号
register(Bank_name, Bank_asset_value);
}
function createTable() public returns(int) {
int count = 0;
TableFactory tf = TableFactory(0x1001);
// 资产管理表, key : account, field : asset_value
// | 资产账户(主键) | 资产额度 |
// |-------------------- |-------------------|
// | account | asset_value |
// |---------------------|-------------------|
//
// 创建资产管理表
count += tf.createTable("t_asset", "account", "asset_value");
// 交易记录表, key: id, field: borrower, debtee, money, status
// | 交易单号(key) | 借债人 | 债权人 | 债务金额 | 状态 |
// |-------------|------|-------|---------|---------|
// | id | borrower | debtee | money | status |
// |-------------|------|-------|---------|---------|
// 创建交易记录表
count += tf.createTable("t_receipt", "id","borrower, debtee, money, status");
emit CreateTableEvent(count);
return count;
}
// 返回资产管理表
function openAssetTable() private returns(Table) {
TableFactory tf = TableFactory(0x1001);
Table table = tf.openTable("t_asset");
return table;
}
// 返回交易记录表
function openReceiptTable() private returns(Table) {
TableFactory tf = TableFactory(0x1001);
Table table = tf.openTable("t_receipt");
return table;
}
/*
描述 : 资产注册
参数 :
account : 资产账户
asset_value : 资产金额
返回值:
0 资产注册成功
-1 资产账户已存在
-2 其他错误
*/
function register(string account, int256 asset_value) public returns(int256){
int256 ret_code = 0;
int256 ret = 0;
int256 temp_asset_value = 0;
// 查询账户是否存在
(ret, temp_asset_value) = selectAccount(account);
if(ret != 0) {
Table table = openAssetTable();
Entry entry_register = table.newEntry();
entry_register.set("account", account);
entry_register.set("asset_value", int256(asset_value));
// 插入
int count = table.insert(account, entry_register);
if (count == 1) {
// 成功
ret_code = 0;
} else {
// 失败? 无权限或者其他错误
ret_code = -2;
table.remove(account, table.newCondition());
}
} else {
// 账户已存在
ret_code = -1;
}
emit RegisterEvent(ret_code, account, asset_value);
return ret_code;
}
/*
描述 : 根据资产账户查询资产金额
参数 :
account : 资产账户
返回值:
参数一: 成功返回 0, 账户不存在返回 -1
参数二: 第一个参数为 0 时有效,代表资产金额
*/
function selectAccount(string account) public constant returns(int256, int256) {
// 打开表
Table table = openAssetTable();
// 查询
Entries entries_account = table.select(account, table.newCondition());
int256 asset_value = 0;
if (0 == int256(entries_account.size())) {
return (-1, asset_value);
} else {
Entry entry = entries_account.get(0);
return (0, int256(entry.getInt("asset_value")));
}
}
/*
描述 : 根据交易 ID 查询交易信息
参数 :
id : 交易编号
返回值:
参数一: 若成功返回 0
参数二: 若成功数组首个元素为初始交易金额, 第二个为未结清金额
参数三: 若成功则第一个元素为债权人, 第二个为借债人
*/
function selectReceipt(string id) public constant returns(int256, int256[], string[]) {
// 打开表
Table table = openReceiptTable();
// 查询
Entries entries_receipt = table.select(id, table.newCondition());
// ret_code
int256 ret_code = 0;
// money, status
int256[] memory info_list = new int256[](2);
// borrower, debtee
string[] memory user_list = new string[](2);
if (0 == int256(entries_receipt.size())) {
ret_code = -1;
return (ret_code, info_list, user_list);
} else {
Entry entry = entries_receipt.get(0);
info_list[0] = entry.getInt("money");
info_list[1] = entry.getInt("status");
user_list[0] = entry.getString("borrower");
user_list[1] = entry.getString("debtee");
return (ret_code, info_list, user_list);
}
}
/*
描述 : 资产转移
参数 :
from_account : 转移资产账户
to_account : 接收资产账户
asset_value : 转移金额
返回值:
0 资产转移成功
-1 转移资产账户不存在
-2 接收资产账户不存在
-3 金额不足
-4 金额溢出
-5 其他错误
*/
function transfer(string from_account, string to_account, int256 asset_value) public returns(int256) {
// 查询转移资产账户信息
int ret_code = 0;
int256 ret = 0;
int256 from_asset_value = 0;
int256 to_asset_value = 0;
// 转移账户是否存在?
(ret, from_asset_value) = selectAccount(from_account);
if(ret != 0) {
ret_code = -1;
// 转移账户不存在
emit TransferEvent(ret_code, from_account, to_account, asset_value);
return ret_code;
}
// 接受账户是否存在?
(ret, to_asset_value) = selectAccount(to_account);
if(ret != 0) {
ret_code = -2;
// 接收资产的账户不存在
emit TransferEvent(ret_code, from_account, to_account, asset_value);
return ret_code;
}
if(from_asset_value < asset_value) {
ret_code = -3;
// 转移资产的账户金额不足
emit TransferEvent(ret_code, from_account, to_account, asset_value);
return ret_code;
}
if (to_asset_value + asset_value < to_asset_value) {
ret_code = -4;
// 接收账户金额溢出
emit TransferEvent(ret_code, from_account, to_account, asset_value);
return ret_code;
}
Table table = openAssetTable();
Entry entry_from = table.newEntry();
entry_from.set("account", from_account);
entry_from.set("asset_value", int256(from_asset_value - asset_value));
// 更新转账账户
int count = table.update(from_account, entry_from, table.newCondition());
if(count != 1) {
ret_code = -5;
// 失败? 无权限或者其他错误?
emit TransferEvent(ret_code, from_account, to_account, asset_value);
return ret_code;
}
Entry entry_to = table.newEntry();
entry_to.set("account", to_account);
entry_to.set("asset_value", int256(to_asset_value + asset_value));
// 更新接收账户
table.update(to_account, entry_to, table.newCondition());
emit TransferEvent(ret_code, from_account, to_account, asset_value);
return ret_code;
}
/*
描述 : 签发应收账款交易上链(添加交易)
参数 :
id : 交易编号
borrower : 借债人
debtee : 债权人
transaction_money: 初始交易金额
返回值:
0 交易添加成功
-1 交易已存在
-2 资产转移错误
-3 借债人资产额度不够
-4 其他错误
*/
function createReceipt(string id, string borrower, string debtee, int256 transaction_money) public returns(int256){
int256 ret_code = 0;
int256 ret = 0;
int256 asset_value = 0;
int isExist = 0;
int256[] memory info_list = new int256[](2);
string[] memory user_list = new string[](2);
// 查询交易是否存在
(isExist, info_list, user_list) = selectReceipt(id);
if(isExist != int256(0)) {
// 打开表
Table table = openReceiptTable();
// 查询
Entry entry_receipt = table.newEntry();
entry_receipt.set("id", id);
entry_receipt.set("borrower", borrower);
entry_receipt.set("debtee", debtee);
entry_receipt.set("money", int256(transaction_money));
entry_receipt.set("status", int256(transaction_money));
// 插入
int count = table.insert(id, entry_receipt);
if (count == 1) {
// 查询借债人的资产额度
(ret, asset_value) = selectAccount(borrower);
if (asset_value > 1000) {
// 将借债人的资产额度转移一部分给债权人
ret = transfer(borrower,debtee,transaction_money);
// 资产额度转让失败
if(ret != 0) {
ret_code = -2;
} else {
ret_code = 0;
}
} else {
// 借债人资产额度不够;
ret_code = -3;
}
} else {
// 失败? 无权限或者其他错误
ret_code = -4;
}
} else {
// 交易已存在
ret_code = -1;
}
// 如果交易创建失败,将记录清除
if(ret_code != 0) {
table.remove(id, table.newCondition());
}
emit CreateReceiptEvent(ret_code, id, borrower, debtee, transaction_money);
return ret_code;
}
/*
描述 : 应收账款的转让上链(拆分交易)
参数 :
original_id: 需要转让的交易 ID
new_id: 新创建的交易 ID
newDebtee: 新创建交易的债权人
divide_money: 交易拆分的金额
返回值 :
0 交易转让成功
-1 转让的交易不存在
-2 账户不存在
-3 转让的金额大于原交易未结算的金额
-4 资产返还错误
-5 新交易创建不成功
*/
function divideReceipt(string original_id, string new_id, string newDebtee, int256 divide_money) public returns(int256) {
int256 ret_code = 0;
int256 ret = 0;
int256 isExist = 0;
int256[] memory info_list = new int256[](2);
string[] memory user_list = new string[](2);
// 查询该欠条是否存在
(isExist, info_list, user_list) = selectReceipt(original_id);
if(isExist == 0) {
int temp = 0;
// 查询账户是否存在
(ret, temp) = selectAccount(newDebtee);
if(ret != 0) {
ret_code = -2;
emit DivideReceiptEvent(ret_code, original_id, new_id, newDebtee, divide_money);
return ret_code;
}
// 转让的金额大于原交易未结算的金额
if(divide_money > info_list[1]){
ret_code = -3;
emit DivideReceiptEvent(ret_code, original_id, new_id, newDebtee, divide_money);
return ret_code;
}
// debtee 把 borrower 借的债转让给 newDebtee,debtee 资产额度转移给 newDebtee,分为两步
// 1. borrower 还债给 debtee
ret = repayReceipt(original_id, divide_money);
if (ret != 0) {
ret_code = -4;
emit DivideReceiptEvent(ret_code, original_id, new_id, newDebtee, divide_money);
return ret_code;
}
// 2. borrower 向 newDebtee 借债
ret = createReceipt(new_id, user_list[0], newDebtee, divide_money);
if (ret != 0) {
// 新交易创建不成功
ret_code = -5;
emit DivideReceiptEvent(ret_code, original_id, new_id, newDebtee, divide_money);
return ret_code;
}
} else { // 转让的交易不存在
ret_code = -1;
}
emit DivideReceiptEvent(ret_code, original_id, new_id, newDebtee, divide_money);
return ret_code;
}
/*
描述 : 利用应收账款向银行融资上链(融资)
参数 :
id : 融资编号
financer : 融资人
finance_money: 金额
返回值:
0 融资成功
-1 融资人不存在
-2 融资额大于融资人目前的资产额度
-3 其他错误
*/
function financeReceipt(string id, string financer , int256 finance_money) public returns(int256) {
int256 ret_code = 0;
int256 ret = 0;
int256 isExist = 0;
int256 asset_value = 0;
// 查询融资人是否存在
(isExist, asset_value) = selectAccount(financer);
if(isExist == 0) { // 融资人存在
// 融资人目前的资产额度大于等于融资额
if (asset_value >= finance_money) {
// 向银行申请融资
ret = createReceipt(id, financer, "bank", finance_money);
if (ret != 0) {
ret_code = -3;
emit FinanceReceiptEvent(ret_code, id, financer, finance_money);
return ret_code;
}
} else {
ret_code = -2;
emit FinanceReceiptEvent(ret_code, id, financer, finance_money);
return ret_code;
}
} else { // 融资人不存在
ret_code = -1;
}
emit FinanceReceiptEvent(ret_code, id, financer, finance_money);
return ret_code;
}
/*
描述 : 应收账款支付结算上链(结算交易)
参数 :
id : 交易编号
repay_money: 金额
返回值:
0 交易结算成功
-1 交易不存在
-2 还债金额大于借款
-3 其他错误
-4 资产返还错误
*/
function repayReceipt(string id, int256 repay_money) public returns(int256){
int256 ret_code = 0;
int256 isExist = 0;
int256[] memory info_list = new int256[](2);
string[] memory user_list = new string[](2);
// 查询该交易是否存在
(isExist, info_list, user_list) = selectReceipt(id);
if(isExist == 0) { // 交易存在
// 还款金额大于欠款
if(repay_money > info_list[1]){
ret_code = -2;
emit RepayReceiptEvent(ret_code, id, repay_money);
return (ret_code);
}
// 更新交易状态
Table table = openReceiptTable();
Entry entry0 = table.newEntry();
entry0.set("id", id);
entry0.set("borrower", user_list[0]);
entry0.set("debtee", user_list[1]);
entry0.set("money", info_list[0]);
// 未结算金额减少
entry0.set("status", (info_list[1] - repay_money));
// 更新交易信息
int count = table.update(id, entry0, table.newCondition());
if(count != 1) {
ret_code = -3;
// 失败? 无权限或者其他错误?
emit RepayReceiptEvent(ret_code, id, repay_money);
return (ret_code);
}
// 资产返还
int256 temp = transfer(user_list[1], user_list[0], repay_money);
if(temp != 0){
ret_code = -4;
emit RepayReceiptEvent(ret_code, id, repay_money);
return (ret_code);
}
ret_code = 0;
} else { // 交易不存在
ret_code = -1;
}
emit RepayReceiptEvent(ret_code, id, repay_money);
return ret_code;
}
}
|
/ 查询账户是否存在 插入 成功 失败? 无权限或者其他错误
|
function register(string account, int256 asset_value) public returns(int256){
int256 ret_code = 0;
int256 ret = 0;
int256 temp_asset_value = 0;
(ret, temp_asset_value) = selectAccount(account);
if(ret != 0) {
Table table = openAssetTable();
Entry entry_register = table.newEntry();
entry_register.set("account", account);
entry_register.set("asset_value", int256(asset_value));
int count = table.insert(account, entry_register);
if (count == 1) {
ret_code = 0;
ret_code = -2;
table.remove(account, table.newCondition());
}
}
emit RegisterEvent(ret_code, account, asset_value);
return ret_code;
}
参数 :
account : 资产账户
返回值:
参数一: 成功返回 0, 账户不存在返回 -1
参数二: 第一个参数为 0 时有效,代表资产金额
| 1,804,812 |
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
import "./uniswapv2/interfaces/IUniswapV2Router02.sol";
/// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract.
/// The only owner function is `init` which is to setup for the first time after deployment.
/// After init finished, owner will be renounced automatically. owner() function will return 0x0 address.
contract DevTreasury is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @dev Developer wallet
address payable public devWallet;
/// @dev SDVD contract address
address public sdvd;
/// @dev Uniswap router
IUniswapV2Router02 uniswapRouter;
/// @dev Uniswap factory
IUniswapV2Factory uniswapFactory;
/// @dev WETH address
address weth;
/// @dev Uniswap LP address
address public pairAddress;
/// @notice Release balance every 1 hour to dev wallet
uint256 public releaseThreshold = 1 hours;
/// @dev Last release timestamp
uint256 public releaseTime;
constructor (address _uniswapRouter, address _sdvd) public {
// Set dev wallet
devWallet = msg.sender;
// Set uniswap router
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
// Set uniswap factory
uniswapFactory = IUniswapV2Factory(uniswapRouter.factory());
// Get weth address
weth = uniswapRouter.WETH();
// Set SDVD address
sdvd = _sdvd;
// Approve uniswap router to spend sdvd
IERC20(sdvd).approve(_uniswapRouter, uint256(- 1));
// Set initial release time
releaseTime = block.timestamp;
}
/* ========== Owner Only ========== */
function init() external onlyOwner {
// Get pair address after init because we wait until pair created in lord of coin
pairAddress = uniswapFactory.getPair(sdvd, weth);
// Renounce ownership immediately after init
renounceOwnership();
}
/* ========== Mutative ========== */
/// @notice Release SDVD to market regardless the price so dev doesn't own any SDVD from 0.5% fee.
/// This is to protect SDVD holders.
function release() external {
_release();
}
/* ========== Internal ========== */
function _release() internal {
if (releaseTime.add(releaseThreshold) <= block.timestamp) {
// Update release time
releaseTime = block.timestamp;
// Get SDVD balance
uint256 sdvdBalance = IERC20(sdvd).balanceOf(address(this));
// If there is SDVD in this contract
// and there is enough liquidity to swap
if (sdvdBalance > 0 && IERC20(sdvd).balanceOf(pairAddress) >= sdvdBalance) {
address[] memory path = new address[](2);
path[0] = sdvd;
path[1] = weth;
// Swap SDVD to ETH on uniswap
// uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline
uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
sdvdBalance,
0,
path,
devWallet,
block.timestamp.add(30 minutes)
);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
// SPDX-License-Identifier: Unlicensed
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
import "./uniswapv2/interfaces/IUniswapV2Router02.sol";
import "./uniswapv2/interfaces/IWETH.sol";
import "./interfaces/ILordOfCoin.sol";
import "./interfaces/IBPool.sol";
/// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract.
/// The only owner function is `init` which is to setup for the first time after deployment.
/// After init finished, owner will be renounced automatically. owner() function will return 0x0 address.
contract TradingTreasury is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event Received(address indexed from, uint256 amount);
/// @dev Lord of coin address
address public controller;
/// @dev Uniswap router
IUniswapV2Router02 uniswapRouter;
/// @dev Uniswap factory
IUniswapV2Factory uniswapFactory;
/// @dev Balancer pool WETH-MUSD
address balancerPool;
/// @dev WETH address
address weth;
/// @dev mUSD contract address
address musd;
/// @dev SDVD contract address
address public sdvd;
/// @dev Uniswap LP address
address public pairAddress;
/// @notice Release balance as sharing pool profit every 1 hour
uint256 public releaseThreshold = 1 hours;
/// @dev Last release timestamp
uint256 public releaseTime;
constructor (address _uniswapRouter, address _balancerPool, address _sdvd, address _musd) public {
// Set uniswap router
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
// Set uniswap factory
uniswapFactory = IUniswapV2Factory(uniswapRouter.factory());
// Get weth address
weth = uniswapRouter.WETH();
// Set balancer pool
balancerPool = _balancerPool;
// Set SDVD address
sdvd = _sdvd;
// Set mUSD address
musd = _musd;
// Approve uniswap to spend SDVD
IERC20(sdvd).approve(_uniswapRouter, uint256(- 1));
// Approve balancer to spend WETH
IERC20(weth).approve(balancerPool, uint256(- 1));
// Set initial release time
releaseTime = block.timestamp;
}
receive() external payable {
emit Received(msg.sender, msg.value);
}
/* ========== Owner Only ========== */
function init(address _controller) external onlyOwner {
// Set Lord of coin address
controller = _controller;
// Get pair address
pairAddress = ILordOfCoin(controller).sdvdEthPairAddress();
// Renounce ownership immediately after init
renounceOwnership();
}
/* ========== Mutative ========== */
/// @notice Release SDVD to be added as profit
function release() external {
_release();
}
/* ========== Internal ========== */
function _release() internal {
if (releaseTime.add(releaseThreshold) <= block.timestamp) {
// Update release time
releaseTime = block.timestamp;
// Get SDVD balance
uint256 sdvdBalance = IERC20(sdvd).balanceOf(address(this));
// If there is SDVD in this contract
// and there is enough liquidity to swap
if (sdvdBalance > 0 && IERC20(sdvd).balanceOf(pairAddress) >= sdvdBalance) {
// Use uniswap since this contract is registered as no fee address for swapping SDVD to ETH
// Swap path
address[] memory path = new address[](2);
path[0] = sdvd;
path[1] = weth;
// Swap SDVD to ETH on uniswap
// uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline
uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
sdvdBalance,
0,
path,
address(this),
block.timestamp.add(30 minutes)
);
// Get all ETH in this contract
uint256 ethAmount = address(this).balance;
// Convert ETH to WETH
IWETH(weth).deposit{ value: ethAmount }();
// Swap WETH to mUSD
(uint256 musdAmount,) = IBPool(balancerPool).swapExactAmountIn(weth, ethAmount, musd, 0, uint256(-1));
// Send it to Lord of Coin
IERC20(musd).safeTransfer(controller, musdAmount);
// Deposit profit
ILordOfCoin(controller).depositTradingProfit(musdAmount);
}
}
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface ILordOfCoin {
function marketOpenTime() external view returns (uint256);
function dvd() external view returns (address);
function sdvd() external view returns (address);
function sdvdEthPairAddress() external view returns (address);
function buy(uint256 musdAmount) external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD);
function buyTo(address recipient, uint256 musdAmount) external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD);
function buyFromETH() payable external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD);
function sell(uint256 dvdAmount) external returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD);
function sellTo(address recipient, uint256 dvdAmount) external returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD);
function sellToETH(uint256 dvdAmount) external returns (uint256 returnedETH, uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD);
function claimDividend() external returns (uint256 net, uint256 fee);
function claimDividendTo(address recipient) external returns (uint256 net, uint256 fee);
function claimDividendETH() external returns (uint256 net, uint256 fee, uint256 receivedETH);
function checkSnapshot() external;
function releaseTreasury() external;
function depositTradingProfit(uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface IBPool {
function isPublicSwap() external view returns (bool);
function isFinalized() external view returns (bool);
function isBound(address t) external view returns (bool);
function getNumTokens() external view returns (uint);
function getCurrentTokens() external view returns (address[] memory tokens);
function getFinalTokens() external view returns (address[] memory tokens);
function getDenormalizedWeight(address token) external view returns (uint);
function getTotalDenormalizedWeight() external view returns (uint);
function getNormalizedWeight(address token) external view returns (uint);
function getBalance(address token) external view returns (uint);
function getSwapFee() external view returns (uint);
function getController() external view returns (address);
function setSwapFee(uint swapFee) external;
function setController(address manager) external;
function setPublicSwap(bool public_) external;
function finalize() external;
function bind(address token, uint balance, uint denorm) external;
function rebind(address token, uint balance, uint denorm) external;
function unbind(address token) external;
function gulp(address token) external;
function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint spotPrice);
function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint spotPrice);
function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external;
function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external;
function swapExactAmountIn(
address tokenIn,
uint tokenAmountIn,
address tokenOut,
uint minAmountOut,
uint maxPrice
) external returns (uint tokenAmountOut, uint spotPriceAfter);
function swapExactAmountOut(
address tokenIn,
uint maxAmountIn,
address tokenOut,
uint tokenAmountOut,
uint maxPrice
) external returns (uint tokenAmountIn, uint spotPriceAfter);
function joinswapExternAmountIn(
address tokenIn,
uint tokenAmountIn,
uint minPoolAmountOut
) external returns (uint poolAmountOut);
function joinswapPoolAmountOut(
address tokenIn,
uint poolAmountOut,
uint maxAmountIn
) external returns (uint tokenAmountIn);
function exitswapPoolAmountIn(
address tokenOut,
uint poolAmountIn,
uint minAmountOut
) external returns (uint tokenAmountOut);
function exitswapExternAmountOut(
address tokenOut,
uint tokenAmountOut,
uint maxPoolAmountIn
) external returns (uint poolAmountIn);
function totalSupply() external view returns (uint);
function balanceOf(address whom) external view returns (uint);
function allowance(address src, address dst) external view returns (uint);
function approve(address dst, uint amt) external returns (bool);
function transfer(address dst, uint amt) external returns (bool);
function transferFrom(
address src, address dst, uint amt
) external returns (bool);
function calcSpotPrice(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint swapFee
) external returns (uint spotPrice);
function calcOutGivenIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountIn,
uint swapFee
) external returns (uint tokenAmountOut);
function calcInGivenOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountOut,
uint swapFee
) external returns (uint tokenAmountIn);
function calcPoolOutGivenSingleIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint tokenAmountIn,
uint swapFee
) external returns (uint poolAmountOut);
function calcSingleInGivenPoolOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint poolAmountOut,
uint swapFee
) external returns (uint tokenAmountIn);
function calcSingleOutGivenPoolIn(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint poolAmountIn,
uint swapFee
) external returns (uint tokenAmountOut);
function calcPoolInGivenSingleOut(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint tokenAmountOut,
uint swapFee
) external returns (uint poolAmountIn);
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
import "./uniswapv2/interfaces/IUniswapV2Router02.sol";
import "./uniswapv2/interfaces/IWETH.sol";
import './interfaces/IERC20Snapshot.sol';
import './interfaces/ITreasury.sol';
import './interfaces/IVault.sol';
import './interfaces/IMasset.sol';
import './interfaces/IDvd.sol';
import './interfaces/ISDvd.sol';
import './interfaces/IPool.sol';
import './interfaces/IBPool.sol';
import './utils/MathUtils.sol';
/// @title Lord of Coin
/// @notice Lord of Coin finds the money, for you - to spend it.
/// @author Lord Nami
// Special thanks to TRIB as inspiration.
// Special thanks to Lord Nami mods @AspieJames, @defimoon, @tectumor, @downsin, @ghost, @LordFes, @converge, @cryptycreepy, @cryptpower, @jonsnow
// and everyone else who support this project by spreading the words on social media.
contract LordOfCoin is ReentrancyGuard {
using SafeMath for uint256;
using MathUtils for uint256;
using SafeERC20 for IERC20;
event Bought(address indexed sender, address indexed recipient, uint256 musdAmount, uint256 dvdReceived);
event Sold(address indexed sender, address indexed recipient, uint256 dvdAmount, uint256 musdReceived);
event SoldToETH(address indexed sender, address indexed recipient, uint256 dvdAmount, uint256 ethReceived);
event DividendClaimed(address indexed recipient, uint256 musdReceived);
event DividendClaimedETH(address indexed recipient, uint256 ethReceived);
event Received(address indexed from, uint256 amount);
/// @notice Applied to every buy or sale of DVD.
/// @dev Tax denominator
uint256 public constant CURVE_TAX_DENOMINATOR = 10;
/// @notice Applied to every buy of DVD before bonding curve tax.
/// @dev Tax denominator
uint256 public constant BUY_TAX_DENOMINATOR = 20;
/// @notice Applied to every sale of DVD after bonding curve tax.
/// @dev Tax denominator
uint256 public constant SELL_TAX_DENOMINATOR = 10;
/// @notice The slope of the bonding curve.
uint256 public constant DIVIDER = 1000000; // 1 / multiplier 0.000001 (so that we don't deal with decimals)
/// @notice Address in which DVD are sent to be burned.
/// These DVD can't be redeemed by the reserve.
address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
/// @dev Uniswap router
IUniswapV2Router02 uniswapRouter;
/// @dev WETH token address
address weth;
/// @dev Balancer pool WETH-MUSD
address balancerPool;
/// @dev mUSD token mStable address.
address musd;
/// @notice Dvd token instance.
address public dvd;
/// @notice SDvd token instance.
address public sdvd;
/// @notice Pair address for SDVD-ETH on uniswap
address public sdvdEthPairAddress;
/// @notice SDVD-ETH farming pool.
address public sdvdEthPool;
/// @notice DVD farming pool.
address public dvdPool;
/// @notice Dev treasury.
address public devTreasury;
/// @notice Pool treasury.
address public poolTreasury;
/// @notice Trading treasury.
address public tradingTreasury;
/// @notice Total dividend earned since the contract deployment.
uint256 public totalDividendClaimed;
/// @notice Total reserve value that backs all DVD in circulation.
/// @dev Area below the bonding curve.
uint256 public totalReserve;
/// @notice Interface for integration with mStable.
address public vault;
/// @notice Current state of the application.
/// Either already open (true) or not yet (false).
bool public isMarketOpen = false;
/// @notice Market will be open on this timestamp
uint256 public marketOpenTime;
/// @notice Current snapshot id
/// Can be thought as week index, since snapshot is increased per week
uint256 public snapshotId;
/// @notice Snapshot timestamp.
uint256 public snapshotTime;
/// @notice Snapshot duration.
uint256 public SNAPSHOT_DURATION = 1 weeks;
/// @dev Total profits on each snapshot id.
mapping(uint256 => uint256) private _totalProfitSnapshots;
/// @dev Dividend paying SDVD supply on each snapshot id.
mapping(uint256 => uint256) private _dividendPayingSDVDSupplySnapshots;
/// @dev Flag to determine if account has claim their dividend on each snapshot id.
mapping(address => mapping(uint256 => bool)) private _isDividendClaimedSnapshots;
receive() external payable {
emit Received(msg.sender, msg.value);
}
constructor(
address _vault,
address _uniswapRouter,
address _balancerPool,
address _dvd,
address _sdvd,
address _sdvdEthPool,
address _dvdPool,
address _devTreasury,
address _poolTreasury,
address _tradingTreasury,
uint256 _marketOpenTime
) public {
// Set vault
vault = _vault;
// mUSD instance
musd = IVault(vault).musd();
// Approve vault to manage mUSD in this contract
_approveMax(musd, vault);
// Set uniswap router
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
// Set balancer pool
balancerPool = _balancerPool;
// Set weth address
weth = uniswapRouter.WETH();
// Approve balancer pool to manage mUSD in this contract
_approveMax(musd, balancerPool);
// Approve balancer pool to manage WETH in this contract
_approveMax(weth, balancerPool);
// Approve self to spend mUSD in this contract (used to buy from ETH / sell to ETH)
_approveMax(musd, address(this));
dvd = _dvd;
sdvd = _sdvd;
sdvdEthPool = _sdvdEthPool;
dvdPool = _dvdPool;
devTreasury = _devTreasury;
poolTreasury = _poolTreasury;
tradingTreasury = _tradingTreasury;
// Create SDVD ETH pair
sdvdEthPairAddress = IUniswapV2Factory(uniswapRouter.factory()).createPair(sdvd, weth);
// Set open time
marketOpenTime = _marketOpenTime;
// Set initial snapshot timestamp
snapshotTime = _marketOpenTime;
}
/* ========== Modifier ========== */
modifier marketOpen() {
require(isMarketOpen, 'Market not open');
_;
}
modifier onlyTradingTreasury() {
require(msg.sender == tradingTreasury, 'Only treasury');
_;
}
/* ========== Trading Treasury Only ========== */
/// @notice Deposit trading profit to vault
function depositTradingProfit(uint256 amount) external onlyTradingTreasury {
// Deposit mUSD to vault
IVault(vault).deposit(amount);
}
/* ========== Mutative ========== */
/// @notice Exchanges mUSD to DVD.
/// @dev mUSD to be exchanged needs to be approved first.
/// @param musdAmount mUSD amount to be exchanged.
function buy(uint256 musdAmount) external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) {
return _buy(msg.sender, msg.sender, musdAmount);
}
/// @notice Exchanges mUSD to DVD.
/// @dev mUSD to be exchanged needs to be approved first.
/// @param recipient Recipient of DVD token.
/// @param musdAmount mUSD amount to be exchanged.
function buyTo(address recipient, uint256 musdAmount) external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) {
return _buy(msg.sender, recipient, musdAmount);
}
/// @notice Exchanges ETH to DVD.
function buyFromETH() payable external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) {
return _buy(address(this), msg.sender, _swapETHToMUSD(address(this), msg.value));
}
/// @notice Exchanges DVD to mUSD.
/// @param dvdAmount DVD amount to be exchanged.
function sell(uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) {
return _sell(msg.sender, msg.sender, dvdAmount);
}
/// @notice Exchanges DVD to mUSD.
/// @param recipient Recipient of mUSD.
/// @param dvdAmount DVD amount to be exchanged.
function sellTo(address recipient, uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) {
return _sell(msg.sender, recipient, dvdAmount);
}
/// @notice Exchanges DVD to ETH.
/// @param dvdAmount DVD amount to be exchanged.
function sellToETH(uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedETH, uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) {
// Sell DVD and receive mUSD in this contract
(returnedMUSD, marketTax, curveTax, taxedDVD) = _sell(msg.sender, address(this), dvdAmount);
// Swap received mUSD dividend for ether and send it back to sender
returnedETH = _swapMUSDToETH(msg.sender, returnedMUSD);
emit SoldToETH(msg.sender, msg.sender, dvdAmount, returnedETH);
}
/// @notice Claim dividend in mUSD.
function claimDividend() external nonReentrant marketOpen returns (uint256 dividend) {
return _claimDividend(msg.sender, msg.sender);
}
/// @notice Claim dividend in mUSD.
/// @param recipient Recipient of mUSD.
function claimDividendTo(address recipient) external nonReentrant marketOpen returns (uint256 dividend) {
return _claimDividend(msg.sender, recipient);
}
/// @notice Claim dividend in ETH.
function claimDividendETH() external nonReentrant marketOpen returns (uint256 dividend, uint256 receivedETH) {
// Claim dividend to this contract
dividend = _claimDividend(msg.sender, address(this));
// Swap received mUSD dividend for ether and send it back to sender
receivedETH = _swapMUSDToETH(msg.sender, dividend);
emit DividendClaimedETH(msg.sender, receivedETH);
}
/// @notice Check if we need to create new snapshot.
function checkSnapshot() public {
if (isMarketOpen) {
// If time has passed for 1 week since last snapshot
// and market is open
if (snapshotTime.add(SNAPSHOT_DURATION) <= block.timestamp) {
// Update snapshot timestamp
snapshotTime = block.timestamp;
// Take new snapshot
snapshotId = ISDvd(sdvd).snapshot();
// Save the interest
_totalProfitSnapshots[snapshotId] = totalProfit();
// Save dividend paying supply
_dividendPayingSDVDSupplySnapshots[snapshotId] = dividendPayingSDVDSupply();
}
// If something wrong / there is no interest, lets try again.
if (snapshotId > 0 && _totalProfitSnapshots[snapshotId] == 0) {
_totalProfitSnapshots[snapshotId] = totalProfit();
}
}
}
/// @notice Release treasury.
function releaseTreasury() public {
if (isMarketOpen) {
ITreasury(devTreasury).release();
ITreasury(poolTreasury).release();
ITreasury(tradingTreasury).release();
}
}
/* ========== View ========== */
/// @notice Get claimable dividend for address.
/// @param account Account address.
/// @return dividend Dividend in mUSD.
function claimableDividend(address account) public view returns (uint256 dividend) {
// If there is no snapshot or already claimed
if (snapshotId == 0 || isDividendClaimedAt(account, snapshotId)) {
return 0;
}
// Get sdvd balance at snapshot
uint256 sdvdBalance = IERC20Snapshot(sdvd).balanceOfAt(account, snapshotId);
if (sdvdBalance == 0) {
return 0;
}
// Get dividend in mUSD based on SDVD balance
dividend = sdvdBalance
.mul(claimableProfitAt(snapshotId))
.div(dividendPayingSDVDSupplyAt(snapshotId));
}
/// @notice Total mUSD that is now forever locked in the protocol.
function totalLockedReserve() external view returns (uint256) {
return _calculateReserveFromSupply(dvdBurnedAmount());
}
/// @notice Total claimable profit.
/// @return Total claimable profit in mUSD.
function claimableProfit() public view returns (uint256) {
return totalProfit().div(2);
}
/// @notice Total claimable profit in snapshot.
/// @return Total claimable profit in mUSD.
function claimableProfitAt(uint256 _snapshotId) public view returns (uint256) {
return totalProfitAt(_snapshotId).div(2);
}
/// @notice Total profit.
/// @return Total profit in MUSD.
function totalProfit() public view returns (uint256) {
uint256 vaultBalance = IVault(vault).getBalance();
// Sometimes mStable returns a value lower than the
// deposit because their exchange rate gets updated after the deposit.
if (vaultBalance < totalReserve) {
vaultBalance = totalReserve;
}
return vaultBalance.sub(totalReserve);
}
/// @notice Total profit in snapshot.
/// @param _snapshotId Snapshot id.
/// @return Total profit in MUSD.
function totalProfitAt(uint256 _snapshotId) public view returns (uint256) {
return _totalProfitSnapshots[_snapshotId];
}
/// @notice Check if dividend already claimed by account.
/// @return Is dividend claimed.
function isDividendClaimedAt(address account, uint256 _snapshotId) public view returns (bool) {
return _isDividendClaimedSnapshots[account][_snapshotId];
}
/// @notice Total supply of DVD. This includes burned DVD.
/// @return Total supply of DVD in wei.
function dvdTotalSupply() public view returns (uint256) {
return IERC20(dvd).totalSupply();
}
/// @notice Total DVD that have been burned.
/// @dev These DVD are still in circulation therefore they
/// are still considered on the bonding curve formula.
/// @return Total burned DVD in wei.
function dvdBurnedAmount() public view returns (uint256) {
return IERC20(dvd).balanceOf(BURN_ADDRESS);
}
/// @notice DVD price in wei according to the bonding curve formula.
/// @return Current DVD price in wei.
function dvdPrice() external view returns (uint256) {
// price = supply * multiplier
return dvdTotalSupply().roundedDiv(DIVIDER);
}
/// @notice DVD price floor in wei according to the bonding curve formula.
/// @return Current DVD price floor in wei.
function dvdPriceFloor() external view returns (uint256) {
return dvdBurnedAmount().roundedDiv(DIVIDER);
}
/// @notice Total supply of Dividend-paying SDVD.
/// @return Total supply of SDVD in wei.
function dividendPayingSDVDSupply() public view returns (uint256) {
// Get total supply
return IERC20(sdvd).totalSupply()
// Get sdvd in uniswap pair balance
.sub(IERC20(sdvd).balanceOf(sdvdEthPairAddress))
// Get sdvd in SDVD-ETH pool
.sub(IERC20(sdvd).balanceOf(sdvdEthPool))
// Get sdvd in DVD pool
.sub(IERC20(sdvd).balanceOf(dvdPool))
// Get sdvd in pool treasury
.sub(IERC20(sdvd).balanceOf(poolTreasury))
// Get sdvd in dev treasury
.sub(IERC20(sdvd).balanceOf(devTreasury))
// Get sdvd in trading treasury
.sub(IERC20(sdvd).balanceOf(tradingTreasury));
}
/// @notice Total supply of Dividend-paying SDVD in snapshot.
/// @return Total supply of SDVD in wei.
function dividendPayingSDVDSupplyAt(uint256 _snapshotId) public view returns (uint256) {
return _dividendPayingSDVDSupplySnapshots[_snapshotId];
}
/// @notice Calculates the amount of DVD in exchange for reserve after applying bonding curve tax.
/// @param reserveAmount Reserve value in wei to use in the conversion.
/// @return Token amount in wei after the 10% tax has been applied.
function reserveToDVDTaxed(uint256 reserveAmount) external view returns (uint256) {
if (reserveAmount == 0) {
return 0;
}
uint256 tax = reserveAmount.div(CURVE_TAX_DENOMINATOR);
uint256 totalDVD = reserveToDVD(reserveAmount);
uint256 taxedDVD = reserveToDVD(tax);
return totalDVD.sub(taxedDVD);
}
/// @notice Calculates the amount of reserve in exchange for DVD after applying bonding curve tax.
/// @param tokenAmount Token value in wei to use in the conversion.
/// @return Reserve amount in wei after the 10% tax has been applied.
function dvdToReserveTaxed(uint256 tokenAmount) external view returns (uint256) {
if (tokenAmount == 0) {
return 0;
}
uint256 reserveAmount = dvdToReserve(tokenAmount);
uint256 tax = reserveAmount.div(CURVE_TAX_DENOMINATOR);
return reserveAmount.sub(tax);
}
/// @notice Calculates the amount of DVD in exchange for reserve.
/// @param reserveAmount Reserve value in wei to use in the conversion.
/// @return Token amount in wei.
function reserveToDVD(uint256 reserveAmount) public view returns (uint256) {
return _calculateReserveToDVD(reserveAmount, totalReserve, dvdTotalSupply());
}
/// @notice Calculates the amount of reserve in exchange for DVD.
/// @param tokenAmount Token value in wei to use in the conversion.
/// @return Reserve amount in wei.
function dvdToReserve(uint256 tokenAmount) public view returns (uint256) {
return _calculateDVDToReserve(tokenAmount, dvdTotalSupply(), totalReserve);
}
/* ========== Internal ========== */
/// @notice Check if market can be opened
function _checkOpenMarket() internal {
require(marketOpenTime <= block.timestamp, 'Market not open');
if (!isMarketOpen) {
// Set flag
isMarketOpen = true;
}
}
/// @notice Exchanges mUSD to DVD.
/// @dev mUSD to be exchanged needs to be approved first.
/// @param sender Address that has mUSD token.
/// @param recipient Address that will receive DVD token.
/// @param musdAmount mUSD amount to be exchanged.
function _buy(address sender, address recipient, uint256 musdAmount) internal returns (uint256 returnedDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) {
_checkOpenMarket();
checkSnapshot();
releaseTreasury();
require(musdAmount > 0, 'Cannot buy 0');
// Tax to be included as profit
marketTax = musdAmount.div(BUY_TAX_DENOMINATOR);
// Get amount after market tax
uint256 inAmount = musdAmount.sub(marketTax);
// Calculate bonding curve tax in mUSD
curveTax = inAmount.div(CURVE_TAX_DENOMINATOR);
// Convert mUSD amount to DVD amount
uint256 totalDVD = reserveToDVD(inAmount);
// Convert tax to DVD amount
taxedDVD = reserveToDVD(curveTax);
// Calculate DVD for recipient
returnedDVD = totalDVD.sub(taxedDVD);
// Transfer mUSD from sender to this contract
IERC20(musd).safeTransferFrom(sender, address(this), musdAmount);
// Deposit mUSD to vault
IVault(vault).deposit(musdAmount);
// Increase mUSD total reserve
totalReserve = totalReserve.add(inAmount);
// Send taxed DVD to burn address
IDvd(dvd).mint(BURN_ADDRESS, taxedDVD);
// Increase recipient DVD balance
IDvd(dvd).mint(recipient, returnedDVD);
// Increase user DVD Shareholder point
IDvd(dvd).increaseShareholderPoint(recipient, returnedDVD);
emit Bought(sender, recipient, musdAmount, returnedDVD);
}
/// @notice Exchanges DVD to mUSD.
/// @param sender Address that has DVD token.
/// @param recipient Address that will receive mUSD token.
/// @param dvdAmount DVD amount to be exchanged.
function _sell(address sender, address recipient, uint256 dvdAmount) internal returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) {
checkSnapshot();
releaseTreasury();
require(dvdAmount <= IERC20(dvd).balanceOf(sender), 'Insufficient balance');
require(dvdAmount > 0, 'Cannot sell 0');
require(IDvd(dvd).shareholderPointOf(sender) >= dvdAmount, 'Insufficient shareholder points');
// Convert number of DVD amount that user want to sell to mUSD amount
uint256 reserveAmount = dvdToReserve(dvdAmount);
// Calculate tax in mUSD
curveTax = reserveAmount.div(CURVE_TAX_DENOMINATOR);
// Make sure fee is enough
require(curveTax >= 1, 'Insufficient tax');
// Get net amount
uint256 net = reserveAmount.sub(curveTax);
// Calculate taxed DVD
taxedDVD = _calculateReserveToDVD(
curveTax,
totalReserve.sub(reserveAmount),
dvdTotalSupply().sub(dvdAmount)
);
// Tax to be included as profit
marketTax = net.div(SELL_TAX_DENOMINATOR);
// Get musd amount for recipient
returnedMUSD = net.sub(marketTax);
// Decrease total reserve
totalReserve = totalReserve.sub(net);
// Reduce user DVD balance
IDvd(dvd).burn(sender, dvdAmount);
// Send taxed DVD to burn address
IDvd(dvd).mint(BURN_ADDRESS, taxedDVD);
// Decrease sender DVD Shareholder point
IDvd(dvd).decreaseShareholderPoint(sender, dvdAmount);
// Redeem mUSD from vault
IVault(vault).redeem(returnedMUSD);
// Send mUSD to recipient
IERC20(musd).safeTransfer(recipient, returnedMUSD);
emit Sold(sender, recipient, dvdAmount, returnedMUSD);
}
/// @notice Claim dividend in mUSD.
/// @param sender Address that has SDVD token.
/// @param recipient Address that will receive mUSD dividend.
function _claimDividend(address sender, address recipient) internal returns (uint256 dividend) {
checkSnapshot();
releaseTreasury();
// Get dividend in mUSD based on SDVD balance
dividend = claimableDividend(sender);
require(dividend > 0, 'No dividend');
// Set dividend as claimed
_isDividendClaimedSnapshots[sender][snapshotId] = true;
// Redeem mUSD from vault
IVault(vault).redeem(dividend);
// Send dividend mUSD to user
IERC20(musd).safeTransfer(recipient, dividend);
emit DividendClaimed(recipient, dividend);
}
/// @notice Swap ETH to mUSD in this contract.
/// @param amount ETH amount.
/// @return musdAmount returned mUSD amount.
function _swapETHToMUSD(address recipient, uint256 amount) internal returns (uint256 musdAmount) {
// Convert ETH to WETH
IWETH(weth).deposit{ value: amount }();
// Swap WETH to mUSD
(musdAmount,) = IBPool(balancerPool).swapExactAmountIn(weth, amount, musd, 0, uint256(-1));
// Send mUSD
if (recipient != address(this)) {
IERC20(musd).safeTransfer(recipient, musdAmount);
}
}
/// @notice Swap mUSD to ETH in this contract.
/// @param amount mUSD Amount.
/// @return ethAmount returned ETH amount.
function _swapMUSDToETH(address recipient, uint256 amount) internal returns (uint256 ethAmount) {
// Swap mUSD to WETH
(ethAmount,) = IBPool(balancerPool).swapExactAmountIn(musd, amount, weth, 0, uint256(-1));
// Convert WETH to ETH
IWETH(weth).withdraw(ethAmount);
// Send ETH
if (recipient != address(this)) {
payable(recipient).transfer(ethAmount);
}
}
/// @notice Approve maximum value to spender
function _approveMax(address tkn, address spender) internal {
uint256 max = uint256(- 1);
IERC20(tkn).safeApprove(spender, max);
}
/**
* Supply (s), reserve (r) and token price (p) are in a relationship defined by the bonding curve:
* p = m * s
* The reserve equals to the area below the bonding curve
* r = s^2 / 2
* The formula for the supply becomes
* s = sqrt(2 * r / m)
*
* In solidity computations, we are using divider instead of multiplier (because its an integer).
* All values are decimals with 18 decimals (represented as uints), which needs to be compensated for in
* multiplications and divisions
*/
/// @notice Computes the increased supply given an amount of reserve.
/// @param _reserveDelta The amount of reserve in wei to be used in the calculation.
/// @param _totalReserve The current reserve state to be used in the calculation.
/// @param _supply The current supply state to be used in the calculation.
/// @return _supplyDelta token amount in wei.
function _calculateReserveToDVD(
uint256 _reserveDelta,
uint256 _totalReserve,
uint256 _supply
) internal pure returns (uint256 _supplyDelta) {
uint256 _reserve = _totalReserve;
uint256 _newReserve = _reserve.add(_reserveDelta);
// s = sqrt(2 * r / m)
uint256 _newSupply = MathUtils.sqrt(
_newReserve
.mul(2)
.mul(DIVIDER) // inverse the operation (Divider instead of multiplier)
.mul(1e18) // compensation for the squared unit
);
_supplyDelta = _newSupply.sub(_supply);
}
/// @notice Computes the decrease in reserve given an amount of DVD.
/// @param _supplyDelta The amount of DVD in wei to be used in the calculation.
/// @param _supply The current supply state to be used in the calculation.
/// @param _totalReserve The current reserve state to be used in the calculation.
/// @return _reserveDelta Reserve amount in wei.
function _calculateDVDToReserve(
uint256 _supplyDelta,
uint256 _supply,
uint256 _totalReserve
) internal pure returns (uint256 _reserveDelta) {
require(_supplyDelta <= _supply, 'Token amount must be less than the supply');
uint256 _newSupply = _supply.sub(_supplyDelta);
uint256 _newReserve = _calculateReserveFromSupply(_newSupply);
_reserveDelta = _totalReserve.sub(_newReserve);
}
/// @notice Calculates reserve given a specific supply.
/// @param _supply The token supply in wei to be used in the calculation.
/// @return _reserve Reserve amount in wei.
function _calculateReserveFromSupply(uint256 _supply) internal pure returns (uint256 _reserve) {
// r = s^2 * m / 2
_reserve = _supply
.mul(_supply)
.div(DIVIDER) // inverse the operation (Divider instead of multiplier)
.div(2)
.roundedDiv(1e18);
// correction of the squared unit
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface IERC20Snapshot {
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.6.12;
interface ITreasury {
function release() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface IVault {
function savingsContract() external view returns (address);
function musd() external view returns (address);
function deposit(uint256) external;
function redeem(uint256) external;
function getBalance() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { MassetStructs } from "./MassetStructs.sol";
///
/// @title IMasset
/// @dev (Internal) Interface for interacting with Masset
/// VERSION: 1.0
/// DATE: 2020-05-05
interface IMasset is MassetStructs {
/// @dev Calc interest
function collectInterest() external returns (uint256 massetMinted, uint256 newTotalSupply);
/// @dev Minting
function mint(address _basset, uint256 _bassetQuantity)
external returns (uint256 massetMinted);
function mintTo(address _basset, uint256 _bassetQuantity, address _recipient)
external returns (uint256 massetMinted);
function mintMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantity, address _recipient)
external returns (uint256 massetMinted);
/// @dev Swapping
function swap( address _input, address _output, uint256 _quantity, address _recipient)
external returns (uint256 output);
function getSwapOutput( address _input, address _output, uint256 _quantity)
external view returns (bool, string memory, uint256 output);
/// @dev Redeeming
function redeem(address _basset, uint256 _bassetQuantity)
external returns (uint256 massetRedeemed);
function redeemTo(address _basset, uint256 _bassetQuantity, address _recipient)
external returns (uint256 massetRedeemed);
function redeemMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantities, address _recipient)
external returns (uint256 massetRedeemed);
function redeemMasset(uint256 _mAssetQuantity, address _recipient) external;
/// @dev Setters for the Manager or Gov to update module info
function upgradeForgeValidator(address _newForgeValidator) external;
/// @dev Setters for Gov to set system params
function setSwapFee(uint256 _swapFee) external;
/// @dev Getters
function getBasketManager() external view returns(address);
function forgeValidator() external view returns (address);
function totalSupply() external view returns (uint256);
function swapFee() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IDvd is IERC20 {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function increaseShareholderPoint(address account, uint256 amount) external;
function decreaseShareholderPoint(address account, uint256 amount) external;
function shareholderPointOf(address account) external view returns (uint256);
function totalShareholderPoint() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface ISDvd is IERC20 {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function setMinter(address account, bool value) external;
function setNoFeeAddress(address account, bool value) external;
function setPairAddress(address _pairAddress) external;
function snapshot() external returns (uint256);
function syncPairTokenTotalSupply() external returns (bool isPairTokenBurned);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface IPool {
function openFarm() external;
function distributeBonusRewards(uint256 amount) external;
function stake(uint256 amount) external;
function stakeTo(address recipient, uint256 amount) external;
function withdraw(uint256 amount) external;
function withdrawTo(address recipient, uint256 amount) external;
function claimReward() external;
function claimRewardTo(address recipient) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16 <0.7.0;
import '@openzeppelin/contracts/math/SafeMath.sol';
library MathUtils {
using SafeMath for uint256;
/// @notice Calculates the square root of a given value.
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
/// @notice Rounds a division result.
function roundedDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, 'div by 0');
uint256 halfB = (b.mod(2) == 0) ? (b.div(2)) : (b.div(2).add(1));
return (a.mod(b) >= halfB) ? (a.div(b).add(1)) : (a.div(b));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
//
// @title MassetStructs
// @author Stability Labs Pty. Ltd.
// @notice Structs used in the Masset contract and associated Libs
interface MassetStructs {
// Stores high level basket info
struct Basket {
// Array of Bassets currently active
Basset[] bassets;
// Max number of bAssets that can be present in any Basket
uint8 maxBassets;
// Some bAsset is undergoing re-collateralisation
bool undergoingRecol;
//
// In the event that we do not raise enough funds from the auctioning of a failed Basset,
// The Basket is deemed as failed, and is undercollateralised to a certain degree.
// The collateralisation ratio is used to calc Masset burn rate.
bool failed;
uint256 collateralisationRatio;
}
// Stores bAsset info. The struct takes 5 storage slots per Basset
struct Basset {
// Address of the bAsset
address addr;
// Status of the basset,
BassetStatus status; // takes uint8 datatype (1 byte) in storage
// An ERC20 can charge transfer fee, for example USDT, DGX tokens.
bool isTransferFeeCharged; // takes a byte in storage
//
// 1 Basset * ratio / ratioScale == x Masset (relative value)
// If ratio == 10e8 then 1 bAsset = 10 mAssets
// A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit)
uint256 ratio;
// Target weights of the Basset (100% == 1e18)
uint256 maxWeight;
// Amount of the Basset that is held in Collateral
uint256 vaultBalance;
}
// Status of the Basset - has it broken its peg?
enum BassetStatus {
Default,
Normal,
BrokenBelowPeg,
BrokenAbovePeg,
Blacklisted,
Liquidating,
Liquidated,
Failed
}
// Internal details on Basset
struct BassetDetails {
Basset bAsset;
address integrator;
uint8 index;
}
// All details needed to Forge with multiple bAssets
struct ForgePropsMulti {
bool isValid; // Flag to signify that forge bAssets have passed validity check
Basset[] bAssets;
address[] integrators;
uint8[] indexes;
}
// All details needed for proportionate Redemption
struct RedeemPropsMulti {
uint256 colRatio;
Basset[] bAssets;
address[] integrators;
uint8[] indexes;
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import './MathUtils.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
library LordLib {
using SafeMath for uint256;
using MathUtils for uint256;
/// @notice The slope of the bonding curve.
uint256 public constant DIVIDER = 1000000; // 1 / multiplier 0.000001 (so that we don't deal with decimals)
/**
* Supply (s), reserve (r) and token price (p) are in a relationship defined by the bonding curve:
* p = m * s
* The reserve equals to the area below the bonding curve
* r = s^2 / 2
* The formula for the supply becomes
* s = sqrt(2 * r / m)
*
* In solidity computations, we are using divider instead of multiplier (because its an integer).
* All values are decimals with 18 decimals (represented as uints), which needs to be compensated for in
* multiplications and divisions
*/
/// @notice Computes the increased supply given an amount of reserve.
/// @param _reserveDelta The amount of reserve in wei to be used in the calculation.
/// @param _totalReserve The current reserve state to be used in the calculation.
/// @param _supply The current supply state to be used in the calculation.
/// @return token amount in wei.
function calculateReserveToTokens(
uint256 _reserveDelta,
uint256 _totalReserve,
uint256 _supply
) internal pure returns (uint256) {
uint256 _reserve = _totalReserve;
uint256 _newReserve = _reserve.add(_reserveDelta);
// s = sqrt(2 * r / m)
uint256 _newSupply = MathUtils.sqrt(
_newReserve
.mul(2)
.mul(DIVIDER) // inverse the operation (Divider instead of multiplier)
.mul(1e18) // compensation for the squared unit
);
uint256 _supplyDelta = _newSupply.sub(_supply);
return _supplyDelta;
}
/// @notice Computes the decrease in reserve given an amount of tokens.
/// @param _supplyDelta The amount of tokens in wei to be used in the calculation.
/// @param _supply The current supply state to be used in the calculation.
/// @param _totalReserve The current reserve state to be used in the calculation.
/// @return Reserve amount in wei.
function calculateTokensToReserve(
uint256 _supplyDelta,
uint256 _supply,
uint256 _totalReserve
) internal pure returns (uint256) {
require(_supplyDelta <= _supply, 'Token amount must be less than the supply');
uint256 _newSupply = _supply.sub(_supplyDelta);
uint256 _newReserve = calculateReserveFromSupply(_newSupply);
uint256 _reserveDelta = _totalReserve.sub(_newReserve);
return _reserveDelta;
}
/// @notice Calculates reserve given a specific supply.
/// @param _supply The token supply in wei to be used in the calculation.
/// @return Reserve amount in wei.
function calculateReserveFromSupply(uint256 _supply) internal pure returns (uint256) {
// r = s^2 * m / 2
uint256 _reserve = _supply
.mul(_supply)
.div(DIVIDER) // inverse the operation (Divider instead of multiplier)
.div(2);
return _reserve.roundedDiv(1e18);
// correction of the squared unit
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import './interfaces/IVault.sol';
import './interfaces/IMStable.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
/// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract.
/// The only owner function is `init` which is to setup for the first time after deployment.
/// After init finished, owner will be renounced automatically. owner() function will return 0x0 address.
contract Vault is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event FundMigration(uint256 value);
/// @notice mStable governance proxy contract.
/// It should not change.
address public nexusGovernance;
/// @notice mStable savingsContract contract.
/// It can be changed through governance.
address public savingsContract;
/// @notice mUSD address.
address public musd;
/// @notice LoC address
address public controller;
constructor(address _musd, address _nexus) public {
// Set mUSD address
musd = _musd;
// Set nexus governance address
nexusGovernance = _nexus;
// Get mStable savings contract
savingsContract = _fetchMStableSavings();
// Approve savings contract to spend mUSD on this contract
_approveMax(musd, savingsContract);
}
/* ========== Modifiers ========== */
modifier onlyController {
require(msg.sender == controller, 'Controller only');
_;
}
/* ========== Owner Only ========== */
/// @notice Setup for the first time after deploy and renounce ownership immediately.
function init(address _controller) external onlyOwner {
// Set Lord of coin
controller = _controller;
// Renounce ownership immediately after init
renounceOwnership();
}
/* ========== Controller Only ========== */
/// @notice Deposits reserve into savingsAccount.
/// @dev It is part of Vault's interface.
/// @param amount Value to be deposited.
function deposit(uint256 amount) external onlyController {
require(amount > 0, 'Cannot deposit 0');
// Transfer mUSD from sender to this contract
IERC20(musd).safeTransferFrom(msg.sender, address(this), amount);
// Send to savings account
IMStable(savingsContract).depositSavings(amount);
}
/// @notice Redeems reserve from savingsAccount.
/// @dev It is part of Vault's interface.
/// @param amount Value to be redeemed.
function redeem(uint256 amount) external onlyController {
require(amount > 0, 'Cannot redeem 0');
// Redeem the amount in credits
uint256 credited = IMStable(savingsContract).redeem(_getRedeemInput(amount));
// Send credited amount to sender
IERC20(musd).safeTransfer(msg.sender, credited);
}
/* ========== View ========== */
/// @notice Returns balance in reserve from the savings contract.
/// @dev It is part of Vault's interface.
/// @return balance Reserve amount in the savings contract.
function getBalance() public view returns (uint256 balance) {
// Get balance in credits amount
balance = IMStable(savingsContract).creditBalances(address(this));
// Convert credits to reserve amount
if (balance > 0) {
balance = balance.mul(IMStable(savingsContract).exchangeRate()).div(1e18);
}
}
/* ========== Mutative ========== */
/// @notice Allows anyone to migrate all reserve to new savings contract.
/// @dev Only use if the savingsContract has been changed by governance.
function migrateSavings() external {
address currentSavingsContract = _fetchMStableSavings();
require(currentSavingsContract != savingsContract, 'Already on latest contract');
_swapSavingsContract();
}
/* ========== Internal ========== */
/// @notice Convert amount to mStable credits amount for redeem.
function _getRedeemInput(uint256 amount) internal view returns (uint256 credits) {
// Add 1 because the amounts always round down
// e.g. i have 51 credits, e4 10 = 20.4
// to withdraw 20 i need 20*10/4 = 50 + 1
credits = amount.mul(1e18).div(IMStable(savingsContract).exchangeRate()).add(1);
}
/// @notice Approve spender to max.
function _approveMax(address token, address spender) internal {
uint256 max = uint256(- 1);
IERC20(token).safeApprove(spender, max);
}
/// @notice Gets the current mStable Savings Contract address.
/// @return address of mStable Savings Contract.
function _fetchMStableSavings() internal view returns (address) {
address manager = IMStable(nexusGovernance).getModule(keccak256('SavingsManager'));
return IMStable(manager).savingsContracts(musd);
}
/// @notice Worker function that swaps the reserve to a new savings contract.
function _swapSavingsContract() internal {
// Get all savings balance
uint256 balance = getBalance();
// Redeem the amount in credits
uint256 credited = IMStable(savingsContract).redeem(_getRedeemInput(balance));
// Get new savings contract
savingsContract = _fetchMStableSavings();
// Approve new savings contract as mUSD spender
_approveMax(musd, savingsContract);
// Send to new savings account
IMStable(savingsContract).depositSavings(credited);
// Emit event
emit FundMigration(balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface IMStable {
// Nexus
function getModule(bytes32) external view returns (address);
// Savings Manager
function savingsContracts(address) external view returns (address);
// Savings Contract
function exchangeRate() external view returns (uint256);
function creditBalances(address) external view returns (uint256);
function depositSavings(uint256) external;
function redeem(uint256) external returns (uint256);
function depositInterest(uint256) external;
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import "./uniswapv2/interfaces/IUniswapV2Pair.sol";
import "./interfaces/ILordOfCoin.sol";
import "./interfaces/ITreasury.sol";
/// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract.
/// The only owner function is `init` which is to setup for the first time after deployment.
/// After init finished, owner will be renounced automatically. owner() function will return 0x0 address.
contract SDvd is ERC20Snapshot, Ownable {
using SafeMath for uint256;
/// @notice Minter address. DVD-ETH Pool, DVD Pool.
mapping(address => bool) public minters;
/// @dev No fee address. SDVD-ETH Pool, DVD Pool.
mapping(address => bool) public noFeeAddresses;
/// @notice Lord of Coin
address public controller;
address public devTreasury;
address public poolTreasury;
address public tradingTreasury;
/// @dev SDVD-ETH pair address
address public pairAddress;
/// @dev SDVD-ETH pair token
IUniswapV2Pair pairToken;
/// @dev Used to check LP removal
uint256 lastPairTokenTotalSupply;
constructor() public ERC20('Stock dvd.finance', 'SDVD') {
}
/* ========== Modifiers ========== */
modifier onlyMinter {
require(minters[msg.sender], 'Minter only');
_;
}
modifier onlyController {
require(msg.sender == controller, 'Controller only');
_;
}
/* ========== Owner Only ========== */
/// @notice Setup for the first time after deploy and renounce ownership immediately
function init(
address _controller,
address _pairAddress,
address _sdvdEthPool,
address _dvdPool,
address _devTreasury,
address _poolTreasury,
address _tradingTreasury
) external onlyOwner {
controller = _controller;
// Create uniswap pair for SDVD-ETH pool
pairAddress = _pairAddress;
// Set pair token
pairToken = IUniswapV2Pair(pairAddress);
devTreasury = _devTreasury;
poolTreasury = _poolTreasury;
tradingTreasury = _tradingTreasury;
// Add pools as SDVD minter
_setMinter(_sdvdEthPool, true);
_setMinter(_dvdPool, true);
// Add no fees address
_setNoFeeAddress(_sdvdEthPool, true);
_setNoFeeAddress(_dvdPool, true);
_setNoFeeAddress(devTreasury, true);
_setNoFeeAddress(poolTreasury, true);
_setNoFeeAddress(tradingTreasury, true);
// Renounce ownership immediately after init
renounceOwnership();
}
/* ========== Minter Only ========== */
function mint(address account, uint256 amount) external onlyMinter {
_mint(account, amount);
}
function burn(address account, uint256 amount) external onlyMinter {
_burn(account, amount);
}
/* ========== Controller Only ========== */
function snapshot() external onlyController returns (uint256) {
return _snapshot();
}
/* ========== Public ========== */
function syncPairTokenTotalSupply() public returns (bool isPairTokenBurned) {
// Get LP token total supply
uint256 pairTokenTotalSupply = pairToken.totalSupply();
// If last total supply > current total supply,
// It means LP token is burned by uniswap, which means someone removing liquidity
isPairTokenBurned = lastPairTokenTotalSupply > pairTokenTotalSupply;
// Save total supply
lastPairTokenTotalSupply = pairTokenTotalSupply;
}
/* ========== Internal ========== */
function _setMinter(address account, bool value) internal {
minters[account] = value;
}
function _setNoFeeAddress(address account, bool value) internal {
noFeeAddresses[account] = value;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual override {
// Check uniswap liquidity removal
_checkUniswapLiquidityRemoval(sender);
if (noFeeAddresses[sender] || noFeeAddresses[recipient]) {
super._transfer(sender, recipient, amount);
} else {
// 0.5% for dev
uint256 devFee = amount.div(200);
// 1% for farmers in pool
uint256 poolFee = devFee.mul(2);
// 1% to goes as sharing profit
uint256 tradingFee = poolFee;
// Get net amount
uint256 net = amount
.sub(devFee)
.sub(poolFee)
.sub(tradingFee);
super._transfer(sender, recipient, net);
super._transfer(sender, devTreasury, devFee);
super._transfer(sender, poolTreasury, poolFee);
super._transfer(sender, tradingTreasury, tradingFee);
}
}
function _checkUniswapLiquidityRemoval(address sender) internal {
bool isPairTokenBurned = syncPairTokenTotalSupply();
// If from uniswap LP address
if (sender == pairAddress) {
// Check if liquidity removed
require(isPairTokenBurned == false, 'LP removal disabled');
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// Update balance and/or total supply snapshots before the values are modified. This is implemented
// in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
// mint
_updateAccountSnapshot(to);
_updateTotalSupplySnapshot();
} else if (to == address(0)) {
// burn
_updateAccountSnapshot(from);
_updateTotalSupplySnapshot();
} else {
// transfer
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
}
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity >=0.5.0;
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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/ILordOfCoin.sol";
import "./interfaces/IDvd.sol";
import "./interfaces/ISDvd.sol";
import "./interfaces/ITreasury.sol";
/// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract.
/// The only owner function is `init` which is to setup for the first time after deployment.
/// After init finished, owner will be renounced automatically. owner() function will return 0x0 address.
abstract contract Pool is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event Staked(address indexed sender, address indexed recipient, uint256 amount);
event Withdrawn(address indexed sender, address indexed recipient, uint256 amount);
event Claimed(address indexed sender, address indexed recipient, uint256 net, uint256 tax, uint256 total);
event Halving(uint256 amount);
/// @dev Token will be DVD or SDVD-ETH UNI-V2
address public stakedToken;
ISDvd public sdvd;
/// @notice Flag to determine if farm is open
bool public isFarmOpen = false;
/// @notice Farming will be open on this timestamp
uint256 public farmOpenTime;
uint256 public rewardAllocation;
uint256 public rewardRate;
uint256 public rewardDuration = 1460 days; // halving per 4 years
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public finishTime;
uint256 public bonusRewardAllocation;
uint256 public bonusRewardRate;
uint256 public bonusRewardDuration = 1 days; // Reward bonus distributed every day, must be the same value with pool treasury release threshold
uint256 public bonusLastUpdateTime;
uint256 public bonusRewardPerTokenStored;
uint256 public bonusRewardFinishTime;
struct AccountInfo {
// Staked token balance
uint256 balance;
// Normal farming reward
uint256 reward;
uint256 rewardPerTokenPaid;
// Bonus reward from transaction fee
uint256 bonusReward;
uint256 bonusRewardPerTokenPaid;
}
/// @dev Account info
mapping(address => AccountInfo) public accountInfos;
/// @dev Total supply of staked tokens
uint256 private _totalSupply;
/// @notice Total rewards minted from this pool
uint256 public totalRewardMinted;
// @dev Lord of Coin
address controller;
// @dev Pool treasury
address poolTreasury;
constructor(address _poolTreasury, uint256 _farmOpenTime) public {
poolTreasury = _poolTreasury;
farmOpenTime = _farmOpenTime;
}
/* ========== Modifiers ========== */
modifier onlyController {
require(msg.sender == controller, 'Controller only');
_;
}
modifier onlyPoolTreasury {
require(msg.sender == poolTreasury, 'Treasury only');
_;
}
modifier farmOpen {
require(isFarmOpen, 'Farm not open');
_;
}
/* ========== Owner Only ========== */
/// @notice Setup for the first time after deploy and renounce ownership immediately
function init(address _controller, address _stakedToken) external onlyOwner {
controller = _controller;
stakedToken = _stakedToken;
sdvd = ISDvd(ILordOfCoin(_controller).sdvd());
// Renounce ownership immediately after init
renounceOwnership();
}
/* ========== Pool Treasury Only ========== */
/// @notice Distribute bonus rewards to farmers
/// @dev Can only be called by pool treasury
function distributeBonusRewards(uint256 amount) external onlyPoolTreasury {
// Set bonus reward allocation
bonusRewardAllocation = amount;
// Calculate bonus reward rate
bonusRewardRate = bonusRewardAllocation.div(bonusRewardDuration);
// Set finish time
bonusRewardFinishTime = block.timestamp.add(bonusRewardDuration);
// Set last update time
bonusLastUpdateTime = block.timestamp;
}
/* ========== Mutative ========== */
/// @notice Stake token.
/// @dev Need to approve staked token first.
/// @param amount Token amount.
function stake(uint256 amount) external nonReentrant {
_stake(msg.sender, msg.sender, amount);
}
/// @notice Stake token.
/// @dev Need to approve staked token first.
/// @param recipient Address who receive staked token balance.
/// @param amount Token amount.
function stakeTo(address recipient, uint256 amount) external nonReentrant {
_stake(msg.sender, recipient, amount);
}
/// @notice Withdraw token.
/// @param amount Token amount.
function withdraw(uint256 amount) external nonReentrant farmOpen {
_withdraw(msg.sender, msg.sender, amount);
}
/// @notice Withdraw token.
/// @param recipient Address who receive staked token.
/// @param amount Token amount.
function withdrawTo(address recipient, uint256 amount) external nonReentrant farmOpen {
_withdraw(msg.sender, recipient, amount);
}
/// @notice Claim SDVD reward
/// @return Reward net amount
/// @return Reward tax amount
/// @return Total Reward amount
function claimReward() external nonReentrant farmOpen returns(uint256, uint256, uint256) {
return _claimReward(msg.sender, msg.sender);
}
/// @notice Claim SDVD reward
/// @param recipient Address who receive reward.
/// @return Reward net amount
/// @return Reward tax amount
/// @return Total Reward amount
function claimRewardTo(address recipient) external nonReentrant farmOpen returns(uint256, uint256, uint256) {
return _claimReward(msg.sender, recipient);
}
/* ========== Internal ========== */
function _updateReward(address account) internal {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
accountInfos[account].reward = earned(account);
accountInfos[account].rewardPerTokenPaid = rewardPerTokenStored;
}
}
function _updateBonusReward(address account) internal {
bonusRewardPerTokenStored = bonusRewardPerToken();
bonusLastUpdateTime = lastTimeBonusRewardApplicable();
if (account != address(0)) {
accountInfos[account].bonusReward = bonusEarned(account);
accountInfos[account].bonusRewardPerTokenPaid = bonusRewardPerTokenStored;
}
}
/// @notice Stake staked token
/// @param sender address. Address who have the token.
/// @param recipient address. Address who receive staked token balance.
function _stake(address sender, address recipient, uint256 amount) internal virtual {
_checkOpenFarm();
_checkHalving();
_updateReward(recipient);
_updateBonusReward(recipient);
_notifyController();
require(amount > 0, 'Cannot stake 0');
IERC20(stakedToken).safeTransferFrom(sender, address(this), amount);
_totalSupply = _totalSupply.add(amount);
accountInfos[recipient].balance = accountInfos[recipient].balance.add(amount);
emit Staked(sender, recipient, amount);
}
/// @notice Withdraw staked token
/// @param sender address. Address who have stake the token.
/// @param recipient address. Address who receive the staked token.
function _withdraw(address sender, address recipient, uint256 amount) internal virtual {
_checkHalving();
_updateReward(sender);
_updateBonusReward(sender);
_notifyController();
require(amount > 0, 'Cannot withdraw 0');
require(accountInfos[sender].balance >= amount, 'Insufficient balance');
_totalSupply = _totalSupply.sub(amount);
accountInfos[sender].balance = accountInfos[sender].balance.sub(amount);
IERC20(stakedToken).safeTransfer(recipient, amount);
emit Withdrawn(sender, recipient, amount);
}
/// @notice Claim reward
/// @param sender address. Address who have stake the token.
/// @param recipient address. Address who receive the reward.
/// @return totalNetReward Total net SDVD reward.
/// @return totalTaxReward Total taxed SDVD reward.
/// @return totalReward Total SDVD reward.
function _claimReward(address sender, address recipient) internal virtual returns(uint256 totalNetReward, uint256 totalTaxReward, uint256 totalReward) {
_checkHalving();
_updateReward(sender);
_updateBonusReward(sender);
_notifyController();
uint256 reward = accountInfos[sender].reward;
uint256 bonusReward = accountInfos[sender].bonusReward;
totalReward = reward.add(bonusReward);
require(totalReward > 0, 'No reward to claim');
if (reward > 0) {
// Reduce reward first
accountInfos[sender].reward = 0;
// Apply tax
uint256 tax = reward.div(claimRewardTaxDenominator());
uint256 net = reward.sub(tax);
// Mint SDVD as reward to recipient
sdvd.mint(recipient, net);
// Mint SDVD tax to pool treasury
sdvd.mint(address(poolTreasury), tax);
// Increase total
totalNetReward = totalNetReward.add(net);
totalTaxReward = totalTaxReward.add(tax);
// Set stats
totalRewardMinted = totalRewardMinted.add(reward);
}
if (bonusReward > 0) {
// Reduce bonus reward first
accountInfos[sender].bonusReward = 0;
// Get balance and check so we doesn't overrun
uint256 balance = sdvd.balanceOf(address(this));
if (bonusReward > balance) {
bonusReward = balance;
}
// Apply tax
uint256 tax = bonusReward.div(claimRewardTaxDenominator());
uint256 net = bonusReward.sub(tax);
// Send bonus reward to recipient
IERC20(sdvd).safeTransfer(recipient, net);
// Send tax to treasury
IERC20(sdvd).safeTransfer(address(poolTreasury), tax);
// Increase total
totalNetReward = totalNetReward.add(net);
totalTaxReward = totalTaxReward.add(tax);
}
if (totalReward > 0) {
emit Claimed(sender, recipient, totalNetReward, totalTaxReward, totalReward);
}
}
/// @notice Check if farm can be open
function _checkOpenFarm() internal {
require(farmOpenTime <= block.timestamp, 'Farm not open');
if (!isFarmOpen) {
// Set flag
isFarmOpen = true;
// Initialize
lastUpdateTime = block.timestamp;
finishTime = block.timestamp.add(rewardDuration);
rewardRate = rewardAllocation.div(rewardDuration);
// Initialize bonus
bonusLastUpdateTime = block.timestamp;
bonusRewardFinishTime = block.timestamp.add(bonusRewardDuration);
bonusRewardRate = bonusRewardAllocation.div(bonusRewardDuration);
}
}
/// @notice Check and do halving when finish time reached
function _checkHalving() internal {
if (block.timestamp >= finishTime) {
// Halving reward
rewardAllocation = rewardAllocation.div(2);
// Calculate reward rate
rewardRate = rewardAllocation.div(rewardDuration);
// Set finish time
finishTime = block.timestamp.add(rewardDuration);
// Set last update time
lastUpdateTime = block.timestamp;
// Emit event
emit Halving(rewardAllocation);
}
}
/// @notice Check if need to increase snapshot in lord of coin
function _notifyController() internal {
ILordOfCoin(controller).checkSnapshot();
ILordOfCoin(controller).releaseTreasury();
}
/* ========== View ========== */
/// @notice Get staked token total supply
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/// @notice Get staked token balance
function balanceOf(address account) external view returns (uint256) {
return accountInfos[account].balance;
}
/// @notice Get full earned amount and bonus
/// @dev Combine earned
function fullEarned(address account) external view returns (uint256) {
return earned(account).add(bonusEarned(account));
}
/// @notice Get full reward rate
/// @dev Combine reward rate
function fullRewardRate() external view returns (uint256) {
return rewardRate.add(bonusRewardRate);
}
/// @notice Get claim reward tax
function claimRewardTaxDenominator() public view returns (uint256) {
if (block.timestamp < farmOpenTime.add(365 days)) {
// 50% tax
return 2;
} else if (block.timestamp < farmOpenTime.add(730 days)) {
// 33% tax
return 3;
} else if (block.timestamp < farmOpenTime.add(1095 days)) {
// 25% tax
return 4;
} else if (block.timestamp < farmOpenTime.add(1460 days)) {
// 20% tax
return 5;
} else {
// 10% tax
return 10;
}
}
/// Normal rewards
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, finishTime);
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return rewardPerTokenStored.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return accountInfos[account].balance.mul(
rewardPerToken().sub(accountInfos[account].rewardPerTokenPaid)
)
.div(1e18)
.add(accountInfos[account].reward);
}
/// Bonus
function lastTimeBonusRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, bonusRewardFinishTime);
}
function bonusRewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return bonusRewardPerTokenStored;
}
return bonusRewardPerTokenStored.add(
lastTimeBonusRewardApplicable().sub(bonusLastUpdateTime).mul(bonusRewardRate).mul(1e18).div(_totalSupply)
);
}
function bonusEarned(address account) public view returns (uint256) {
return accountInfos[account].balance.mul(
bonusRewardPerToken().sub(accountInfos[account].bonusRewardPerTokenPaid)
)
.div(1e18)
.add(accountInfos[account].bonusReward);
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import "./uniswapv2/interfaces/IUniswapV2Router02.sol";
import "./uniswapv2/interfaces/IUniswapV2Pair.sol";
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
import "./interfaces/IDvd.sol";
import "./Pool.sol";
contract SDvdEthPool is Pool {
event StakedETH(address indexed account, uint256 amount);
event ClaimedAndStaked(address indexed account, uint256 amount);
/// @dev Uniswap router
IUniswapV2Router02 uniswapRouter;
/// @dev Uniswap factory
IUniswapV2Factory uniswapFactory;
/// @dev WETH address
address weth;
/// @notice LGE state
bool public isLGEActive = true;
/// @notice Max initial deposit cap
uint256 public LGE_INITIAL_DEPOSIT_CAP = 5 ether;
/// @notice Amount in SDVD. After hard cap reached, stake ETH will function as normal staking.
uint256 public LGE_HARD_CAP = 200 ether;
/// @dev Initial price multiplier
uint256 public LGE_INITIAL_PRICE_MULTIPLIER = 2;
constructor(address _poolTreasury, address _uniswapRouter, uint256 _farmOpenTime) public Pool(_poolTreasury, _farmOpenTime) {
rewardAllocation = 240000 * 1e18;
rewardAllocation = rewardAllocation.sub(LGE_HARD_CAP.div(2));
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
uniswapFactory = IUniswapV2Factory(uniswapRouter.factory());
weth = uniswapRouter.WETH();
}
/// @dev Added to receive ETH when swapping on Uniswap
receive() external payable {
}
/// @notice Stake token using ETH conveniently.
function stakeETH() external payable nonReentrant {
_stakeETH(msg.value);
}
/// @notice Stake token using SDVD and ETH conveniently.
/// @dev User must approve SDVD first
function stakeSDVD(uint256 amountToken) external payable nonReentrant farmOpen {
require(isLGEActive == false, 'LGE still active');
uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken);
uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken);
uint256 amountETH = amountToken.mul(pairETHBalance).div(pairSDVDBalance);
// Make sure received eth is enough
require(msg.value >= amountETH, 'Not enough ETH');
// Check if there is excess eth
uint256 excessETH = msg.value.sub(amountETH);
// Send back excess eth
if (excessETH > 0) {
msg.sender.transfer(excessETH);
}
// Transfer sdvd from sender to this contract
IERC20(sdvd).safeTransferFrom(msg.sender, address(this), amountToken);
// Approve uniswap router to spend SDVD
IERC20(sdvd).approve(address(uniswapRouter), amountToken);
// Add liquidity
(,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountToken, 0, 0, address(this), block.timestamp.add(30 minutes));
// Approve self
IERC20(stakedToken).approve(address(this), liquidity);
// Stake LP token for sender
_stake(address(this), msg.sender, liquidity);
}
/// @notice Claim reward and re-stake conveniently.
function claimRewardAndStake() external nonReentrant farmOpen {
require(isLGEActive == false, 'LGE still active');
// Claim SDVD reward to this address
(uint256 totalNetReward,,) = _claimReward(msg.sender, address(this));
// Split total reward to be swapped
uint256 swapAmountSDVD = totalNetReward.div(2);
// Swap path
address[] memory path = new address[](2);
path[0] = address(sdvd);
path[1] = weth;
// Approve uniswap router to spend sdvd
IERC20(sdvd).approve(address(uniswapRouter), swapAmountSDVD);
// Swap SDVD to ETH
// Param: uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline
uint256[] memory amounts = uniswapRouter.swapExactTokensForETH(swapAmountSDVD, 0, path, address(this), block.timestamp.add(30 minutes));
// Get received ETH amount from swap
uint256 amountETHReceived = amounts[1];
// Get pair address and balance
uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken);
uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken);
// Get available SDVD
uint256 amountSDVD = totalNetReward.sub(swapAmountSDVD);
// Calculate how much ETH needed to provide liquidity
uint256 amountETH = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance);
// If required ETH amount to add liquidity is bigger than what we have
// Then we need to reduce SDVD amount
if (amountETH > amountETHReceived) {
// Set ETH amount
amountETH = amountETHReceived;
// Get amount SDVD needed to add liquidity
uint256 amountSDVDRequired = amountETH.mul(pairSDVDBalance).div(pairETHBalance);
// Send dust
if (amountSDVD > amountSDVDRequired) {
IERC20(sdvd).safeTransfer(msg.sender, amountSDVD.sub(amountSDVDRequired));
}
// Set SDVD amount
amountSDVD = amountSDVDRequired;
}
// Else if we have too much ETH
else if (amountETHReceived > amountETH) {
// Send excess
msg.sender.transfer(amountETHReceived.sub(amountETH));
}
// Approve uniswap router to spend SDVD
IERC20(sdvd).approve(address(uniswapRouter), amountSDVD);
// Add liquidity
(,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes));
// Approve self
IERC20(stakedToken).approve(address(this), liquidity);
// Stake LP token for sender
_stake(address(this), msg.sender, liquidity);
emit ClaimedAndStaked(msg.sender, liquidity);
}
/* ========== Internal ========== */
/// @notice Stake ETH
/// @param value Value in ETH
function _stakeETH(uint256 value) internal {
// If in LGE
if (isLGEActive) {
// SDVD-ETH pair address
uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken);
if (pairSDVDBalance == 0) {
require(msg.value <= LGE_INITIAL_DEPOSIT_CAP, 'Initial deposit cap reached');
}
uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken);
uint256 amountETH = msg.value;
// If SDVD balance = 0 then set initial price
uint256 amountSDVD = pairSDVDBalance == 0 ? amountETH.mul(LGE_INITIAL_PRICE_MULTIPLIER) : amountETH.mul(pairSDVDBalance).div(pairETHBalance);
uint256 excessETH = 0;
// If amount token to be minted pass the hard cap
if (pairSDVDBalance.add(amountSDVD) > LGE_HARD_CAP) {
// Get excess token
uint256 excessToken = pairSDVDBalance.add(amountSDVD).sub(LGE_HARD_CAP);
// Reduce it
amountSDVD = amountSDVD.sub(excessToken);
// Get excess ether
excessETH = excessToken.mul(pairETHBalance).div(pairSDVDBalance);
// Reduce amount ETH to be put on uniswap liquidity
amountETH = amountETH.sub(excessETH);
}
// Mint LGE SDVD
ISDvd(sdvd).mint(address(this), amountSDVD);
// Add liquidity in uniswap and send the LP token to this contract
IERC20(sdvd).approve(address(uniswapRouter), amountSDVD);
(,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes));
// Recheck the SDVD in pair address
pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken);
// Set LGE active state
isLGEActive = pairSDVDBalance < LGE_HARD_CAP;
// Approve self
IERC20(stakedToken).approve(address(this), liquidity);
// Stake LP token for sender
_stake(address(this), msg.sender, liquidity);
// If there is excess ETH
if (excessETH > 0) {
_stakeETH(excessETH);
}
} else {
// Split ETH sent
uint256 amountETH = value.div(2);
// Swap path
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(sdvd);
// Swap ETH to SDVD using uniswap
// Param: uint amountOutMin, address[] calldata path, address to, uint deadline
uint256[] memory amounts = uniswapRouter.swapExactETHForTokens{value : amountETH}(
0,
path,
address(this),
block.timestamp.add(30 minutes)
);
// Get SDVD amount
uint256 amountSDVDReceived = amounts[1];
// Get pair address balance
uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken);
uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken);
// Get available ETH
amountETH = value.sub(amountETH);
// Calculate amount of SDVD needed to add liquidity
uint256 amountSDVD = amountETH.mul(pairSDVDBalance).div(pairETHBalance);
// If required SDVD amount to add liquidity is bigger than what we have
// Then we need to reduce ETH amount
if (amountSDVD > amountSDVDReceived) {
// Set SDVD amount
amountSDVD = amountSDVDReceived;
// Get amount ETH needed to add liquidity
uint256 amountETHRequired = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance);
// Send dust back to sender
if (amountETH > amountETHRequired) {
msg.sender.transfer(amountETH.sub(amountETHRequired));
}
// Set ETH amount
amountETH = amountETHRequired;
}
// Else if we have too much SDVD
else if (amountSDVDReceived > amountSDVD) {
// Send dust
IERC20(sdvd).transfer(msg.sender, amountSDVDReceived.sub(amountSDVD));
}
// Approve uniswap router to spend SDVD
IERC20(sdvd).approve(address(uniswapRouter), amountSDVD);
// Add liquidity
(,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes));
// Sync total token supply
ISDvd(sdvd).syncPairTokenTotalSupply();
// Approve self
IERC20(stakedToken).approve(address(this), liquidity);
// Stake LP token for sender
_stake(address(this), msg.sender, liquidity);
}
emit StakedETH(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IERC20Mock is IERC20 {
function mint(address account, uint256 amount) external;
function mockMint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function mockBurn(address account, uint256 amount) external;
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import "./interfaces/IPool.sol";
/// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract.
/// The only owner function is `init` which is to setup for the first time after deployment.
/// After init finished, owner will be renounced automatically. owner() function will return 0x0 address.
contract PoolTreasury is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @dev SDVD ETH pool address
address public sdvdEthPool;
/// @dev DVD pool address
address public dvdPool;
/// @dev SDVD contract address
address public sdvd;
/// @dev Distribute reward every 1 day to pool
uint256 public releaseThreshold = 1 days;
/// @dev Last release timestamp
uint256 public releaseTime;
/// @notice Swap reward distribution numerator when this time reached
uint256 public numeratorSwapTime;
/// @notice How long we should wait before swap numerator
uint256 public NUMERATOR_SWAP_WAIT = 4383 days; // 12 normal years + 3 leap days;
constructor(address _sdvd) public {
sdvd = _sdvd;
releaseTime = block.timestamp;
numeratorSwapTime = block.timestamp.add(NUMERATOR_SWAP_WAIT);
}
/* ========== Owner Only ========== */
/// @notice Setup for the first time after deploy and renounce ownership immediately
function init(address _sdvdEthPool, address _dvdPool) external onlyOwner {
sdvdEthPool = _sdvdEthPool;
dvdPool = _dvdPool;
// Renounce ownership after init
renounceOwnership();
}
/* ========== Mutative ========== */
/// @notice Release pool treasury to pool and give rewards for farmers.
function release() external {
_release();
}
/* ========== Internal ========== */
/// @notice Release pool treasury to pool
function _release() internal {
if (releaseTime.add(releaseThreshold) <= block.timestamp) {
// Update release time
releaseTime = block.timestamp;
// Check balance
uint256 balance = IERC20(sdvd).balanceOf(address(this));
// If there is balance
if (balance > 0) {
// Get numerator
uint256 numerator = block.timestamp <= numeratorSwapTime ? 4 : 6;
// Distribute reward to pools
uint dvdPoolReward = balance.div(10).mul(numerator);
IERC20(sdvd).transfer(dvdPool, dvdPoolReward);
IPool(dvdPool).distributeBonusRewards(dvdPoolReward);
uint256 sdvdEthPoolReward = balance.sub(dvdPoolReward);
IERC20(sdvd).transfer(sdvdEthPool, sdvdEthPoolReward);
IPool(sdvdEthPool).distributeBonusRewards(sdvdEthPoolReward);
}
}
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import "./uniswapv2/interfaces/IUniswapV2Router02.sol";
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
import "./interfaces/IDvd.sol";
import "./interfaces/IPool.sol";
import "./Pool.sol";
contract DvdPool is Pool {
event StakedETH(address indexed account, uint256 amount);
event WithdrawnETH(address indexed account, uint256 amount);
event ClaimedAndStaked(address indexed account, uint256 amount);
/// @dev mUSD instance
address public musd;
/// @dev Uniswap router
IUniswapV2Router02 uniswapRouter;
/// @dev Uniswap factory
IUniswapV2Factory uniswapFactory;
/// @dev WETH address
address weth;
/// @dev SDVD ETH pool address
address public sdvdEthPool;
constructor(address _poolTreasury, address _musd, address _uniswapRouter, address _sdvdEthPool, uint256 _farmOpenTime) public Pool(_poolTreasury, _farmOpenTime) {
rewardAllocation = 360000 * 1e18;
musd = _musd;
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
uniswapFactory = IUniswapV2Factory(uniswapRouter.factory());
weth = uniswapRouter.WETH();
sdvdEthPool = _sdvdEthPool;
}
/// @dev Added to receive ETH when swapping on Uniswap
receive() external payable {
}
/// @notice Stake token using ETH conveniently.
function stakeETH() external payable nonReentrant {
// Buy DVD using ETH
(uint256 dvdAmount,,,) = ILordOfCoin(controller).buyFromETH{value : msg.value}();
// Approve self
IERC20(stakedToken).approve(address(this), dvdAmount);
// Stake user DVD
_stake(address(this), msg.sender, dvdAmount);
emit StakedETH(msg.sender, msg.value);
}
/// @notice Withdraw token to ETH conveniently.
/// @param amount Number of staked DVD token.
/// @dev Need to approve DVD token first.
function withdrawETH(uint256 amount) external nonReentrant farmOpen {
// Call withdraw to this address
_withdraw(msg.sender, address(this), amount);
// Approve LoC to spend DVD
IERC20(stakedToken).approve(controller, amount);
// Sell received DVD to ETH
(uint256 receivedETH,,,,) = ILordOfCoin(controller).sellToETH(amount);
// Send received ETH to sender
msg.sender.transfer(receivedETH);
emit WithdrawnETH(msg.sender, receivedETH);
}
/// @notice Claim reward and re-stake conveniently.
function claimRewardAndStake() external nonReentrant farmOpen {
// Claim SDVD reward to this address
(uint256 totalNetReward,,) = _claimReward(msg.sender, address(this));
// Split total reward to be swapped
uint256 swapAmountSDVD = totalNetReward.div(2);
// Swap path
address[] memory path = new address[](2);
path[0] = address(sdvd);
path[1] = weth;
// Approve uniswap router to spend sdvd
IERC20(sdvd).approve(address(uniswapRouter), swapAmountSDVD);
// Swap SDVD to ETH
// Param: uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline
uint256[] memory amounts = uniswapRouter.swapExactTokensForETH(swapAmountSDVD, 0, path, address(this), block.timestamp.add(30 minutes));
// Get received ETH amount from swap
uint256 amountETHReceived = amounts[1];
// Get pair address and balance
address pairAddress = uniswapFactory.getPair(address(sdvd), weth);
uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(pairAddress);
uint256 pairETHBalance = IERC20(weth).balanceOf(pairAddress);
// Get available SDVD
uint256 amountSDVD = totalNetReward.sub(swapAmountSDVD);
// Calculate how much ETH needed to provide liquidity
uint256 amountETH = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance);
// If required ETH amount to add liquidity is bigger than what we have
// Then we need to reduce SDVD amount
if (amountETH > amountETHReceived) {
// Set ETH amount
amountETH = amountETHReceived;
// Get amount SDVD needed to add liquidity
uint256 amountSDVDRequired = amountETH.mul(pairSDVDBalance).div(pairETHBalance);
// Send dust
if (amountSDVD > amountSDVDRequired) {
IERC20(sdvd).safeTransfer(msg.sender, amountSDVD.sub(amountSDVDRequired));
}
// Set SDVD amount
amountSDVD = amountSDVDRequired;
}
// Else if we have too much ETH
else if (amountETHReceived > amountETH) {
// Send dust
msg.sender.transfer(amountETHReceived.sub(amountETH));
}
// Approve uniswap router to spend SDVD
IERC20(sdvd).approve(address(uniswapRouter), amountSDVD);
// Add liquidity
(,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes));
// Approve SDVD ETH pool to spend LP token
IERC20(pairAddress).approve(sdvdEthPool, liquidity);
// Stake LP token for sender
IPool(sdvdEthPool).stakeTo(msg.sender, liquidity);
emit ClaimedAndStaked(msg.sender, liquidity);
}
/* ========== Internal ========== */
/// @notice Override stake function to check shareholder points
/// @param amount Number of DVD token to be staked.
function _stake(address sender, address recipient, uint256 amount) internal virtual override {
require(IDvd(stakedToken).shareholderPointOf(sender) >= amount, 'Insufficient shareholder points');
super._stake(sender, recipient, amount);
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/math/Math.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import './DvdShareholderPoint.sol';
/// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract.
/// The only owner function is `init` which is to setup for the first time after deployment.
/// After init finished, owner will be renounced automatically. owner() function will return 0x0 address.
contract Dvd is ERC20, DvdShareholderPoint, Ownable {
/// @notice Minter for DVD token. This value will be Lord of Coin address.
address public minter;
/// @notice Controller. This value will be Lord of Coin address.
address public controller;
/// @dev DVD pool address.
address public dvdPool;
constructor() public ERC20('Dvd.finance', 'DVD') {
}
/* ========== Modifiers ========== */
modifier onlyMinter {
require(msg.sender == minter, 'Minter only');
_;
}
modifier onlyController {
require(msg.sender == controller, 'Controller only');
_;
}
/* ========== Owner Only ========== */
/// @notice Setup for the first time after deploy and renounce ownership immediately
function init(address _controller, address _dvdPool) external onlyOwner {
controller = _controller;
minter = _controller;
dvdPool = _dvdPool;
// Renounce ownership immediately after init
renounceOwnership();
}
/* ========== Minter Only ========== */
function mint(address account, uint256 amount) external onlyMinter {
_mint(account, amount);
}
function burn(address account, uint256 amount) external onlyMinter {
_burn(account, amount);
}
/* ========== Controller Only ========== */
/// @notice Increase shareholder point.
/// @dev Can only be called by the LoC contract.
/// @param account Account address
/// @param amount The amount to increase.
function increaseShareholderPoint(address account, uint256 amount) external onlyController {
_increaseShareholderPoint(account, amount);
}
/// @notice Decrease shareholder point.
/// @dev Can only be called by the LoC contract.
/// @param account Account address
/// @param amount The amount to decrease.
function decreaseShareholderPoint(address account, uint256 amount) external onlyController {
_decreaseShareholderPoint(account, amount);
}
/* ========== Internal ========== */
/// @notice ERC20 Before token transfer hook
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
// If transfer between two accounts
if (from != address(0) && to != address(0)) {
// Remove shareholder point from account
_decreaseShareholderPoint(from, Math.min(amount, shareholderPointOf(from)));
}
// If transfer is from DVD pool (This occurs when user withdraw their stake, or using convenient stake ETH)
// Give back their shareholder point.
if (from == dvdPool) {
_increaseShareholderPoint(to, amount);
}
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
abstract contract DvdShareholderPoint {
using SafeMath for uint256;
event ShareholderPointIncreased(address indexed account, uint256 amount, uint256 totalShareholderPoint);
event ShareholderPointDecreased(address indexed account, uint256 amount, uint256 totalShareholderPoint);
/// @dev Our shareholder point tracker
/// Shareholder point will determine how much token one account can use to farm SDVD
/// This point can only be increased/decreased by LoC buy/sell function to prevent people trading DVD on exchange and don't pay their taxes
mapping(address => uint256) private _shareholderPoints;
uint256 private _totalShareholderPoint;
/// @notice Get shareholder point of an account
/// @param account address.
function shareholderPointOf(address account) public view returns (uint256) {
return _shareholderPoints[account];
}
/// @notice Get total shareholder points
function totalShareholderPoint() public view returns (uint256) {
return _totalShareholderPoint;
}
/// @notice Increase shareholder point
/// @param amount The amount to increase.
function _increaseShareholderPoint(address account, uint256 amount) internal {
// If account is burn address then skip
if (account != address(0)) {
_totalShareholderPoint = _totalShareholderPoint.add(amount);
_shareholderPoints[account] = _shareholderPoints[account].add(amount);
emit ShareholderPointIncreased(account, amount, _shareholderPoints[account]);
}
}
/// @notice Decrease shareholder point.
/// @param amount The amount to decrease.
function _decreaseShareholderPoint(address account, uint256 amount) internal {
// If account is burn address then skip
if (account != address(0)) {
_totalShareholderPoint = _totalShareholderPoint.sub(amount);
_shareholderPoints[account] = _shareholderPoints[account] > amount ? _shareholderPoints[account].sub(amount) : 0;
emit ShareholderPointDecreased(account, amount, _shareholderPoints[account]);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16 <0.7.0;
import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol';
/**
* @title StableMath
* @author Stability Labs Pty. Ltd.
* @notice A library providing safe mathematical operations to multiply and
* divide with standardised precision.
* @dev Derives from OpenZeppelin's SafeMath lib and uses generic system
* wide variables for managing precision.
*/
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* @dev bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x.mul(FULL_SCALE);
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x.mul(ratio);
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled.add(RATIO_SCALE.sub(1));
// return 100..00.999e8 / 1e8 = 1e18
return ceil.div(RATIO_SCALE);
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
uint256 y = x.mul(RATIO_SCALE);
// return 1e22 / 1e12 = 1e10
return y.div(ratio);
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
|
Precisely divides two units, by first scaling the left hand operand. Useful for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) x Left hand input to division y Right hand input to division return Result after multiplying the left operand by the scale, and executing the division on the right hand input./ e.g. 8e18 1e18 = 8e36 e.g. 8e36 / 10e18 = 8e17
|
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x.mul(FULL_SCALE);
return z.div(y);
}
| 1,609,632 |
/**
*Submitted for verification at Etherscan.io on 2020-08-26
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.5;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.5;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.5;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.5;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/CornFinance.sol
pragma solidity 0.6.5;
// CornFinance with Governance.
contract CornFinance is ERC20("CornFinance", "CFI"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (CornFarm).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CFI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CFI::delegateBySig: invalid nonce");
require(now <= expiry, "CFI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CFI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CFIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CFI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/CornFarm.sol
pragma solidity 0.6.5;
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to CornSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// CornSwap must mint EXACTLY the same amount of CornSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// CornFarm is the master of Corn. He can make Corn and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once Corn is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract CornFarm is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of Corns
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSfiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSfiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. Corns to distribute per block.
uint256 lastRewardBlock; // Last block number that Sfis distribution occurs.
uint256 accSfiPerShare; // Accumulated CFIs per share, times 1e12. See below.
}
// The CFI TOKEN!
CornFinance public cfi;
// Dev address.
address public devaddr;
// Block number when bonus CFI period ends.
uint256 public bonusEndBlock;
// CFI tokens created per block.
uint256 public cfiPerBlock;
// Bonus muliplier for early CFI makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when CFI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
CornFinance _cfi,
address _devaddr,
uint256 _cfiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
cfi = _cfi;
devaddr = _devaddr;
cfiPerBlock = _cfiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSfiPerShare: 0
}));
}
// Update the given pool's CFI allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending CFIs on frontend.
function pendingSfi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSfiPerShare = pool.accSfiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cfiReward = multiplier.mul(cfiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSfiPerShare = accSfiPerShare.add(cfiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSfiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cfiReward = multiplier.mul(cfiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
cfi.mint(devaddr, cfiReward.div(10));
cfi.mint(address(this), cfiReward);
pool.accSfiPerShare = pool.accSfiPerShare.add(cfiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to CornFarm for CFI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSfiPerShare).div(1e12).sub(user.rewardDebt);
safeSfiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSfiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from CornFarm.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSfiPerShare).div(1e12).sub(user.rewardDebt);
safeSfiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSfiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe cfi transfer function, just in case if rounding error causes pool to not have enough CFIs.
function safeSfiTransfer(address _to, uint256 _amount) internal {
uint256 cfiBal = cfi.balanceOf(address(this));
if (_amount > cfiBal) {
cfi.transfer(_to, cfiBal);
} else {
cfi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CFI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 6,912,722 |
./partial_match/1/0xA1DB57DEFD15Be659CfBC612A13195adf5b237c6/sources/ManaCoin.sol
|
get sell tax details true burn smart lp reflection adding
|
function _transferSell(address sender, address recipient, uint256 amount) private {
uint256 randomTaxType = _generateRandomTaxType();
uint256 taxAmount = amount * sellTax/100;
uint256 sentAmount = amount - taxAmount;
( uint256 treasuryAmount, uint256 burnAmount, uint256 lpAmount, uint256 reflectionAmount ) = _getTaxAmount(taxAmount);
bool canSwap = swapableTreasuryTax >= minTokenSwapAmount;
if(canSwap && !_swapping ) {
_swapping = true;
_swapping = false;
swapableTreasuryTax = swapableTreasuryTax - (minTokenSwapAmount);
}
_balances[sender] = _balances[sender] - (amount);
_balances[recipient] = _balances[recipient] + (sentAmount);
_balances[address(this)] = _balances[address(this)] + (treasuryAmount);
swapableTreasuryTax = swapableTreasuryTax + (treasuryAmount);
if(_balances[sender] == 0) {
}
if (randomTaxType == 1) {
_burn(sender, burnAmount);
emit functionType(randomTaxType, sender, burnAmount);
_takeLP(sender, lpAmount);
emit functionType(randomTaxType, sender, lpAmount);
_balances[address(this)] = _balances[address(this)] + (reflectionAmount);
swapableRefection = swapableRefection + (reflectionAmount);
totalReflected = totalReflected + (reflectionAmount);
emit functionType(randomTaxType, sender, reflectionAmount);
}
emit Transfer(sender, recipient, amount);
}
| 2,771,788 |
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul
// WARNING - `executeActionWithAtomicBatchCalls` has a `bytes[]` argument that
// requires ABIEncoderV2. Exercise caution when calling that specific function.
pragma experimental ABIEncoderV2;
interface DharmaSmartWalletImplementationV1Interface {
event CallSuccess(
bytes32 actionID,
bool rolledBack,
uint256 nonce,
address to,
uint256 value,
bytes data,
bytes returnData
);
event CallFailure(
bytes32 actionID,
uint256 nonce,
address to,
uint256 value,
bytes data,
string revertReason
);
// ABIEncoderV2 uses an array of Calls for executing generic batch calls.
struct Call {
address to;
uint96 value;
bytes data;
}
// ABIEncoderV2 uses an array of CallReturns for handling generic batch calls.
struct CallReturn {
bool ok;
bytes returnData;
}
function withdrawEther(
uint256 amount,
address payable recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function executeAction(
address to,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData);
function recover(address newUserSigningKey) external;
function executeActionWithAtomicBatchCalls(
Call[] calldata calls,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool[] memory ok, bytes[] memory returnData);
function getNextGenericActionID(
address to,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getGenericActionID(
address to,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getNextGenericAtomicBatchActionID(
Call[] calldata calls,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getGenericAtomicBatchActionID(
Call[] calldata calls,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
}
interface DharmaSmartWalletImplementationV3Interface {
event Cancel(uint256 cancelledNonce);
event EthWithdrawal(uint256 amount, address recipient);
}
interface DharmaSmartWalletImplementationV4Interface {
event Escaped();
function setEscapeHatch(
address account,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function removeEscapeHatch(
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function permanentlyDisableEscapeHatch(
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function escape(address token) external;
}
interface DharmaSmartWalletImplementationV7Interface {
// Fires when a new user signing key is set on the smart wallet.
event NewUserSigningKey(address userSigningKey);
// Fires when an error occurs as part of an attempted action.
event ExternalError(address indexed source, string revertReason);
// The smart wallet recognizes DAI, USDC, ETH, and SAI as supported assets.
enum AssetType {
DAI,
USDC,
ETH,
SAI
}
// Actions, or protected methods (i.e. not deposits) each have an action type.
enum ActionType {
Cancel,
SetUserSigningKey,
Generic,
GenericAtomicBatch,
SAIWithdrawal,
USDCWithdrawal,
ETHWithdrawal,
SetEscapeHatch,
RemoveEscapeHatch,
DisableEscapeHatch,
DAIWithdrawal,
SignatureVerification,
TradeEthForDai,
DAIBorrow,
USDCBorrow
}
function initialize(address userSigningKey) external;
function repayAndDeposit() external;
function withdrawDai(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function withdrawUSDC(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function cancel(
uint256 minimumActionGas,
bytes calldata signature
) external;
function setUserSigningKey(
address userSigningKey,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function migrateSaiToDai() external;
function migrateCSaiToDDai() external;
function migrateCDaiToDDai() external;
function migrateCUSDCToDUSDC() external;
function getBalances() external view returns (
uint256 daiBalance,
uint256 usdcBalance,
uint256 etherBalance,
uint256 dDaiUnderlyingDaiBalance,
uint256 dUsdcUnderlyingUsdcBalance,
uint256 dEtherUnderlyingEtherBalance // always returns zero
);
function getUserSigningKey() external view returns (address userSigningKey);
function getNonce() external view returns (uint256 nonce);
function getNextCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getVersion() external pure returns (uint256 version);
}
interface DharmaSmartWalletImplementationV8Interface {
function tradeEthForDaiAndMintDDai(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData);
function getNextEthForDaiActionID(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function getEthForDaiActionID(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
}
interface DharmaSmartWalletImplementationV12Interface {
function setApproval(address token, uint256 amount) external;
}
interface DharmaSmartWalletImplementationV13Interface {
function redeemAllDDai() external;
function redeemAllDUSDC() external;
}
interface ERC20Interface {
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
function allowance(
address owner, address spender
) external view returns (uint256);
}
interface ERC1271Interface {
function isValidSignature(
bytes calldata data, bytes calldata signature
) external view returns (bytes4 magicValue);
}
interface DTokenInterface {
// These external functions trigger accrual on the dToken and backing cToken.
function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted);
function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived);
function redeemUnderlying(uint256 underlyingToReceive) external returns (uint256 dTokensBurned);
// These external functions only trigger accrual on the dToken.
function mintViaCToken(uint256 cTokensToSupply) external returns (uint256 dTokensMinted);
// View and pure functions do not trigger accrual on the dToken or the cToken.
function balanceOfUnderlying(address account) external view returns (uint256 underlyingBalance);
}
interface DharmaKeyRegistryInterface {
function getKey() external view returns (address key);
}
interface DharmaEscapeHatchRegistryInterface {
function setEscapeHatch(address newEscapeHatch) external;
function removeEscapeHatch() external;
function permanentlyDisableEscapeHatch() external;
function getEscapeHatch() external view returns (
bool exists, address escapeHatch
);
}
interface RevertReasonHelperInterface {
function reason(uint256 code) external pure returns (string memory);
}
interface EtherizedInterface {
function triggerEtherTransfer(
address payable target, uint256 value
) external returns (bool success);
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
library ECDSA {
function recover(
bytes32 hash, bytes memory signature
) internal pure returns (address) {
if (signature.length != 65) {
return (address(0));
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
return ecrecover(hash, v, r, s);
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
contract Etherized is EtherizedInterface {
address private constant _ETHERIZER = address(
0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191
);
function triggerEtherTransfer(
address payable target, uint256 amount
) external returns (bool success) {
require(msg.sender == _ETHERIZER, "Etherized: only callable by Etherizer");
(success, ) = target.call.value(amount)("");
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
}
/**
* @title DharmaSmartWalletImplementationV14
* @author 0age
* @notice The V14 implementation for the Dharma smart wallet is a non-custodial,
* meta-transaction-enabled wallet with helper functions to facilitate lending
* funds through Dharma Dai and Dharma USD Coin (which in turn use CompoundV2),
* and with an added security backstop provided by Dharma Labs prior to making
* withdrawals. It adds support for Dharma Dai and Dharma USD Coin - they employ
* the respective cTokens as backing tokens and mint and redeem them internally
* as interest-bearing collateral. This implementation also contains methods to
* support account recovery, escape hatch functionality, and generic actions,
* including in an atomic batch. The smart wallet instances utilizing this
* implementation are deployed through the Dharma Smart Wallet Factory via
* `CREATE2`, which allows for their address to be known ahead of time, and any
* Dai or USDC that has already been sent into that address will automatically
* be deposited into the respective Dharma Token upon deployment of the new
* smart wallet instance. V14 allows for Ether transfers as part of generic
* actions, supports "simulation" of generic batch actions, and revises escape
* hatch functionality to support arbitrary token withdrawals.
*/
contract DharmaSmartWalletImplementationV14 is
DharmaSmartWalletImplementationV1Interface,
DharmaSmartWalletImplementationV3Interface,
DharmaSmartWalletImplementationV4Interface,
DharmaSmartWalletImplementationV7Interface,
DharmaSmartWalletImplementationV8Interface,
DharmaSmartWalletImplementationV12Interface,
DharmaSmartWalletImplementationV13Interface,
ERC1271Interface,
Etherized {
using Address for address;
using ECDSA for bytes32;
// WARNING: DO NOT REMOVE OR REORDER STORAGE WHEN WRITING NEW IMPLEMENTATIONS!
// The user signing key associated with this account is in storage slot 0.
// It is the core differentiator when it comes to the account in question.
address private _userSigningKey;
// The nonce associated with this account is in storage slot 1. Every time a
// signature is submitted, it must have the appropriate nonce, and once it has
// been accepted the nonce will be incremented.
uint256 private _nonce;
// The self-call context flag is in storage slot 2. Some protected functions
// may only be called externally from calls originating from other methods on
// this contract, which enables appropriate exception handling on reverts.
// Any storage should only be set immediately preceding a self-call and should
// be cleared upon entering the protected function being called.
bytes4 internal _selfCallContext;
// END STORAGE DECLARATIONS - DO NOT REMOVE OR REORDER STORAGE ABOVE HERE!
// The smart wallet version will be used when constructing valid signatures.
uint256 internal constant _DHARMA_SMART_WALLET_VERSION = 14;
// DharmaKeyRegistryV2 holds a public key for verifying meta-transactions.
DharmaKeyRegistryInterface internal constant _DHARMA_KEY_REGISTRY = (
DharmaKeyRegistryInterface(0x000000000D38df53b45C5733c7b34000dE0BDF52)
);
// Account recovery is facilitated using a hard-coded recovery manager,
// controlled by Dharma and implementing appropriate timelocks.
address internal constant _ACCOUNT_RECOVERY_MANAGER = address(
0x0000000000DfEd903aD76996FC07BF89C0127B1E
);
// Users can designate an "escape hatch" account with the ability to sweep any
// funds from their smart wallet by using the Dharma Escape Hatch Registry.
DharmaEscapeHatchRegistryInterface internal constant _ESCAPE_HATCH_REGISTRY = (
DharmaEscapeHatchRegistryInterface(0x00000000005280B515004B998a944630B6C663f8)
);
// Interface with dDai and dUSDC contracts.
DTokenInterface internal constant _DDAI = DTokenInterface(
0x00000000001876eB1444c986fD502e618c587430 // mainnet
);
DTokenInterface internal constant _DUSDC = DTokenInterface(
0x00000000008943c65cAf789FFFCF953bE156f6f8 // mainnet
);
// The "revert reason helper" contains a collection of revert reason strings.
RevertReasonHelperInterface internal constant _REVERT_REASON_HELPER = (
RevertReasonHelperInterface(0x9C0ccB765D3f5035f8b5Dd30fE375d5F4997D8E4)
);
// The "Trade Bot" enables limit orders using unordered meta-transactions.
address internal constant _TRADE_BOT = address(
0x8bFB7aC05bF9bDC6Bc3a635d4dd209c8Ba39E554
);
// ERC-1271 must return this magic value when `isValidSignature` is called.
bytes4 internal constant _ERC_1271_MAGIC_VALUE = bytes4(0x20c13b0b);
// Specify the amount of gas to supply when making Ether transfers.
uint256 private constant _ETH_TRANSFER_GAS = 4999;
/**
* @notice Accept Ether in the fallback.
*/
function () external payable {}
/**
* @notice In the initializer, set up the initial user signing key. Note that
* this initializer is only callable while the smart wallet instance is still
* in the contract creation phase.
* @param userSigningKey address The initial user signing key for the smart
* wallet.
*/
function initialize(address userSigningKey) external {
// Ensure that this function is only callable during contract construction.
assembly { if extcodesize(address) { revert(0, 0) } }
// Set up the user's signing key and emit a corresponding event.
_setUserSigningKey(userSigningKey);
}
/**
* @notice Redeem all Dharma Dai held by this account for Dai.
*/
function redeemAllDDai() external {
_withdrawMaxFromDharmaToken(AssetType.DAI);
}
/**
* @notice Redeem all Dharma USD Coin held by this account for USDC.
*/
function redeemAllDUSDC() external {
_withdrawMaxFromDharmaToken(AssetType.USDC);
}
/**
* @notice This call is no longer supported.
*/
function repayAndDeposit() external {
revert("Deprecated.");
}
/**
* @notice This call is no longer supported.
*/
function withdrawDai(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
revert("Deprecated.");
}
/**
* @notice This call is no longer supported.
*/
function withdrawUSDC(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
revert("Deprecated.");
}
/**
* @notice Withdraw Ether to a provided recipient address by transferring it
* to a recipient.
* @param amount uint256 The amount of Ether to withdraw.
* @param recipient address The account to transfer the Ether to.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return True if the transfer succeeded, otherwise false.
*/
function withdrawEther(
uint256 amount,
address payable recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.ETHWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that a non-zero amount of Ether has been supplied.
if (amount == 0) {
revert(_revertReason(4));
}
// Ensure that a non-zero recipient has been supplied.
if (recipient == address(0)) {
revert(_revertReason(1));
}
// Attempt to transfer Ether to the recipient and emit an appropriate event.
ok = _transferETH(recipient, amount);
}
/**
* @notice Allow a signatory to increment the nonce at any point. The current
* nonce needs to be provided as an argument to the signature so as not to
* enable griefing attacks. All arguments can be omitted if called directly.
* No value is returned from this function - it will either succeed or revert.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param signature bytes A signature that resolves to either the public key
* set for this account in storage slot zero, `_userSigningKey`, or the public
* key returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function cancel(
uint256 minimumActionGas,
bytes calldata signature
) external {
// Get the current nonce.
uint256 nonceToCancel = _nonce;
// Ensure the caller or the supplied signature is valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.Cancel,
abi.encode(),
minimumActionGas,
signature,
signature
);
// Emit an event to validate that the nonce is no longer valid.
emit Cancel(nonceToCancel);
}
/**
* @notice This call is no longer supported.
*/
function executeAction(
address to,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData) {
revert("Deprecated.");
}
/**
* @notice Allow signatory to set a new user signing key. The current nonce
* needs to be provided as an argument to the signature so as not to enable
* griefing attacks. No value is returned from this function - it will either
* succeed or revert.
* @param userSigningKey address The new user signing key to set on this smart
* wallet.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function setUserSigningKey(
address userSigningKey,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.SetUserSigningKey,
abi.encode(userSigningKey),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set new user signing key on smart wallet and emit a corresponding event.
_setUserSigningKey(userSigningKey);
}
/**
* @notice Set a dedicated address as the "escape hatch" account. This account
* can then call `escape(address token)` at any point to "sweep" the entire
* balance of the token (or Ether given null address) from the smart wallet.
* This function call will revert if the smart wallet has previously called
* `permanentlyDisableEscapeHatch` at any point and disabled the escape hatch.
* No value is returned from this function - it will either succeed or revert.
* @param account address The account to set as the escape hatch account.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function setEscapeHatch(
address account,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.SetEscapeHatch,
abi.encode(account),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an escape hatch account has been provided.
if (account == address(0)) {
revert(_revertReason(5));
}
// Set a new escape hatch for the smart wallet unless it has been disabled.
_ESCAPE_HATCH_REGISTRY.setEscapeHatch(account);
}
/**
* @notice Remove the "escape hatch" account if one is currently set. This
* function call will revert if the smart wallet has previously called
* `permanentlyDisableEscapeHatch` at any point and disabled the escape hatch.
* No value is returned from this function - it will either succeed or revert.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function removeEscapeHatch(
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.RemoveEscapeHatch,
abi.encode(),
minimumActionGas,
userSignature,
dharmaSignature
);
// Remove the escape hatch for the smart wallet if one is currently set.
_ESCAPE_HATCH_REGISTRY.removeEscapeHatch();
}
/**
* @notice Permanently disable the "escape hatch" mechanism for this smart
* wallet. This function call will revert if the smart wallet has already
* called `permanentlyDisableEscapeHatch` at any point in the past. No value
* is returned from this function - it will either succeed or revert.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function permanentlyDisableEscapeHatch(
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.DisableEscapeHatch,
abi.encode(),
minimumActionGas,
userSignature,
dharmaSignature
);
// Permanently disable the escape hatch mechanism for this smart wallet.
_ESCAPE_HATCH_REGISTRY.permanentlyDisableEscapeHatch();
}
/**
* @notice This call is no longer supported.
*/
function tradeEthForDaiAndMintDDai(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData) {
revert("Deprecated.");
}
/**
* @notice Allow the designated escape hatch account to redeem and "sweep"
* the total token balance or Ether balance (by supplying the null address)
* from the smart wallet. The call will revert for any other caller, or if
* there is no escape hatch account on this smart wallet. An `Escaped` event
* will be emitted. No value is returned from this function - it will either
* succeed or revert.
*/
function escape(address token) external {
// Get the escape hatch account, if one exists, for this account.
(bool exists, address escapeHatch) = _ESCAPE_HATCH_REGISTRY.getEscapeHatch();
// Ensure that an escape hatch is currently set for this smart wallet.
if (!exists) {
revert(_revertReason(6));
}
// Ensure that the escape hatch account is the caller.
if (msg.sender != escapeHatch) {
revert(_revertReason(7));
}
if (token == address(0)) {
// Determine if there is Ether at this address that should be transferred.
uint256 balance = address(this).balance;
if (balance > 0) {
// Attempt to transfer any Ether to caller and emit an appropriate event.
_transferETH(msg.sender, balance);
}
} else {
// Attempt to transfer all tokens to the caller.
_transferMax(ERC20Interface(address(token)), msg.sender, false);
}
// Emit an `Escaped` event.
emit Escaped();
}
/**
* @notice Allow the account recovery manager to set a new user signing key on
* the smart wallet. The call will revert for any other caller. The account
* recovery manager implements a set of controls around the process, including
* a timelock and an option to permanently opt out of account recover. No
* value is returned from this function - it will either succeed or revert.
* @param newUserSigningKey address The new user signing key to set on this
* smart wallet.
*/
function recover(address newUserSigningKey) external {
// Only the Account Recovery Manager contract may call this function.
if (msg.sender != _ACCOUNT_RECOVERY_MANAGER) {
revert(_revertReason(8));
}
// Increment nonce to prevent signature reuse should original key be reset.
_nonce++;
// Set up the user's new dharma key and emit a corresponding event.
_setUserSigningKey(newUserSigningKey);
}
function setApproval(address token, uint256 amount) external {
// Only the Trade Bot contract may call this function.
if (msg.sender != _TRADE_BOT) {
revert("Only the Trade Bot may call this function.");
}
ERC20Interface(token).approve(_TRADE_BOT, amount);
}
/**
* @notice This call is no longer supported.
*/
function migrateSaiToDai() external {
revert("Deprecated.");
}
/**
* @notice This call is no longer supported.
*/
function migrateCSaiToDDai() external {
revert("Deprecated.");
}
/**
* @notice This call is no longer supported.
*/
function migrateCDaiToDDai() external {
revert("Deprecated.");
}
/**
* @notice This call is no longer supported.
*/
function migrateCUSDCToDUSDC() external {
revert("Deprecated.");
}
/**
* @notice This call is no longer supported.
*/
function getBalances() external view returns (
uint256 daiBalance,
uint256 usdcBalance,
uint256 etherBalance,
uint256 dDaiUnderlyingDaiBalance,
uint256 dUsdcUnderlyingUsdcBalance,
uint256 dEtherUnderlyingEtherBalance // always returns 0
) {
revert("Deprecated.");
}
/**
* @notice View function for getting the current user signing key for the
* smart wallet.
* @return The current user signing key.
*/
function getUserSigningKey() external view returns (address userSigningKey) {
userSigningKey = _userSigningKey;
}
/**
* @notice View function for getting the current nonce of the smart wallet.
* This nonce is incremented whenever an action is taken that requires a
* signature and/or a specific caller.
* @return The current nonce.
*/
function getNonce() external view returns (uint256 nonce) {
nonce = _nonce;
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by both the user signing key and by the
* key returned for this smart wallet by the Dharma Key Registry in order to
* construct a valid signature for the corresponding action. Any nonce value
* may be supplied, which enables constructing valid message hashes for
* multiple future actions ahead of time.
* @param action uint8 The type of action, designated by it's index. Valid
* custom actions include Cancel (0), SetUserSigningKey (1),
* DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6),
* SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9).
* @param amount uint256 The amount to withdraw for Withdrawal actions. This
* value is ignored for non-withdrawal action types.
* @param recipient address The account to transfer withdrawn funds to or the
* new user signing key. This value is ignored for Cancel, RemoveEscapeHatch,
* and DisableEscapeHatch action types.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getNextCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
action,
_validateCustomActionTypeAndGetArguments(action, amount, recipient),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by both the user signing key and by the
* key returned for this smart wallet by the Dharma Key Registry in order to
* construct a valid signature for the corresponding action. The current nonce
* will be used, which means that it will only be valid for the next action
* taken.
* @param action uint8 The type of action, designated by it's index. Valid
* custom actions include Cancel (0), SetUserSigningKey (1),
* DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6),
* SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9).
* @param amount uint256 The amount to withdraw for Withdrawal actions. This
* value is ignored for non-withdrawal action types.
* @param recipient address The account to transfer withdrawn funds to or the
* new user signing key. This value is ignored for Cancel, RemoveEscapeHatch,
* and DisableEscapeHatch action types.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
action,
_validateCustomActionTypeAndGetArguments(action, amount, recipient),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice This call is no longer supported.
*/
function getNextGenericActionID(
address to,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
revert("Deprecated.");
}
/**
* @notice This call is no longer supported.
*/
function getGenericActionID(
address to,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
revert("Deprecated.");
}
/**
* @notice This call is no longer supported.
*/
function getNextEthForDaiActionID(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
revert("Deprecated.");
}
/**
* @notice This call is no longer supported.
*/
function getEthForDaiActionID(
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
revert("Deprecated.");
}
/**
* @notice View function that implements ERC-1271 and validates a set of
* signatures, one from the owner (using ERC-1271 as well if the user signing
* key is a contract) and one from the Dharma Key Registry against the
* supplied data. The data must be ABI encoded as (bytes32, bytes), where the
* first bytes32 parameter represents the hash digest for validating the
* supplied signatures and the second bytes parameter contains context for the
* requested validation. The two signatures are packed together, with the one
* from Dharma coming first and that from the user coming second - this is so
* that, in future versions, multiple user signatures may be supplied if the
* associated key ring requires them.
* @param data bytes The data used to validate the signature.
* @param signatures bytes The two signatures, each 65 bytes - one from the
* owner (using ERC-1271 as well if the user signing key is a contract) and
* one from the Dharma Key Registry.
* @return The 4-byte magic value to signify a valid signature in ERC-1271, if
* the signatures are both valid.
*/
function isValidSignature(
bytes calldata data, bytes calldata signatures
) external view returns (bytes4 magicValue) {
// Get message hash digest and any additional context from data argument.
bytes32 digest;
bytes memory context;
if (data.length == 32) {
digest = abi.decode(data, (bytes32));
} else {
if (data.length < 64) {
revert(_revertReason(30));
}
(digest, context) = abi.decode(data, (bytes32, bytes));
}
// Get Dharma signature & user signature from combined signatures argument.
if (signatures.length != 130) {
revert(_revertReason(11));
}
bytes memory signaturesInMemory = signatures;
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signaturesInMemory, 0x20))
s := mload(add(signaturesInMemory, 0x40))
v := byte(0, mload(add(signaturesInMemory, 0x60)))
}
bytes memory dharmaSignature = abi.encodePacked(r, s, v);
assembly {
r := mload(add(signaturesInMemory, 0x61))
s := mload(add(signaturesInMemory, 0x81))
v := byte(0, mload(add(signaturesInMemory, 0xa1)))
}
bytes memory userSignature = abi.encodePacked(r, s, v);
// Validate user signature with `SignatureVerification` as the action type.
if (
!_validateUserSignature(
digest,
ActionType.SignatureVerification,
context,
_userSigningKey,
userSignature
)
) {
revert(_revertReason(12));
}
// Recover Dharma signature against key returned from Dharma Key Registry.
if (_getDharmaSigningKey() != digest.recover(dharmaSignature)) {
revert(_revertReason(13));
}
// Return the ERC-1271 magic value to indicate success.
magicValue = _ERC_1271_MAGIC_VALUE;
}
/**
* @notice View function for getting the current Dharma Smart Wallet
* implementation contract address set on the upgrade beacon.
* @return The current Dharma Smart Wallet implementation contract.
*/
function getImplementation() external view returns (address implementation) {
(bool ok, bytes memory returnData) = address(
0x000000000026750c571ce882B17016557279ADaa
).staticcall("");
require(ok && returnData.length == 32, "Invalid implementation.");
implementation = abi.decode(returnData, (address));
}
/**
* @notice Pure function for getting the current Dharma Smart Wallet version.
* @return The current Dharma Smart Wallet version.
*/
function getVersion() external pure returns (uint256 version) {
version = _DHARMA_SMART_WALLET_VERSION;
}
/**
* @notice Perform a series of generic calls to other contracts. If any call
* fails during execution, the preceding calls will be rolled back, but their
* original return data will still be accessible. Calls that would otherwise
* occur after the failed call will not be executed. Note that accounts with
* no code may not be specified unless value is included, nor may the smart
* wallet itself or the escape hatch registry. In order to increment the nonce
* and invalidate the signatures, a call to this function with valid targets,
* signatutes, and gas will always succeed. To determine whether each call
* made as part of the action was successful or not, either the corresponding
* return value or `CallSuccess` and `CallFailure` events can be used - note
* that even calls that return a success status will be rolled back unless all
* of the calls returned a success status. Finally, note that this function
* must currently be implemented as a public function (instead of as an
* external one) due to an ABIEncoderV2 `UnimplementedFeatureError`.
* @param calls Call[] A struct containing the target, value, and calldata to
* provide when making each call.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return An array of structs signifying the status of each call, as well as
* any data returned from that call. Calls that are not executed will return
* empty data.
*/
function executeActionWithAtomicBatchCalls(
Call[] memory calls,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) public returns (bool[] memory ok, bytes[] memory returnData) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
if (calls[i].value == 0) {
_ensureValidGenericCallTarget(calls[i].to);
}
}
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce(
ActionType.GenericAtomicBatch,
abi.encode(calls),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this contract. However, one of the
// calls may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Specify length of returned values in order to work with them in memory.
ok = new bool[](calls.length);
returnData = new bytes[](calls.length);
// Set self-call context to call _executeActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.executeActionWithAtomicBatchCalls.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool externalOk, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._executeActionWithAtomicBatchCallsAtomic.selector, calls
)
);
// Ensure that self-call context has been cleared.
if (!externalOk) {
delete _selfCallContext;
}
// Parse data returned from self-call into each call result and store / log.
CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[]));
for (uint256 i = 0; i < callResults.length; i++) {
Call memory currentCall = calls[i];
// Set the status and the return data / revert reason from the call.
ok[i] = callResults[i].ok;
returnData[i] = callResults[i].returnData;
// Emit CallSuccess or CallFailure event based on the outcome of the call.
if (callResults[i].ok) {
// Note: while the call succeeded, the action may still have "failed".
emit CallSuccess(
actionID,
!externalOk, // If another call failed this will have been rolled back
nonce,
currentCall.to,
uint256(currentCall.value),
currentCall.data,
callResults[i].returnData
);
} else {
// Note: while the call failed, the nonce will still be incremented,
// which will invalidate all supplied signatures.
emit CallFailure(
actionID,
nonce,
currentCall.to,
uint256(currentCall.value),
currentCall.data,
_decodeRevertReason(callResults[i].returnData)
);
// exit early - any calls after the first failed call will not execute.
break;
}
}
}
/**
* @notice Protected function that can only be called from
* `executeActionWithAtomicBatchCalls` on this contract. It will attempt to
* perform each specified call, populating the array of results as it goes,
* unless a failure occurs, at which point it will revert and "return" the
* array of results as revert data. Otherwise, it will simply return the array
* upon successful completion of each call. Finally, note that this function
* must currently be implemented as a public function (instead of as an
* external one) due to an ABIEncoderV2 `UnimplementedFeatureError`.
* @param calls Call[] A struct containing the target, value, and calldata to
* provide when making each call.
* @return An array of structs signifying the status of each call, as well as
* any data returned from that call. Calls that are not executed will return
* empty data. If any of the calls fail, the array will be returned as revert
* data.
*/
function _executeActionWithAtomicBatchCallsAtomic(
Call[] memory calls
) public returns (CallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.executeActionWithAtomicBatchCalls.selector);
bool rollBack = false;
callResults = new CallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = calls[i].to.call.value(
uint256(calls[i].value)
)(calls[i].data);
callResults[i] = CallReturn({ok: ok, returnData: returnData});
if (!ok) {
// Exit early - any calls after the first failed call will not execute.
rollBack = true;
break;
}
}
if (rollBack) {
// Wrap in length encoding and revert (provide bytes instead of a string).
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
}
/**
* @notice Simulate a series of generic calls to other contracts. Signatures
* are not required, but all calls will be rolled back (and calls will only be
* simulated up until a failing call is encountered).
* @param calls Call[] A struct containing the target, value, and calldata to
* provide when making each call.
* @return An array of structs signifying the status of each call, as well as
* any data returned from that call. Calls that are not executed will return
* empty data.
*/
function simulateActionWithAtomicBatchCalls(
Call[] memory calls
) public /* view */ returns (bool[] memory ok, bytes[] memory returnData) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
if (calls[i].value == 0) {
_ensureValidGenericCallTarget(calls[i].to);
}
}
// Specify length of returned values in order to work with them in memory.
ok = new bool[](calls.length);
returnData = new bytes[](calls.length);
// Set self-call context to call _simulateActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.simulateActionWithAtomicBatchCalls.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool mustBeFalse, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._simulateActionWithAtomicBatchCallsAtomic.selector, calls
)
);
// Note: this should never be the case, but check just to be extra safe.
if (mustBeFalse) {
revert("Simulation call must revert!");
}
// Ensure that self-call context has been cleared.
delete _selfCallContext;
// Parse data returned from self-call into each call result and store / log.
CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[]));
for (uint256 i = 0; i < callResults.length; i++) {
// Set the status and the return data / revert reason from the call.
ok[i] = callResults[i].ok;
returnData[i] = callResults[i].returnData;
if (!callResults[i].ok) {
// exit early - any calls after the first failed call will not execute.
break;
}
}
}
/**
* @notice Protected function that can only be called from
* `simulateActionWithAtomicBatchCalls` on this contract. It will attempt to
* perform each specified call, populating the array of results as it goes,
* unless a failure occurs, at which point it will revert and "return" the
* array of results as revert data. Regardless, it will roll back all calls at
* the end of execution — in other words, this call always reverts.
* @param calls Call[] A struct containing the target, value, and calldata to
* provide when making each call.
* @return An array of structs signifying the status of each call, as well as
* any data returned from that call. Calls that are not executed will return
* empty data. If any of the calls fail, the array will be returned as revert
* data.
*/
function _simulateActionWithAtomicBatchCallsAtomic(
Call[] memory calls
) public returns (CallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.simulateActionWithAtomicBatchCalls.selector);
callResults = new CallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = calls[i].to.call.value(
uint256(calls[i].value)
)(calls[i].data);
callResults[i] = CallReturn({ok: ok, returnData: returnData});
if (!ok) {
// Exit early - any calls after the first failed call will not execute.
break;
}
}
// Wrap in length encoding and revert (provide bytes instead of a string).
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by both the user signing key and by the
* key returned for this smart wallet by the Dharma Key Registry in order to
* construct a valid signature for a given generic atomic batch action. The
* current nonce will be used, which means that it will only be valid for the
* next action taken. Finally, note that this function must currently be
* implemented as a public function (instead of as an external one) due to an
* ABIEncoderV2 `UnimplementedFeatureError`.
* @param calls Call[] A struct containing the target and calldata to provide
* when making each call.
* @param calls Call[] A struct containing the target and calldata to provide
* when making each call.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getNextGenericAtomicBatchActionID(
Call[] memory calls,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.GenericAtomicBatch,
abi.encode(calls),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by both the user signing key and by the
* key returned for this smart wallet by the Dharma Key Registry in order to
* construct a valid signature for a given generic atomic batch action. Any
* nonce value may be supplied, which enables constructing valid message
* hashes for multiple future actions ahead of time. Finally, note that this
* function must currently be implemented as a public function (instead of as
* an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`.
* @param calls Call[] A struct containing the target and calldata to provide
* when making each call.
* @param calls Call[] A struct containing the target and calldata to provide
* when making each call.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getGenericAtomicBatchActionID(
Call[] memory calls,
uint256 nonce,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.GenericAtomicBatch,
abi.encode(calls),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice Internal function for setting a new user signing key. Called by the
* initializer, by the `setUserSigningKey` function, and by the `recover`
* function. A `NewUserSigningKey` event will also be emitted.
* @param userSigningKey address The new user signing key to set on this smart
* wallet.
*/
function _setUserSigningKey(address userSigningKey) internal {
// Ensure that a user signing key is set on this smart wallet.
if (userSigningKey == address(0)) {
revert(_revertReason(14));
}
_userSigningKey = userSigningKey;
emit NewUserSigningKey(userSigningKey);
}
/**
* @notice Internal function for withdrawing the total underlying asset
* balance from the corresponding dToken. Note that the requested balance may
* not be currently available on Compound, which will cause the withdrawal to
* fail.
* @param asset uint256 The asset's ID, either Dai (0) or USDC (1).
*/
function _withdrawMaxFromDharmaToken(AssetType asset) internal {
// Get dToken address for the asset type. (No custom ETH withdrawal action.)
address dToken = asset == AssetType.DAI ? address(_DDAI) : address(_DUSDC);
// Try to retrieve the current dToken balance for this account.
ERC20Interface dTokenBalance;
(bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector(
dTokenBalance.balanceOf.selector, address(this)
));
uint256 redeemAmount = 0;
if (ok && data.length == 32) {
redeemAmount = abi.decode(data, (uint256));
} else {
// Something went wrong with the balance check - log an ExternalError.
_checkDharmaTokenInteractionAndLogAnyErrors(
asset, dTokenBalance.balanceOf.selector, ok, data
);
}
// Only perform the call to redeem if there is a non-zero balance.
if (redeemAmount > 0) {
// Attempt to redeem the underlying balance from the dToken contract.
(ok, data) = dToken.call(abi.encodeWithSelector(
// Function selector is the same for all dTokens, so just use dDai's.
_DDAI.redeem.selector, redeemAmount
));
// Log an external error if something went wrong with the attempt.
_checkDharmaTokenInteractionAndLogAnyErrors(
asset, _DDAI.redeem.selector, ok, data
);
}
}
/**
* @notice Internal function for transferring the total underlying balance of
* the corresponding token to a designated recipient. It will return true if
* tokens were successfully transferred (or there is no balance), signified by
* the boolean returned by the transfer function, or the call status if the
* `suppressRevert` boolean is set to true.
* @param token IERC20 The interface of the token in question.
* @param recipient address The account that will receive the tokens.
* @param suppressRevert bool A boolean indicating whether reverts should be
* suppressed or not. Used by the escape hatch so that a problematic transfer
* will not block the rest of the call from executing.
* @return True if tokens were successfully transferred or if there is no
* balance, else false.
*/
function _transferMax(
ERC20Interface token, address recipient, bool suppressRevert
) internal returns (bool success) {
// Get the current balance on the smart wallet for the supplied ERC20 token.
uint256 balance = 0;
bool balanceCheckWorked = true;
if (!suppressRevert) {
balance = token.balanceOf(address(this));
} else {
// Try to retrieve current token balance for this account with 1/2 gas.
(bool ok, bytes memory data) = address(token).call.gas(gasleft() / 2)(
abi.encodeWithSelector(token.balanceOf.selector, address(this))
);
if (ok && data.length >= 32) {
balance = abi.decode(data, (uint256));
} else {
// Something went wrong with the balance check.
balanceCheckWorked = false;
}
}
// Only perform the call to transfer if there is a non-zero balance.
if (balance > 0) {
if (!suppressRevert) {
// Perform the transfer and pass along the returned boolean (or revert).
success = token.transfer(recipient, balance);
} else {
// Attempt transfer with 1/2 gas, allow reverts, and return call status.
(success, ) = address(token).call.gas(gasleft() / 2)(
abi.encodeWithSelector(token.transfer.selector, recipient, balance)
);
}
} else {
// Skip the transfer and return true as long as the balance check worked.
success = balanceCheckWorked;
}
}
/**
* @notice Internal function for transferring Ether to a designated recipient.
* It will return true and emit an `EthWithdrawal` event if Ether was
* successfully transferred - otherwise, it will return false and emit an
* `ExternalError` event.
* @param recipient address payable The account that will receive the Ether.
* @param amount uint256 The amount of Ether to transfer.
* @return True if Ether was successfully transferred, else false.
*/
function _transferETH(
address payable recipient, uint256 amount
) internal returns (bool success) {
// Attempt to transfer any Ether to caller and emit an event if it fails.
(success, ) = recipient.call.gas(_ETH_TRANSFER_GAS).value(amount)("");
if (!success) {
emit ExternalError(recipient, _revertReason(18));
} else {
emit EthWithdrawal(amount, recipient);
}
}
/**
* @notice Internal function for validating supplied gas (if specified),
* retrieving the signer's public key from the Dharma Key Registry, deriving
* the action ID, validating the provided caller and/or signatures using that
* action ID, and incrementing the nonce. This function serves as the
* entrypoint for all protected "actions" on the smart wallet, and is the only
* area where these functions should revert (other than due to out-of-gas
* errors, which can be guarded against by supplying a minimum action gas
* requirement).
* @param action uint8 The type of action, designated by it's index. Valid
* actions include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5),
* ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and
* DisableEscapeHatch (9).
* @param arguments bytes ABI-encoded arguments for the action.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return The nonce of the current action (prior to incrementing it).
*/
function _validateActionAndIncrementNonce(
ActionType action,
bytes memory arguments,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) internal returns (bytes32 actionID, uint256 actionNonce) {
// Ensure that the current gas exceeds the minimum required action gas.
// This prevents griefing attacks where an attacker can invalidate a
// signature without providing enough gas for the action to succeed. Also
// note that some gas will be spent before this check is reached - supplying
// ~30,000 additional gas should suffice when submitting transactions. To
// skip this requirement, supply zero for the minimumActionGas argument.
if (minimumActionGas != 0) {
if (gasleft() < minimumActionGas) {
revert(_revertReason(19));
}
}
// Get the current nonce for the action to be performed.
actionNonce = _nonce;
// Get the user signing key that will be used to verify their signature.
address userSigningKey = _userSigningKey;
// Get the Dharma signing key that will be used to verify their signature.
address dharmaSigningKey = _getDharmaSigningKey();
// Determine the actionID - this serves as the signature hash.
actionID = _getActionID(
action,
arguments,
actionNonce,
minimumActionGas,
userSigningKey,
dharmaSigningKey
);
// Compute the message hash - the hashed, EIP-191-0x45-prefixed action ID.
bytes32 messageHash = actionID.toEthSignedMessageHash();
// Actions other than Cancel require both signatures; Cancel only needs one.
if (action != ActionType.Cancel) {
// Validate user signing key signature unless it is `msg.sender`.
if (msg.sender != userSigningKey) {
if (
!_validateUserSignature(
messageHash, action, arguments, userSigningKey, userSignature
)
) {
revert(_revertReason(20));
}
}
// Validate Dharma signing key signature unless it is `msg.sender`.
if (msg.sender != dharmaSigningKey) {
if (dharmaSigningKey != messageHash.recover(dharmaSignature)) {
revert(_revertReason(21));
}
}
} else {
// Validate signing key signature unless user or Dharma is `msg.sender`.
if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) {
if (
dharmaSigningKey != messageHash.recover(dharmaSignature) &&
!_validateUserSignature(
messageHash, action, arguments, userSigningKey, userSignature
)
) {
revert(_revertReason(22));
}
}
}
// Increment nonce in order to prevent reuse of signatures after the call.
_nonce++;
}
/**
* @notice Internal function to determine whether a call to a given dToken
* succeeded, and to emit a relevant ExternalError event if it failed.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param functionSelector bytes4 The function selector that was called on the
* corresponding dToken of the asset type.
* @param ok bool A boolean representing whether the call returned or
* reverted.
* @param data bytes The data provided by the returned or reverted call.
* @return True if the interaction was successful, otherwise false. This will
* be used to determine if subsequent steps in the action should be attempted
* or not, specifically a transfer following a withdrawal.
*/
function _checkDharmaTokenInteractionAndLogAnyErrors(
AssetType asset,
bytes4 functionSelector,
bool ok,
bytes memory data
) internal returns (bool success) {
// Log an external error if something went wrong with the attempt.
if (ok) {
if (data.length == 32) {
uint256 amount = abi.decode(data, (uint256));
if (amount > 0) {
success = true;
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_getDharmaTokenDetails(asset, functionSelector)
);
emit ExternalError(
account,
string(
abi.encodePacked(
name,
" gave no tokens calling ",
functionName,
"."
)
)
);
}
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_getDharmaTokenDetails(asset, functionSelector)
);
emit ExternalError(
account,
string(
abi.encodePacked(
name,
" gave bad data calling ",
functionName,
"."
)
)
);
}
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_getDharmaTokenDetails(asset, functionSelector)
);
// Decode the revert reason in the event one was returned.
string memory revertReason = _decodeRevertReason(data);
emit ExternalError(
account,
string(
abi.encodePacked(
name,
" reverted calling ",
functionName,
": ",
revertReason
)
)
);
}
}
/**
* @notice Internal function to ensure that protected functions can only be
* called from this contract and that they have the appropriate context set.
* The self-call context is then cleared. It is used as an additional guard
* against reentrancy, especially once generic actions are supported by the
* smart wallet in future versions.
* @param selfCallContext bytes4 The expected self-call context, equal to the
* function selector of the approved calling function.
*/
function _enforceSelfCallFrom(bytes4 selfCallContext) internal {
// Ensure caller is this contract and self-call context is correctly set.
if (msg.sender != address(this) || _selfCallContext != selfCallContext) {
revert(_revertReason(25));
}
// Clear the self-call context.
delete _selfCallContext;
}
/**
* @notice Internal view function for validating a user's signature. If the
* user's signing key does not have contract code, it will be validated via
* ecrecover; otherwise, it will be validated using ERC-1271, passing the
* message hash that was signed, the action type, and the arguments as data.
* @param messageHash bytes32 The message hash that is signed by the user. It
* is derived by prefixing (according to EIP-191 0x45) and hashing an actionID
* returned from `getCustomActionID`.
* @param action uint8 The type of action, designated by it's index. Valid
* actions include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5),
* ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and
* DisableEscapeHatch (9).
* @param arguments bytes ABI-encoded arguments for the action.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used.
* @return A boolean representing the validity of the supplied user signature.
*/
function _validateUserSignature(
bytes32 messageHash,
ActionType action,
bytes memory arguments,
address userSigningKey,
bytes memory userSignature
) internal view returns (bool valid) {
if (!userSigningKey.isContract()) {
valid = userSigningKey == messageHash.recover(userSignature);
} else {
bytes memory data = abi.encode(messageHash, action, arguments);
valid = (
ERC1271Interface(userSigningKey).isValidSignature(
data, userSignature
) == _ERC_1271_MAGIC_VALUE
);
}
}
/**
* @notice Internal view function to get the Dharma signing key for the smart
* wallet from the Dharma Key Registry. This key can be set for each specific
* smart wallet - if none has been set, a global fallback key will be used.
* @return The address of the Dharma signing key, or public key corresponding
* to the secondary signer.
*/
function _getDharmaSigningKey() internal view returns (
address dharmaSigningKey
) {
dharmaSigningKey = _DHARMA_KEY_REGISTRY.getKey();
}
/**
* @notice Internal view function that, given an action type and arguments,
* will return the action ID or message hash that will need to be prefixed
* (according to EIP-191 0x45), hashed, and signed by the key designated by
* the Dharma Key Registry in order to construct a valid signature for the
* corresponding action. The current nonce will be supplied to this function
* when reconstructing an action ID during protected function execution based
* on the supplied parameters.
* @param action uint8 The type of action, designated by it's index. Valid
* actions include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5),
* ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and
* DisableEscapeHatch (9).
* @param arguments bytes ABI-encoded arguments for the action.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param dharmaSigningKey address The address of the secondary key, or public
* key corresponding to the secondary signer.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function _getActionID(
ActionType action,
bytes memory arguments,
uint256 nonce,
uint256 minimumActionGas,
address userSigningKey,
address dharmaSigningKey
) internal view returns (bytes32 actionID) {
// actionID is constructed according to EIP-191-0x45 to prevent replays.
actionID = keccak256(
abi.encodePacked(
address(this),
_DHARMA_SMART_WALLET_VERSION,
userSigningKey,
dharmaSigningKey,
nonce,
minimumActionGas,
action,
arguments
)
);
}
/**
* @notice Internal pure function to get the dToken address, it's name, and
* the name of the called function, based on a supplied asset type and
* function selector. It is used to help construct ExternalError events.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param functionSelector bytes4 The function selector that was called on the
* corresponding dToken of the asset type.
* @return The dToken address, it's name, and the name of the called function.
*/
function _getDharmaTokenDetails(
AssetType asset,
bytes4 functionSelector
) internal pure returns (
address account,
string memory name,
string memory functionName
) {
if (asset == AssetType.DAI) {
account = address(_DDAI);
name = "Dharma Dai";
} else {
account = address(_DUSDC);
name = "Dharma USD Coin";
}
// Note: since both dTokens have the same interface, just use dDai's.
if (functionSelector == _DDAI.mint.selector) {
functionName = "mint";
} else {
if (functionSelector == ERC20Interface(account).balanceOf.selector) {
functionName = "balanceOf";
} else {
functionName = string(abi.encodePacked(
"redeem",
functionSelector == _DDAI.redeem.selector ? "" : "Underlying"
));
}
}
}
/**
* @notice Internal view function to ensure that a given `to` address provided
* as part of a generic action is valid. Calls cannot be performed to accounts
* without code or back into the smart wallet itself. Additionally, generic
* calls cannot supply the address of the Dharma Escape Hatch registry - the
* specific, designated functions must be used in order to make calls into it.
* @param to address The address that will be targeted by the generic call.
*/
function _ensureValidGenericCallTarget(address to) internal view {
if (!to.isContract()) {
revert(_revertReason(26));
}
if (to == address(this)) {
revert(_revertReason(27));
}
if (to == address(_ESCAPE_HATCH_REGISTRY)) {
revert(_revertReason(28));
}
}
/**
* @notice Internal pure function to ensure that a given action type is a
* "custom" action type (i.e. is not a generic action type) and to construct
* the "arguments" input to an actionID based on that action type.
* @param action uint8 The type of action, designated by it's index. Valid
* custom actions include Cancel (0), SetUserSigningKey (1),
* DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6),
* SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9).
* @param amount uint256 The amount to withdraw for Withdrawal actions. This
* value is ignored for all non-withdrawal action types.
* @param recipient address The account to transfer withdrawn funds to or the
* new user signing key. This value is ignored for Cancel, RemoveEscapeHatch,
* and DisableEscapeHatch action types.
* @return A bytes array containing the arguments that will be provided as
* a component of the inputs when constructing a custom action ID.
*/
function _validateCustomActionTypeAndGetArguments(
ActionType action, uint256 amount, address recipient
) internal pure returns (bytes memory arguments) {
// Ensure that the action type is a valid custom action type.
bool validActionType = (
action == ActionType.Cancel ||
action == ActionType.SetUserSigningKey ||
action == ActionType.DAIWithdrawal ||
action == ActionType.USDCWithdrawal ||
action == ActionType.ETHWithdrawal ||
action == ActionType.SetEscapeHatch ||
action == ActionType.RemoveEscapeHatch ||
action == ActionType.DisableEscapeHatch
);
if (!validActionType) {
revert(_revertReason(29));
}
// Use action type to determine parameters to include in returned arguments.
if (
action == ActionType.Cancel ||
action == ActionType.RemoveEscapeHatch ||
action == ActionType.DisableEscapeHatch
) {
// Ignore parameters for Cancel, RemoveEscapeHatch, or DisableEscapeHatch.
arguments = abi.encode();
} else if (
action == ActionType.SetUserSigningKey ||
action == ActionType.SetEscapeHatch
) {
// Ignore `amount` parameter for other, non-withdrawal actions.
arguments = abi.encode(recipient);
} else {
// Use both `amount` and `recipient` parameters for withdrawals.
arguments = abi.encode(amount, recipient);
}
}
/**
* @notice Internal pure function to decode revert reasons. The revert reason
* prefix is removed and the remaining string argument is decoded.
* @param revertData bytes The raw data supplied alongside the revert.
* @return The decoded revert reason string.
*/
function _decodeRevertReason(
bytes memory revertData
) internal pure returns (string memory revertReason) {
// Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector
if (
revertData.length > 68 && // prefix (4) + position (32) + length (32)
revertData[0] == byte(0x08) &&
revertData[1] == byte(0xc3) &&
revertData[2] == byte(0x79) &&
revertData[3] == byte(0xa0)
) {
// Get the revert reason without the prefix from the revert data.
bytes memory revertReasonBytes = new bytes(revertData.length - 4);
for (uint256 i = 4; i < revertData.length; i++) {
revertReasonBytes[i - 4] = revertData[i];
}
// Decode the resultant revert reason as a string.
revertReason = abi.decode(revertReasonBytes, (string));
} else {
// Simply return the default, with no revert reason.
revertReason = _revertReason(uint256(-1));
}
}
/**
* @notice Internal pure function call the revert reason helper contract,
* supplying a revert "code" and receiving back a revert reason string.
* @param code uint256 The code for the revert reason.
* @return The revert reason string.
*/
function _revertReason(
uint256 code
) internal pure returns (string memory reason) {
reason = _REVERT_REASON_HELPER.reason(code);
}
}
|
Allow the account recovery manager to set a new user signing key on the smart wallet. The call will revert for any other caller. The account recovery manager implements a set of controls around the process, including a timelock and an option to permanently opt out of account recover. No value is returned from this function - it will either succeed or revert. newUserSigningKey address The new user signing key to set on this smart wallet./ Only the Account Recovery Manager contract may call this function.
|
function recover(address newUserSigningKey) external {
if (msg.sender != _ACCOUNT_RECOVERY_MANAGER) {
revert(_revertReason(8));
}
}
| 2,135,521 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.10;
import {RolesAuthority} from "solmate/auth/authorities/RolesAuthority.sol";
import {SSTORE2} from "solmate/utils/SSTORE2.sol";
// Radicle DripsHub imports
import {ERC20Reserve} from "radicle-drips-hub/ERC20Reserve.sol";
import {ERC20DripsHub} from "radicle-drips-hub/ERC20DripsHub.sol";
import {ManagedDripsHubProxy} from "radicle-drips-hub/ManagedDripsHub.sol";
import {IDripsHub} from "./IDripsHub.sol";
import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol";
/// @notice Workstreams contract. Enables organizations and individuals to compensate contributors.
/// @author Odysseas Lamtzidis (odyslam.eth)
contract Workstreams {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a new workstream is created.
/// @param org The org address that created the event.
/// @param workstreamId The Id of the workstream.
event WorkstreamCreated(address indexed org, address workstreamId);
event ERC20DripsHubCreated(address tokenAddress);
/*///////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
uint64 public constant CYCLE_SECS = 7 days;
address public admin;
uint256 public constant BASE_UNIT = 10e18;
mapping(address => address) public workstreamIdToOrgAddress;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor() {
admin = msg.sender;
}
function initCommonDripsHubs(
IDripsHub daiHub,
IDripsHub usdtHub,
IDripsHub usdcHub,
IDripsHub wethHub
) external {
require(
address(daiDripsHub) == address(0),
"Workstreams::initCommonDripsHubs::already_initialized"
);
erc20TokensLibrary[address(daiHub.erc20())] = daiHub;
daiDripsHub = daiHub;
erc20TokensLibrary[address(usdtHub.erc20())] = usdtHub;
erc20TokensLibrary[address(usdcHub.erc20())] = usdcHub;
erc20TokensLibrary[address(wethHub.erc20())] = wethHub;
}
/*///////////////////////////////////////////////////////////////
WORKSTREAMS UTILITIES
//////////////////////////////////////////////////////////////*/
/// @notice Stores the workstream information using the SSTORE2 method. Read more information in:
/// https://github.com/0xsequence/sstore2/ . We use the solmate implementation.
/// @param anchor The project_id and commit hash where the workstream proposal
/// got accepted by the Org for a particular RFP.
/// @param workstreamType The type of Workstream. One of: 0: DAI, 1: ERC20, 2: ETH
/// @param org The org to which the workstream belongs to.
/// @param account The account of the drip. Every address can have different drips, one per account.
/// Read more about accounts in: https://github.com/radicle-dev/radicle-drips-hub/blob/master/src/DripsHub.sol
/// @param lastTimestamp The last block.timestamp at which the drip got updated.
/// @param newBalance The new balance of the drip that will be "dripped" to the drip receivers.
/// @param newReceivers The new receivers of the drip. It's a struct that encapsulates both the address
/// of the receivers and the amount per second that they receive.
/// @param hub The drips hub contract instance.
/// @return workstreamId The unique identification of this workstream, required to retrieve and update it.
function _storeWorkstream(
string memory anchor,
uint8 workstreamType,
address org,
uint256 account,
uint64 lastTimestamp,
int128 newBalance,
IDripsHub.DripsReceiver[] memory newReceivers,
IDripsHub hub
) internal returns (address) {
return
SSTORE2.write(
abi.encode(
anchor,
workstreamType,
org,
account,
lastTimestamp,
newBalance,
newReceivers,
hub
)
);
}
/// @notice Load the workstream from the SSTORE2 storage. Read more about this in _storeWorkstream.
/// @param key The address that is used as a key to load the data from storage. It returns the data passed with
/// _storeWorkstream.
function loadWorkstream(address key)
public
view
returns (
string memory,
uint8,
address,
uint256,
uint64,
uint128,
IDripsHub.DripsReceiver[] memory,
IDripsHub
)
{
return
abi.decode(
SSTORE2.read(key),
(
string,
uint8,
address,
uint256,
uint64,
uint128,
IDripsHub.DripsReceiver[],
IDripsHub
)
);
}
/*///////////////////////////////////////////////////////////////
ERC20 WORKSTREAMS
//////////////////////////////////////////////////////////////*/
/// @notice Stores the dripshub for each erc20 token that has been registered to workstreams.
mapping(address => IDripsHub) public erc20TokensLibrary;
/// @notice Create a new workstream with an ERC20 drip. Read more about this on createDaiWorkstream().
function createERC20Workstream(
address orgAddress,
string calldata anchor,
address[] calldata workstreamMembers,
uint128[] calldata amountsPerSecond,
uint128 initialAmount,
address erc20
) external returns (address) {
IDripsHub erc20Hub = erc20TokensLibrary[erc20];
require(
address(erc20Hub) != address(0),
"Workstreams::createERC20Workstream::no_hub_with_erc20"
);
IERC20(erc20).transferFrom(
msg.sender,
address(this),
uint256(initialAmount)
);
IERC20(erc20).approve(address(erc20Hub), uint256(initialAmount));
IDripsHub.DripsReceiver[] memory formattedReceivers = _receivers(
workstreamMembers,
amountsPerSecond
);
address workstreamId = fundWorkstreamERC20(
address(0),
anchor,
orgAddress,
0,
formattedReceivers,
int128(initialAmount),
erc20Hub
);
workstreamIdToOrgAddress[workstreamId] = orgAddress;
return workstreamId;
}
function fundWorkstreamERC20(
address workstreamId,
string memory anchor,
address org,
uint256 account,
IDripsHub.DripsReceiver[] memory newReceivers,
int128 amount,
IDripsHub erc20Hub
) public returns (address) {
if (workstreamId == address(0)) {
IDripsHub.DripsReceiver[] memory oldReceivers;
// Currently, the workstream contract is the single user that owns all drips
erc20Hub.setDrips(
account,
0,
0,
oldReceivers,
amount,
newReceivers
);
} else {
_internalFundERC20(workstreamId, amount, newReceivers);
}
return
_storeWorkstream(
anchor,
1,
org,
account,
uint64(block.timestamp),
amount,
newReceivers,
erc20Hub
);
}
function _internalFundERC20(
address workstreamId,
int128 amount,
IDripsHub.DripsReceiver[] memory newReceivers
) internal {
IDripsHub.DripsReceiver[] memory oldReceivers;
uint64 lastTimestamp;
uint128 balance;
address org;
uint256 account;
IDripsHub erc20Hub;
(
,
,
org,
account,
lastTimestamp,
balance,
oldReceivers,
erc20Hub
) = loadWorkstream(workstreamId);
account++;
IERC20 erc20 = erc20Hub.erc20();
erc20.transferFrom(msg.sender, address(this), uint256(balance));
erc20.approve(address(erc20Hub), uint256(balance));
erc20Hub.setDrips(
account,
lastTimestamp,
balance,
oldReceivers,
amount,
newReceivers
);
}
/*///////////////////////////////////////////////////////////////
DAI WORKSTREAMS
//////////////////////////////////////////////////////////////*/
IDripsHub daiDripsHub;
/// @notice Create a new workstream with a DAI drip.
/// @param orgAddress The address which is the owner of the workstream.
/// @param anchor The project_id and commit hash where the workstream proposal
/// got accepted by the Org for a particular RFP. Structure: "radicleProjectURN_at_commitHash"
/// Example: rad:git:hnrkmzko1nps1pjogxadcmqipfxpeqn6xbeto_at_a4b88fed911c96ef5cadf60b461f7024ff967985
/// @param workstreamMembers The initial members of the workstreams. Addresses should be ordered.
/// @param amountsPerSecond The amount per second that each address should receive from the workstream.
/// @param initialAmount The initial amount that the workstream creator funds the workstream with.
/// @param permitArgs EIP712-compatible arguments struct which permits and moves funds from the workstream creator
/// to the workstream drip.
/// @return The workstreamId, used to retrieve information later and update the workstream.
function createDaiWorkstream(
address orgAddress,
string calldata anchor,
address[] calldata workstreamMembers,
uint128[] calldata amountsPerSecond,
uint128 initialAmount,
IDripsHub.PermitArgs calldata permitArgs
) external returns (address) {
IDripsHub.DripsReceiver[] memory formattedReceivers = _receivers(
workstreamMembers,
amountsPerSecond
);
address workstreamId = fundWorkstreamDai(
address(0),
anchor,
orgAddress,
0,
formattedReceivers,
int128(initialAmount),
permitArgs
);
workstreamIdToOrgAddress[workstreamId] = orgAddress;
return workstreamId;
}
/// @notice Fund a workstream. If it's the first time, it also serves as initialization of the workstream object.
/// @param workstreamId The workstream Id is required to retrieve information about the workstream.
/// @param anchor The projectId and commit hash of the proposal to the project's canonical repository.
/// @param org The org owner of the workstream.
/// @param account The org's account the workstream's drip in the main DripsHub smart contract.
/// @param newReceivers The updated struct of the receivers and their respective amount-per-second.
/// @param amount The new amount that will fund this workstream's drip.
/// @param permitArgs The permitArgs used to permit and move the required DAI from the orgAddress to the drip.
/// @return It returns the new workstream Id for this particular workstream.
function fundWorkstreamDai(
address workstreamId,
string memory anchor,
address org,
uint256 account,
IDripsHub.DripsReceiver[] memory newReceivers,
int128 amount,
IDripsHub.PermitArgs calldata permitArgs
) public returns (address) {
if (workstreamId == address(0)) {
IDripsHub.DripsReceiver[] memory oldReceivers;
daiDripsHub.setDripsAndPermit(
account,
0,
0,
oldReceivers,
amount,
newReceivers,
permitArgs
);
} else {
_internalFundDai(workstreamId, amount, newReceivers, permitArgs);
}
return
_storeWorkstream(
anchor,
1,
org,
account,
uint64(block.timestamp),
amount,
newReceivers,
daiDripsHub
);
}
/// @notice Internal function that is used to break up fundWorkstreamDai and bypass the 'stack too deep' error.
/// For the parameters read the fundWorkstreamDai function.
function _internalFundDai(
address workstreamId,
int128 amount,
IDripsHub.DripsReceiver[] memory newReceivers,
IDripsHub.PermitArgs calldata permitArgs
) internal {
IDripsHub.DripsReceiver[] memory oldReceivers;
uint64 lastTimestamp;
uint128 balance;
address org;
uint256 account;
(
,
,
org,
account,
lastTimestamp,
balance,
oldReceivers,
) = loadWorkstream(workstreamId);
account++;
daiDripsHub.setDripsAndPermit(
account,
lastTimestamp,
balance,
oldReceivers,
amount,
newReceivers,
permitArgs
);
}
/// @notice Internal function that constructs the receivers struct from two arrays of receivers and
/// amounts-per-second.
/// @param receiversAddresses An ordered array of addresses.
/// @param amountsPerSecond Amount of funds that should be dripped to the corresponding address
/// defined in the receiversAddresses parameter.
/// @return formattedReceivers The final struct that is cominbes the params and
/// is required by the DripsHub smart contract.
function _receivers(
address[] calldata receiversAddresses,
uint128[] memory amountsPerSecond
) internal view returns (IDripsHub.DripsReceiver[] memory) {
IDripsHub.DripsReceiver[]
memory formattedReceivers = new IDripsHub.DripsReceiver[](
receiversAddresses.length
);
for (uint256 i; i < receiversAddresses.length; i++) {
formattedReceivers[i] = IDripsHub.DripsReceiver(
receiversAddresses[i],
amountsPerSecond[i]
);
}
return formattedReceivers;
}
}
|
Internal function that constructs the receivers struct from two arrays of receivers and amounts-per-second. receiversAddresses An ordered array of addresses. amountsPerSecond Amount of funds that should be dripped to the corresponding address defined in the receiversAddresses parameter. return formattedReceivers The final struct that is cominbes the params and is required by the DripsHub smart contract.
|
function _receivers(
address[] calldata receiversAddresses,
uint128[] memory amountsPerSecond
) internal view returns (IDripsHub.DripsReceiver[] memory) {
IDripsHub.DripsReceiver[]
memory formattedReceivers = new IDripsHub.DripsReceiver[](
receiversAddresses.length
);
for (uint256 i; i < receiversAddresses.length; i++) {
formattedReceivers[i] = IDripsHub.DripsReceiver(
receiversAddresses[i],
amountsPerSecond[i]
);
}
return formattedReceivers;
}
| 15,802,323 |
pragma solidity ^0.4.13;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) 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) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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) returns (bool) {
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) constant 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)) 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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove 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.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
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 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint _value) public {
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
event Burn(address indexed burner, uint indexed value);
}
/**
* @title WTF Token Network Token
* @dev ERC20 WTF Token Network Token (WTF)
*
* WTF Tokens are divisible by 1e8 (100,000,000) base
* units referred to as 'Grains'.
*
* WTF are displayed using 8 decimal places of precision.
*
* 1 WTF is equivalent to:
* 100000000 == 1 * 10**8 == 1e8 == One Hundred Million Grains
*
* 10 Million WTF (total supply) is equivalent to:
* 1000000000000000 == 10000000 * 10**8 == 1e15 == One Quadrillion Grains
*
* All initial WTF Grains are assigned to the creator of
* this contract.
*
*/
contract WTFToken is BurnableToken, Pausable {
string public constant name = 'WTF Token'; // Set the token name for display
string public constant symbol = 'WTF'; // Set the token symbol for display
uint8 public constant decimals = 8; // Set the number of decimals for display
uint256 constant INITIAL_SUPPLY = 10000000 * 10**uint256(decimals); // 10 Million WTF specified in Grains
uint256 public sellPrice;
mapping(address => uint256) bonuses;
uint8 public freezingPercentage;
uint32 public constant unfreezingTimestamp = 1530403200; // 2018, July, 1, 00:00:00 UTC
/**
* @dev WTFToken Constructor
* Runs only on initial contract creation.
*/
function WTFToken() {
totalSupply = INITIAL_SUPPLY; // Set the total supply
balances[msg.sender] = INITIAL_SUPPLY; // Creator address is assigned all
sellPrice = 0;
freezingPercentage = 100;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return super.balanceOf(_owner) - bonuses[_owner] * freezingPercentage / 100;
}
/**
* @dev Transfer token for a specified address when not paused
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) whenNotPaused returns (bool) {
require(_to != address(0));
require(balances[msg.sender] - bonuses[msg.sender] * freezingPercentage / 100 >= _value);
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens and bonus tokens to a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _bonus The bonus amount.
*/
function transferWithBonuses(address _to, uint256 _value, uint256 _bonus) onlyOwner returns (bool) {
require(_to != address(0));
require(balances[msg.sender] - bonuses[msg.sender] * freezingPercentage / 100 >= _value + _bonus);
bonuses[_to] = bonuses[_to].add(_bonus);
return super.transfer(_to, _value + _bonus);
}
/**
* @dev Check the frozen bonus balance
* @param _owner The address to check the balance of.
*/
function bonusesOf(address _owner) constant returns (uint256 balance) {
return bonuses[_owner] * freezingPercentage / 100;
}
/**
* @dev Unfreezing part of bonus tokens by owner
* @param _percentage uint8 Percentage of bonus tokens to be left frozen
*/
function setFreezingPercentage(uint8 _percentage) onlyOwner returns (bool) {
require(_percentage < freezingPercentage);
require(now < unfreezingTimestamp);
freezingPercentage = _percentage;
return true;
}
/**
* @dev Unfreeze all bonus tokens
*/
function unfreezeBonuses() returns (bool) {
require(now >= unfreezingTimestamp);
freezingPercentage = 0;
return true;
}
/**
* @dev Transfer tokens from one address to another when not paused
* @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) whenNotPaused returns (bool) {
require(_to != address(0));
require(balances[_from] - bonuses[_from] * freezingPercentage / 100 >= _value);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender when not paused.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
/**
* @dev Gets the purchase price of tokens by contract
*/
function getPrice() constant returns (uint256 _sellPrice) {
return sellPrice;
}
/**
* @dev Sets the purchase price of tokens by contract
* @param newSellPrice New purchase price
*/
function setPrice(uint256 newSellPrice) external onlyOwner returns (bool success) {
require(newSellPrice > 0);
sellPrice = newSellPrice;
return true;
}
/**
* @dev Buying ethereum for tokens
* @param amount Number of tokens
*/
function sell(uint256 amount) external returns (uint256 revenue){
require(balances[msg.sender] - bonuses[msg.sender] * freezingPercentage / 100 >= amount); // Checks if the sender has enough to sell
balances[this] = balances[this].add(amount); // Adds the amount to owner's balance
balances[msg.sender] = balances[msg.sender].sub(amount); // Subtracts the amount from seller's balance
revenue = amount.mul(sellPrice); // Calculate the seller reward
msg.sender.transfer(revenue); // Sends ether to the seller: it's important to do this last to prevent recursion attacks
Transfer(msg.sender, this, amount); // Executes an event reflecting on the change
return revenue; // Ends function and returns
}
/**
* @dev Allows you to get tokens from the contract
* @param amount Number of tokens
*/
function getTokens(uint256 amount) onlyOwner external returns (bool success) {
require(balances[this] >= amount);
balances[msg.sender] = balances[msg.sender].add(amount);
balances[this] = balances[this].sub(amount);
Transfer(this, msg.sender, amount);
return true;
}
/**
* @dev Allows you to put Ethereum to the smart contract
*/
function sendEther() payable onlyOwner external returns (bool success) {
return true;
}
/**
* @dev Allows you to get ethereum from the contract
* @param amount Number of tokens
*/
function getEther(uint256 amount) onlyOwner external returns (bool success) {
require(amount > 0);
msg.sender.transfer(amount);
return true;
}
}
|
WTFToken Constructor Runs only on initial contract creation./
|
function WTFToken() {
sellPrice = 0;
freezingPercentage = 100;
}
| 7,020,155 |
./full_match/4/0x30E26CcfE3895ec62F93dAD47c3958E3C0Bbf29e/sources/gist-c2dd952f7525e468792bcc1defdec8df/contract_flat.sol
|
Authorize someone other than the owner to change the sales status
|
function authorizeSalesAdmin(address admin) external onlyOwner{
authAdmin=admin;
}
| 12,497,015 |
./full_match/5/0x0fc7602A26221f998D7C08F307c3146Ee4Af3182/sources/contracts/Tribe.sol
|
Overrides the `_transfer` function of the ERC721 standard/
|
function _transfer(address from, address to, uint256 tokenId) internal virtual override {}
| 1,941,180 |
./full_match/1/0x2FDebA51baC8041A33d180A33B5503F1663111A5/sources/eth_bot_for_all.sol
|
Specific code for a simple swap and a multihop (2 swaps in sequence)
|
function multihopBatchSwapExactOut(
Swap[][] memory swapSequences,
TokenInterface tokenIn,
TokenInterface tokenOut,
uint maxTotalAmountIn
)
public payable
returns(uint totalAmountIn)
{
transferFromAll(tokenIn, maxTotalAmountIn);
for (uint i = 0; i < swapSequences.length; i++) {
uint tokenAmountInFirstSwap;
if (swapSequences[i].length == 1) {
Swap memory swap = swapSequences[i][0];
TokenInterface SwapTokenIn = TokenInterface(swap.tokenIn);
PoolInterface pool = PoolInterface(swap.pool);
if (SwapTokenIn.allowance(address(this), swap.pool) > 0) {
SwapTokenIn.approve(swap.pool, 0);
}
SwapTokenIn.approve(swap.pool, swap.limitReturnAmount);
(tokenAmountInFirstSwap,) = pool.swapExactAmountOut(
swap.tokenIn,
swap.limitReturnAmount,
swap.tokenOut,
swap.swapAmount,
swap.maxPrice
);
PoolInterface poolSecondSwap = PoolInterface(secondSwap.pool);
intermediateTokenAmount = poolSecondSwap.calcInGivenOut(
poolSecondSwap.getBalance(secondSwap.tokenIn),
poolSecondSwap.getDenormalizedWeight(secondSwap.tokenIn),
poolSecondSwap.getBalance(secondSwap.tokenOut),
poolSecondSwap.getDenormalizedWeight(secondSwap.tokenOut),
secondSwap.swapAmount,
poolSecondSwap.getSwapFee()
);
TokenInterface FirstSwapTokenIn = TokenInterface(firstSwap.tokenIn);
PoolInterface poolFirstSwap = PoolInterface(firstSwap.pool);
if (FirstSwapTokenIn.allowance(address(this), firstSwap.pool) < uint(-1)) {
FirstSwapTokenIn.approve(firstSwap.pool, uint(-1));
}
(tokenAmountInFirstSwap,) = poolFirstSwap.swapExactAmountOut(
firstSwap.tokenIn,
firstSwap.limitReturnAmount,
firstSwap.tokenOut,
firstSwap.maxPrice
);
if (SecondSwapTokenIn.allowance(address(this), secondSwap.pool) < uint(-1)) {
SecondSwapTokenIn.approve(secondSwap.pool, uint(-1));
}
poolSecondSwap.swapExactAmountOut(
secondSwap.tokenIn,
secondSwap.limitReturnAmount,
secondSwap.tokenOut,
secondSwap.swapAmount,
secondSwap.maxPrice
);
}
totalAmountIn = tokenAmountInFirstSwap.add(totalAmountIn);
}
require(totalAmountIn <= maxTotalAmountIn, "ERR_LIMIT_IN");
transferAll(tokenOut, getBalance(tokenOut));
transferAll(tokenIn, getBalance(tokenIn));
}
| 16,433,292 |
./full_match/1/0x4B4Fa17F83c09873cb5b4e0023f25d4f533Fc9Ba/sources/contracts/BasedGold.sol
|
door deze functie per aparte loop te callen (sell / buy / transfer) verkoopt sell tx ook eigen feeTokens + mogelijkheid om 0 fees van slechts 1 soort te hebben
|
function ProcessFees(address from, uint256 amount, uint256 marketingTokens, uint256 devTokens) private returns(uint256) {
unchecked {
if (distributeTokens) {
amount = amount - marketingTokens - devTokens;
_balances[marketingWallet] += marketingTokens;
emit Transfer(from, marketingWallet, marketingTokens);
_balances[devWallet] += devTokens;
emit Transfer(from, devWallet, devTokens);
accMarketingFee += marketingTokens;
accDevFee += devTokens;
uint256 fees = marketingTokens + devTokens;
amount -= fees;
_balances[address(this)] += fees;
emit Transfer(from, address(this), fees);
}
return amount;
}
unchecked {
if (distributeTokens) {
amount = amount - marketingTokens - devTokens;
_balances[marketingWallet] += marketingTokens;
emit Transfer(from, marketingWallet, marketingTokens);
_balances[devWallet] += devTokens;
emit Transfer(from, devWallet, devTokens);
accMarketingFee += marketingTokens;
accDevFee += devTokens;
uint256 fees = marketingTokens + devTokens;
amount -= fees;
_balances[address(this)] += fees;
emit Transfer(from, address(this), fees);
}
return amount;
}
} else {
}
| 16,565,284 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.